diff options
99 files changed, 9294 insertions, 6549 deletions
diff --git a/.clang-format b/.clang-format new file mode 100644 index 0000000..d3ca92c --- /dev/null +++ b/.clang-format @@ -0,0 +1,35 @@ +--- +AlignConsecutiveAssignments: true +AlignConsecutiveDeclarations: true +AlignEscapedNewlines: Left +AttributeMacros: + - ZIX_MALLOC_FUNC + - ZIX_PURE_FUNC +BasedOnStyle: Mozilla +BraceWrapping: + AfterNamespace: false + AfterClass: true + AfterEnum: false + AfterExternBlock: false + AfterFunction: true + AfterStruct: false + SplitEmptyFunction: false + SplitEmptyRecord: false +BreakBeforeBraces: Custom +Cpp11BracedListStyle: true +FixNamespaceComments: true +ForEachMacros: + - LILV_FOREACH + - LV2_ATOM_OBJECT_BODY_FOREACH + - LV2_ATOM_OBJECT_FOREACH + - LV2_ATOM_SEQUENCE_BODY_FOREACH + - LV2_ATOM_SEQUENCE_FOREACH + - LV2_ATOM_TUPLE_BODY_FOREACH + - LV2_ATOM_TUPLE_FOREACH +IndentCaseLabels: false +IndentPPDirectives: AfterHash +KeepEmptyLinesAtTheStartOfBlocks: false +SpacesInContainerLiterals: false +StatementMacros: + - Q_OBJECT +... diff --git a/.clang-tidy b/.clang-tidy new file mode 100644 index 0000000..dd52ffc --- /dev/null +++ b/.clang-tidy @@ -0,0 +1,48 @@ +Checks: > + *, + -*-c-arrays, + -*-macro-to-enum, + -*-magic-numbers, + -*-named-parameter, + -*-narrowing-conversions, + -altera-*, + -boost-*, + -bugprone-assignment-in-if-condition, + -bugprone-casting-through-void, + -bugprone-easily-swappable-parameters, + -bugprone-multi-level-implicit-pointer-conversion, + -cert-err33-c, + -cert-err34-c, + -clang-analyzer-optin.core.EnumCastOutOfRange, + -clang-analyzer-security.insecureAPI.DeprecatedOrUnsafeBufferHandling, + -clang-analyzer-valist.Uninitialized, + -concurrency-mt-unsafe, + -cppcoreguidelines-avoid-non-const-global-variables, + -cppcoreguidelines-macro-usage, + -cppcoreguidelines-owning-memory, + -cppcoreguidelines-pro-bounds-pointer-arithmetic, + -cppcoreguidelines-pro-type-reinterpret-cast, + -fuchsia-default-arguments-calls, + -google-readability-todo, + -hicpp-signed-bitwise, + -llvm-header-guard, + -llvmlibc-*, + -misc-include-cleaner, + -misc-no-recursion, + -modernize-use-nodiscard, + -modernize-use-trailing-return-type, + -modernize-use-using, + -performance-enum-size, + -readability-function-cognitive-complexity, + -readability-identifier-length, + -readability-implicit-bool-conversion, + -readability-redundant-casting, + -readability-static-accessed-through-instance, +CheckOptions: + - key: hicpp-uppercase-literal-suffix.NewSuffixes + value: 'L;U;UL;ULL' + - key: readability-uppercase-literal-suffix.NewSuffixes + value: 'L;U;UL;ULL' +WarningsAsErrors: '*' +HeaderFilterRegex: '.*' +FormatStyle: file diff --git a/.clant.json b/.clant.json new file mode 100644 index 0000000..8347642 --- /dev/null +++ b/.clant.json @@ -0,0 +1,4 @@ +{ + "version": "1.0.0", + "mapping_files": [".includes.imp", "qt5_11.imp"] +} @@ -1 +1,13 @@ -__pycache__ +# Copyright 2019-2025 David Robillard <d@drobilla.net> +# SPDX-License-Identifier: 0BSD OR ISC + +/build/ +/subprojects/lilv-0.24.26/ +/subprojects/lv2/ +/subprojects/packagecache/ +/subprojects/serd/ +/subprojects/sord-0.16.18/ +/subprojects/sphinxygen-1.0.10/ +/subprojects/sratom-0.6.18/ +/subprojects/suil-0.10.22/ +/subprojects/zix-0.6.2/ diff --git a/.gitmodules b/.gitmodules deleted file mode 100644 index 0ebe4f2..0000000 --- a/.gitmodules +++ /dev/null @@ -1,3 +0,0 @@ -[submodule "waflib"] - path = waflib - url = ../autowaf diff --git a/.includes.imp b/.includes.imp new file mode 100644 index 0000000..9ec9064 --- /dev/null +++ b/.includes.imp @@ -0,0 +1,7 @@ +[ + { "symbol": [ "QT_VERSION", "private", "<QtGlobal>", "public" ] }, + { "symbol": [ "QT_VERSION_CHECK", "private", "<QtGlobal>", "public" ] }, + { "symbol": [ "Q_OBJECT", "private", "<QObject>", "public" ] }, + { "symbol": [ "Q_SLOT", "private", "<QObject>", "public" ] }, + { "symbol": [ "qMax", "private", "<QtGlobal>", "public" ] } +] diff --git a/.reuse/dep5 b/.reuse/dep5 new file mode 100644 index 0000000..5888ff3 --- /dev/null +++ b/.reuse/dep5 @@ -0,0 +1,12 @@ +Format: https://www.debian.org/doc/packaging-manuals/copyright-format/1.0/ +Upstream-Name: jalv +Upstream-Contact: David Robillard <d@drobilla.net> +Source: https://gitlab.com/drobilla/jalv + +Files: .clang* .clant.json .gitignore .includes.imp .suppress.cppcheck AUTHORS NEWS jalv.desktop.in jalv.ttl +Copyright: 2010-2022 David Robillard <d@drobilla.net> +License: 0BSD OR ISC + +Files: INSTALL.md README.md doc/*.1 +Copyright: 2011-2020 David Robillard <d@drobilla.net> +License: ISC diff --git a/.suppress.cppcheck b/.suppress.cppcheck new file mode 100644 index 0000000..db432cb --- /dev/null +++ b/.suppress.cppcheck @@ -0,0 +1,3 @@ +cstyleCast +normalCheckLevelMaxBranches +unusedStructMember @@ -1,14 +1,20 @@ Author: David Robillard <d@drobilla.net> -Original GTK2 Generic Plugin UI: +Original GTK generic UI: Nick Lanham <nick@afternight.org> -Various UI improvements: +JACK latency support and other improvements: Robin Gareus <robin@gareus.org> Preset menu support for Qt: Timo Westkämper <timo.westkamper@gmail.com> -Qt4 Generic Plugin UI: +Original Qt generic UI: Amadeus Folego <amadeusfolego@gmail.com> + +GTK plugin selector UI: + Alexandros Theodotou <alex@zrythm.org> + +Original man pages: + Jaromír Mikes <mira.mikes@seznam.cz> @@ -1,13 +1,13 @@ -Copyright 2011-2019 David Robillard <http://drobilla.net> +Copyright 2011-2022 David Robillard <d@drobilla.net> Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby granted, provided that the above copyright notice and this permission notice appear in all copies. -THIS SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES -WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF -MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR -ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES -WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN -ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF -OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. +THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH +REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND +FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, +INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM +LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR +OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR +PERFORMANCE OF THIS SOFTWARE. diff --git a/INSTALL b/INSTALL deleted file mode 100644 index 623cddd..0000000 --- a/INSTALL +++ /dev/null @@ -1,59 +0,0 @@ -Installation Instructions -========================= - -Basic Installation ------------------- - -Building this software requires only Python. To install with default options: - - ./waf configure - ./waf - ./waf install - -You may need to become root for the install stage, for example: - - sudo ./waf install - -Configuration Options ---------------------- - -All supported options can be viewed using the command: - - ./waf --help - -Most options only need to be passed during the configure stage, for example: - - ./waf configure --prefix=/usr - ./waf - ./waf install - -Compiler Configuration ----------------------- - -Several standard environment variables can be used to control how compilers are -invoked: - - * CC: Path to C compiler - * CFLAGS: C compiler options - * CXX: Path to C++ compiler - * CXXFLAGS: C++ compiler options - * CPPFLAGS: C preprocessor options - * LINKFLAGS: Linker options - -Installation Directories ------------------------- - -The --prefix option (or the PREFIX environment variable) can be used to change -the prefix which all files are installed under. There are also several options -allowing for more fine-tuned control, see the --help output for details. - -Packaging ---------- - -Everything can be installed to a specific root directory by passing a --destdir -option to the install stage (or setting the DESTDIR environment variable), -which adds a prefix to all install paths. For example: - - ./waf configure --prefix=/usr - ./waf - ./waf install --destdir=/tmp/package diff --git a/INSTALL.md b/INSTALL.md new file mode 100644 index 0000000..37ec9e8 --- /dev/null +++ b/INSTALL.md @@ -0,0 +1,76 @@ +Installation Instructions +========================= + +Prerequisites +------------- + +To build from source, you will need: + + * A relatively modern C compiler (GCC, Clang, and MSVC are known to work). + + * [Meson](http://mesonbuild.com/), which depends on + [Python](http://python.org/). + +This is a brief overview of building this project with meson. See the meson +documentation for more detailed information. + +Configuration +------------- + +The build is configured with the `setup` command, which creates a new build +directory with the given name: + + meson setup build + +Some environment variables are read during `setup` and stored with the +configuration: + + * `CC`: Path to C compiler. + * `CFLAGS`: C compiler options. + * `CXX`: Path to C++ compiler. + * `CXXFLAGS`: C++ compiler options. + * `LDFLAGS`: Linker options. + +However, it is better to use meson options for configuration. All options can +be inspected with the `configure` command from within the build directory: + + cd build + meson configure + +Options can be set by passing C-style "define" options to `configure`: + + meson configure -Dc_args="-march=native" -Dprefix="/opt/mypackage/" + +Note that some options, such as `strict` and `werror` are for +developer/maintainer use only. Please don't file issues about anything that +happens when they are enabled. + +Building +-------- + +From within a configured build directory, everything can be built with the +`compile` command: + + meson compile + +Similarly, tests can be run with the `test` command: + + meson test + +Meson can also generate a project for several popular IDEs, see the `backend` +option for details. + +Installation +------------ + +A compiled project can be installed with the `install` command: + + meson install + +You may need to acquire root permissions to install to a system-wide prefix. +For packaging, the installation may be staged to a directory using the +`DESTDIR` environment variable or the `--destdir` option: + + DESTDIR=/tmp/mypackage/ meson install + + meson install --destdir=/tmp/mypackage/ diff --git a/LICENSES/0BSD.txt b/LICENSES/0BSD.txt new file mode 100644 index 0000000..b3e8cfd --- /dev/null +++ b/LICENSES/0BSD.txt @@ -0,0 +1,12 @@ +Copyright 2011-2022 David Robillard <d@drobilla.net> + +Permission to use, copy, modify, and/or distribute this software for any +purpose with or without fee is hereby granted. + +THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH +REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND +FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, +INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM +LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR +OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR +PERFORMANCE OF THIS SOFTWARE. diff --git a/LICENSES/ISC.txt b/LICENSES/ISC.txt new file mode 120000 index 0000000..012065c --- /dev/null +++ b/LICENSES/ISC.txt @@ -0,0 +1 @@ +../COPYING
\ No newline at end of file @@ -1,11 +1,76 @@ -jalv (1.6.4) stable; +jalv (1.6.9) unstable; urgency=medium + + * Add Qt6 version + * Add missing short versions of command line options + * Add option to install tool man pages + * Add support for control outputs with lv2:latency designation + * Build Qt UI with -fPIC + * Clean up and strengthen code + * Clean up command line help output + * Cleanly separate audio thread from the rest of the application + * Fix Jack latency recomputation when plugin latency changes + * Fix clashing command line options + * Fix minor memory leaks + * Make help and version commands exit successfully + * Only send control messages to designated lv2:control ports + * Reduce Jack process callback overhead + * Remove Gtk2 interface + * Remove limits on the size of messages sent from plugin to UI + * Remove transport position dumping from Jack process callback + * Replace use of deprecated Gtk interfaces + * Rewrite man pages in mdoc + * Switch to external zix dependency + * Use Gtk switches instead of checkboxes for toggle controls + * Use fewer platform-specific APIs + * Use portable zix filesystem API + + -- David Robillard <d@drobilla.net> Fri, 20 Dec 2024 00:45:28 +0000 + +jalv (1.6.8) stable; urgency=medium + + * Add Gtk plugin selector UI and desktop file + * Add missing option in console help output + * Add version option to console executable + * Build Qt interface as C++14 + * Change no-menu short option to m to avoid clash with jack-name + * Clean up and modernize code + * Fix "preset" console command when "presets" hasn't been called + * Fix MSVC build + * Fix atom buffer alignment + * Fix crash when running jalv without arguments + * Fix man page headers + * Fix memory leaks + * Fix outdated man pages + * Fix spurious transport messages + * Fix thread-safety of plugin/UI communication rings + * Flush stdout after printing control values in console interface + * Print status information consistently to stdout + * Propagate worker errors to the scheduler when possible + * Remove Gtkmm interface + * Remove Qt4 support + * Support both rdfs:label and lv2:name for port group labels + * Switch to meson build system + + -- David Robillard <d@drobilla.net> Sat, 10 Sep 2022 00:43:05 +0000 + +jalv (1.6.6) stable; urgency=medium + + * Add a command line argument to select a specific UI + * Explicitly support lv2:inPlaceBroken + * Ignore ports with nonsense lv2:control designations + * Remove Jack session support + * Support port events for ui:showInterface UIs + + -- David Robillard <d@drobilla.net> Thu, 07 Jan 2021 22:05:38 +0000 + +jalv (1.6.4) stable; urgency=medium * Support rdfs:label for port groups * Use screen refresh rate with Gtk3 and Qt5 - -- David Robillard <d@drobilla.net> Sun, 10 Nov 2019 22:56:49 +0100 + -- David Robillard <d@drobilla.net> Sun, 10 Nov 2019 21:56:49 +0000 -jalv (1.6.2) stable; +jalv (1.6.2) stable; urgency=medium * Add jalv -i option to ignore stdin for background use * Add several commands to console interface @@ -21,7 +86,7 @@ jalv (1.6.2) stable; -- David Robillard <d@drobilla.net> Thu, 06 Jun 2019 20:38:01 +0000 -jalv (1.6.0) stable; +jalv (1.6.0) stable; urgency=medium * Add PortAudio backend (compile time option, audio only) * Add Qt5 version @@ -47,7 +112,7 @@ jalv (1.6.0) stable; -- David Robillard <d@drobilla.net> Wed, 04 Jan 2017 17:24:58 +0000 -jalv (1.4.6) stable; +jalv (1.4.6) stable; urgency=medium * Add option to print control output changes to stdout * Add support for data-access extension (based on patch by Filipe Coelho) @@ -62,7 +127,7 @@ jalv (1.4.6) stable; -- David Robillard <d@drobilla.net> Fri, 08 Aug 2014 22:30:28 +0000 -jalv (1.4.4) stable; +jalv (1.4.4) stable; urgency=medium * Add --no-menu option for jalv.gtk * Add -c option for setting controls from the command line @@ -75,7 +140,7 @@ jalv (1.4.4) stable; -- David Robillard <d@drobilla.net> Sat, 04 Jan 2014 21:11:45 +0000 -jalv (1.4.2) stable; +jalv (1.4.2) stable; urgency=medium * Add command-line option to control UI update frequency * Fix crash when running "jalv" with bad command line arguments @@ -90,7 +155,7 @@ jalv (1.4.2) stable; -- David Robillard <d@drobilla.net> Fri, 09 Aug 2013 14:40:20 +0000 -jalv (1.4.0) stable; +jalv (1.4.0) stable; urgency=medium * Add menu bar and pass parent widget in Qt version for true UI embedding * Add spinbuttons for precisely setting control values @@ -103,7 +168,7 @@ jalv (1.4.0) stable; -- David Robillard <d@drobilla.net> Sat, 23 Feb 2013 03:35:22 +0000 -jalv (1.2.0) stable; +jalv (1.2.0) stable; urgency=medium * Add Gtk3 UI * Fix Jack Session support @@ -119,7 +184,7 @@ jalv (1.2.0) stable; -- David Robillard <d@drobilla.net> Sun, 14 Oct 2012 22:38:53 +0000 -jalv (1.0.0) stable; +jalv (1.0.0) stable; urgency=medium * Initial release @@ -1,19 +1,19 @@ Jalv ==== -Jalv is a simple but fully featured LV2 host for Jack which exposes plugin -ports to Jack, essentially making any LV2 plugin function as a Jack -application. -For more information, see <http://drobilla.net/software/jalv>. +Jalv (JAck LV2) is a simple host for LV2 plugins. It runs a plugin, and +exposes the plugin ports to the system, essentially making the plugin an +application. For more information, see <http://drobilla.net/software/jalv>. -Jalv is a small program which is useful, but also intended to be an appropriate -test host for plugin development. It runs plugins from the command line with -no user interaction, is light enough to run in valgrind, and is capable of -dumping all communication between the plugin and its UI in a human readable -format. +Jalv can be built to run on JACK, where plugin ports are exposed directly as +JACK ports, or via PortAudio, where the plugin is connected to the system +inputs and outputs. -To make it simple to test plugins in hosts that use different toolkits, there -are several Jalv executables: jalv, jalv.gtk, jalv.gtk3, jalv.gtkmm, jalv.qt4, -and jalv.qt5. +Jalv is particularly useful as a simple test host for plugin development and +testing. It runs plugins from the command line with no user interaction, is +light enough to run with tools like sanitizers or valgrind, and is capable of +dumping all communication between the plugin and its UI in a human readable +format. Plugin UIs can be tested in different host toolkits by using different +executables: jalv, jalv.gtk, jalv.gtk3, and jalv.qt5. -- David Robillard <d@drobilla.net> @@ -1,85 +1,125 @@ -.TH JALV 1 "18 Feb 2017" - -.SH NAME -.B jalv \- Run an LV2 plugin as a JACK application (console version). - -.SH SYNOPSIS -.B jalv [OPTION]... PLUGIN_URI - -.SH OPTIONS - -.TP -\fB\-b SIZE\fR -Buffer size for plugin <=> UI communication. - -.TP -\fB\-c SYM=VAL\fR -Set control value (e.g. "vol=1.4"). - -.TP -\fB\-d\fR -Dump plugin <=> UI communication. - -.TP -\fB\-h\fR -Print the command line options. - -.TP -\fB\-i\fR -Ignore input on stdin (for background use). - -.TP -\fB\-l DIR\fR -Load state from state directory. - -.TP -\fB\-n NAME\fR -Jack client name - -.TP -\fB\-p\fR -Print control output changes to stdout. - -.TP -\fB\-s\fR +.\" # Copyright 2024 David Robillard <d@drobilla.net> +.\" # SPDX-License-Identifier: ISC +.Dd December 20, 2024 +.Dt JALV 1 +.Os +.Sh NAME +.Nm jalv +.Nd run an LV2 plugin with a command-line interface +.Sh SYNOPSIS +.Nm jalv +.Op Fl dhipstx +.Op Fl b Ar size +.Op Fl c Ar symbol=value +.Op Fl U Ar ui_uri +.Op Fl l Ar dir +.Op Fl n Ar name +.Ar plugin_uri +.Sh DESCRIPTION +.Nm +is a simple LV2 host that runs one plugin. +It has several versions, this one has an interactive command-line interface. +.Pp +.Nm +has one positional argument, the URI of an installed LV2 plugin. +.Pp +The options are as follows: +.Bl -tag -width 3n +.It Fl b Ar bytes +Buffer size for communication between plugin and UI. +The default value should be enough, +but if there are overflows, +this option can be used to allocate more space. +.It Fl c Ar symbol=value +Set control value, for example, +.Fl c Ar vol=1.4 +where +.Dq vol +is the symbol of a control port on the plugin. +.It Fl d +Dump communication between plugin and UI to +.Dv stdout . +Note that this may print an extreme amount of text, +piping the output to a pager or file is recommended. +.It Fl h +Print the command line options and exit. +.It Fl i +Ignore input on +.Dv stdin +and run non-interactively. +.It Fl l Ar dir +Load state from the given directory before running the plugin. +.It Fl n Ar name +Use the given JACK client name. +Note that JACK may adjust the name if necessary unless +.Fl x +is also given. +.It Fl p +Print control output changes to +.Dv stdout . +.It Fl s Show plugin UI if possible. - -This option only works when plugins provide a UI that is usable via the non-embeddable showHide interface. For other, embeddable UIs, use jalv.gtk(1) or jalv.qt(1). - -.TP -\fB\-t\fR -Print trace messages from plugin - -.TP -\fB\-u UUID\fR -UUID for Jack session restoration. - -.TP -\fB\-x\fR -Use only exact Jack client name, and exit if it is taken - -.SH COMMANDS - +This option only works when plugins provide a UI that uses the non-embeddable +.Li showHide +interface. +For embeddable UIs, use +.Xr jalv.gtk3 1 +instead. +.It Fl t +Print trace messages from plugin. +This enables the +.Dq trace +log defined by LV2, which is used by some plugins to print debugging output. +.It Fl U Ar uri +Load the UI with the given URI. +Usually only one suitable UI is available on a given platform, +which is used by default. +If there are several, this option can be used to select which is loaded. +.It Fl V +Print version information and exit. +.It Fl x +Use only the exact JACK client name given by +.Fl n +or exit if it's unavailable. +.El +.Sh COMMANDS The Jalv prompt supports several commands for interactive control: - - \fBhelp\fR Display help message - \fBcontrols\fR Print settable control values - \fBmonitors\fR Print output control values - \fBpresets\fR Print available presets - \fBpreset URI\fR Set preset - \fBset INDEX VALUE\fR Set control value by port index - \fBset SYMBOL VALUE\fR Set control value by symbol - \fBSYMBOL = VALUE\fR Set control value by symbol - -.SH "SEE ALSO" -.BR jalv.gtk(1), -.BR jalv.gtkmm(1), -.BR jalv.qt(2), -.BR lv2ls(1), -.BR jackd(1) - -.SH AUTHOR -jalv was written by David Robillard <d@drobilla.net> -.PP -This manual page was written by Jaromír Mikes <mira.mikes@seznam.cz> -and David Robillard <d@drobilla.net> +.Pp +.Bl -tag -width 16n -compact +.It Ic help +Display help message. +.It Ic controls +Print settable control values. +.It Ic monitors +Print output control values. +.It Ic presets +Print available presets. +.It Ic preset Ar uri +Set preset. +.It Ic set index value +Set control value by port index. +.It Ic set Ar symbol Ar value +Set control value by symbol. +.It Ar symbol Cm = Ar value +Set control value by symbol. +.El +.Sh ENVIRONMENT +.Bl -tag -width LV2_PATH +.It Ev LV2_PATH +Search path for LV2 bundles, in +.Ev PATH +format. +.El +.Sh SEE ALSO +.Xr jalv.gtk3 1 , +.Xr jalv.qt5 1 , +.Xr lv2ls 1 +.Sh AUTHORS +.Nm +was written by +.An David Robillard +.Aq Mt d@drobilla.net , +with contributions by +Robin Gareus, +Hanspeter Portner, +and others. diff --git a/doc/jalv.gtk.1 b/doc/jalv.gtk.1 deleted file mode 100644 index 5177e1d..0000000 --- a/doc/jalv.gtk.1 +++ /dev/null @@ -1,58 +0,0 @@ -.TH JALV.GTK "18 Feb 2017" - -.SH NAME -.B jalv.gtk \- Run an LV2 plugin as a JACK application (Gtk version). - -.SH SYNOPSIS -.B jalv.gtk [OPTION]... PLUGIN_URI - -.SH OPTIONS - -.TP -\fB\-b SIZE\fR -Buffer size for plugin <=> UI communication. - -.TP -\fB\-c SYM=VAL\fR -Set control value (e.g. "vol=1.4"). - -.TP -\fB\-d\fR, \fB\-\-dump\fR -Dump plugin <=> UI communication. - -.TP -\fB\-g\fR, \fB\-\-generic\-ui\fR -Use Jalv generic UI and not the plugin UI. - -.TP -\fB\-h\fR, \fB\-\-help\fR -Print the command line options. - -.TP -\fB\-l DIR\fR, \fB\-\-load DIR\fR -Load state from state directory. - -.TP -\fB\-p\fR, \fB\-\-print\-controls\fR -Print control output changes to stdout. - -.TP -\fB\-t\fR, \fB\-\-trace\fR -Print trace messages from plugin. - -.TP -\fB\-u UUID\fR, \fB\-\-uuid UUID\fR -UUID for Jack session restoration. - -.SH "SEE ALSO" -.BR jalv(1), -.BR jalv.gtkmm(1), -.BR jalv.qt(2), -.BR lv2ls(1), -.BR jackd(1) - -.SH AUTHOR -jalv was written by David Robillard <d@drobilla.net> -.PP -This manual page was written by Jaromír Mikes <mira.mikes@seznam.cz> -and David Robillard <d@drobilla.net> diff --git a/doc/jalv.gtk3.1 b/doc/jalv.gtk3.1 new file mode 100644 index 0000000..953c5b0 --- /dev/null +++ b/doc/jalv.gtk3.1 @@ -0,0 +1,101 @@ +.\" # Copyright 2024 David Robillard <d@drobilla.net> +.\" # SPDX-License-Identifier: ISC +.Dd December 20, 2024 +.Dt JALV.GTK3 1 +.Os +.Sh NAME +.Nm jalv.gtk3 +.Nd run an LV2 plugin with a GTK3 interface +.Sh SYNOPSIS +.Nm jalv.gtk3 +.Op Fl dghmpstx +.Op Fl b , Fl Fl buffer-size Ns = Ns Ar size +.Op Fl c , Fl Fl control Ns = Ns Ar setting +.Op Fl l , Fl Fl load Ns = Ns Ar dir +.Op Fl n , Fl Fl jack-name Ns = Ns Ar name +.Op Fl P , Fl Fl preset Ns = Ns Ar uri +.Op Fl r , Fl Fl update-frequency Ns = Ns Ar hz +.Op Fl S , Fl Fl scale-factor Ns = Ns Ar scale +.Op Fl U , Fl Fl ui-uri Ns = Ns Ar uri +.Ar plugin_uri +.Sh DESCRIPTION +.Nm +is a simple LV2 host that runs a single plugin. +This version has a GTK3 interface that shows either generic controls or a custom plugin GUI. +.Pp +The options are as follows: +.Bl -tag -width 3n +.It Fl b Ar size +Buffer size for plugin <=> UI communication. +.It Fl c Ar symbol=value +Set control value, for example, +.Fl c Ar vol=1.4 +where +.Dq vol +is the symbol of some control port on the plugin. +.It Fl d +Dump plugin <=> UI communication. +.It Fl g +Show generic UI instead of custom plugin GUI. +.It Fl h +Print the command line options. +.It Fl l Ar dir +Load state from the given directory before running the plugin. +.It Fl m +Hide application menu, showing only the plugin interface. +.It Fl n Ar name +Use the given JACK client name. +Note that JACK may adjust the name if necessary unless +.Fl x +is also given. +.It Fl P uri +Load the given preset before running plugin. +.It Fl p +Print control output changes to +.Dv stdout . +.It Fl r Ar hz +Set the UI update frequency. +By default the screen refresh rate is used, typically 30 or 60 Hz. +.It Fl S Ar factor +Override the UI scale factor. +.It Fl s +Show controls that are normally hidden. +.It Fl t +Print trace messages from plugin. +.It Fl U +URI Load the UI with the given URI. +.It Fl x +Use only the exact JACK client name given by +.Fl n +or exit if it's unavailable. +.El +.Sh COMMANDS +The Jalv prompt supports several commands for interactive control: +.Pp +.Bl -tag -width 16n -compact +.It Ic help +Display help message. +.It Ic controls +Print settable control values. +.It Ic monitors +Print output control values. +.It Ic presets +Print available presets. +.It Ic preset Ar uri +Set preset. +.It Ic set index value +Set control value by port index. +.It Ic set Ar symbol Ar value +Set control value by symbol. +.It Ar SYMBOL Cm = Ar VALUE +Set control value by symbol. +.El +.Sh SEE ALSO +.Xr jalv 1 , +.Xr jalv.qt5 1 +.Sh AUTHORS +jalv was written by +.An David Robillard +.Aq Mt d@drobilla.net +with contributions by others. +Most of the GTK interface was added by Alexandros Theodotou and Nick Lanham. diff --git a/doc/jalv.gtkmm.1 b/doc/jalv.gtkmm.1 deleted file mode 100644 index 2a6ce01..0000000 --- a/doc/jalv.gtkmm.1 +++ /dev/null @@ -1,25 +0,0 @@ -.TH JALV.GTKMM 1 "19 Apr 2012" - -.SH NAME -.B jalv.gtkmm \- Run an LV2 plugin as a JACK application (Gtkmm version). - -.SH SYNOPSIS -.B jalv.gtkmm PLUGIN_URI - -.SH DESCRIPTION - -This is a version of Jalv with a GUI implemented in Gtkmm. It is mainly for -developer testing purposes, for a production ready program use jalv.gtk. - -.SH "SEE ALSO" -.BR jalv(1), -.BR jalv.gtk(1), -.BR jalv.qt(2), -.BR lv2ls(1), -.BR jackd(1) - -.SH AUTHOR -jalv was written by David Robillard <d@drobilla.net> -.PP -This manual page was written by Jaromír Mikes <mira.mikes@seznam.cz> -and David Robillard <d@drobilla.net> diff --git a/doc/jalv.qt.1 b/doc/jalv.qt.1 deleted file mode 100644 index 352835d..0000000 --- a/doc/jalv.qt.1 +++ /dev/null @@ -1,25 +0,0 @@ -.TH JALV.QT 1 "19 Apr 2012" - -.SH NAME -.B jalv.qt \- Run an LV2 plugin as a JACK application (Qt version). - -.SH SYNOPSIS -.B jalv.qt PLUGIN_URI - -.SH DESCRIPTION - -This is a version of Jalv with a GUI implemented in Qt. It is mainly for -developer testing purposes, for a production ready program use jalv.gtk. - -.SH "SEE ALSO" -.BR jalv(1), -.BR jalv.gtkmm(1), -.BR jalv.qt(2), -.BR lv2ls(1), -.BR jackd(1) - -.SH AUTHOR -jalv was written by David Robillard <d@drobilla.net> -.PP -This manual page was written by Jaromír Mikes <mira.mikes@seznam.cz> -and David Robillard <d@drobilla.net> diff --git a/doc/jalv.qt5.1 b/doc/jalv.qt5.1 new file mode 100644 index 0000000..578dab4 --- /dev/null +++ b/doc/jalv.qt5.1 @@ -0,0 +1,29 @@ +.\" # Copyright 2024 David Robillard <d@drobilla.net> +.\" # SPDX-License-Identifier: ISC +.Dd December 20, 2024 +.Dt JALV.QT5 1 +.Os +.Sh NAME +.Nm jalv.qt5 +.Nd run an LV2 plugin with a Qt5 interface +.Sh SYNOPSIS +.Nm jalv.qt5 +.Ar plugin_uri +.Sh DESCRIPTION +.Nm +is a simple LV2 host that runs a single plugin. +This version has a Qt5 interface that shows either generic controls or a custom plugin GUI. +.Pp +This version has no options and requires the plugin URI to be given on the command line. +For a fully graphical version with a plugin selector, see +.Xr jalv.gtk3 1 . +.Sh SEE ALSO +.Xr jalv 1 , +.Xr jalv.gtk3 1 , +.Xr lv2ls 1 +.Sh AUTHORS +jalv was written by +.An David Robillard +.Aq Mt d@drobilla.net +with contributions by others. +Most of the Qt interface was added by Amadeus Folego and Timo Westkämper. diff --git a/doc/jalv.qt6.1 b/doc/jalv.qt6.1 new file mode 100644 index 0000000..6b80b2c --- /dev/null +++ b/doc/jalv.qt6.1 @@ -0,0 +1,29 @@ +.\" # Copyright 2024 David Robillard <d@drobilla.net> +.\" # SPDX-License-Identifier: ISC +.Dd December 20, 2024 +.Dt JALV.QT6 1 +.Os +.Sh NAME +.Nm jalv.qt6 +.Nd run an LV2 plugin with a Qt6 interface +.Sh SYNOPSIS +.Nm jalv.qt6 +.Ar plugin_uri +.Sh DESCRIPTION +.Nm +is a simple LV2 host that runs a single plugin. +This version has a Qt6 interface that shows either generic controls or a custom plugin GUI. +.Pp +This version has no options and requires the plugin URI to be given on the command line. +For a fully graphical version with a plugin selector, see +.Xr jalv.gtk3 1 . +.Sh SEE ALSO +.Xr jalv 1 , +.Xr jalv.gtk3 1 , +.Xr lv2ls 1 +.Sh AUTHORS +jalv was written by +.An David Robillard +.Aq Mt d@drobilla.net +with contributions by others. +Most of the Qt interface was added by Amadeus Folego and Timo Westkämper. diff --git a/doc/mandoc.css b/doc/mandoc.css new file mode 100644 index 0000000..aee69e5 --- /dev/null +++ b/doc/mandoc.css @@ -0,0 +1,327 @@ +/* + Copyright 2021-2022 David Robillard <d@drobilla.net> + SPDX-License-Identifier: ISC +*/ + +/* Generic page style */ + +/* + Smaller sizes: 0.236em 0.271em 0.382em 0.438em 0.618em 0.708em + Larger sizes: 1.146em 1.618em 1.854em 2.618em 3em 4.236em +*/ + +html { + margin: 0 1.618em; + background: #fff; + color: #000; +} + +body { + font-style: normal; + line-height: 1.618em; + margin: 0 auto auto; + padding: 0; + max-width: 60em; + font-family: "SF Pro Text", Verdana, "DejaVu Sans", sans-serif; + text-rendering: optimizelegibility; +} + +h1 { + font-family: Helvetica, Arial, "DejaVu Sans Condensed", Verdana, sans-serif; + font-size: 1.854em; + font-weight: 600; + line-height: 114.6%; + margin: 1.146em 0; +} + +a { + text-decoration: none; +} + +h1 a, +h2 a, +h3 a, +h4 a, +h5 a, +h6 a { + color: #222; +} + +a:hover { + text-decoration: underline; +} + +h1 a:link, +h2 a:link, +h3 a:link, +h4 a:link, +h5 a:link, +h6 a:link { + color: #222; +} + +h1 a:visited, +h2 a:visited, +h3 a:visited, +h4 a:visited, +h5 a:visited, +h6 a:visited { + color: #222; +} + +pre, +tt, +code { + overflow: auto; + font-family: "SF Mono", Menlo, Consolas, "DejaVu Sans Mono", monospace, fixed; + hyphens: none; + white-space: nowrap; + + /* stylelint-disable property-no-vendor-prefix */ + -epub-hyphens: none; + -moz-hyphens: none; + -ms-hyphens: none; + -webkit-hyphens: none; + /* stylelint-enable property-no-vendor-prefix */ +} + +ul, +ol, +dl { + margin: 0; + padding: 0; +} + +ul { + padding: 0; + hyphens: auto; +} + +dt { + font-weight: 600; + padding: 0.618em 0 0; +} + +dd { + margin: 0 0 0 2.618em; + hyphens: auto; +} + +dd > ul:only-child, +dd > ol:only-child { + padding-left: 0; +} + +li { + margin-left: 2.618em; +} + +dt:empty { + margin: 0; + display: none; +} + +dd:empty { + margin: 0; + display: none; +} + +dt:blank { + margin: 0; + display: none; +} + +dd:blank { + margin: 0; + display: none; +} + +/* Media-specific style */ + +/* Color links on screens */ +@media screen { + a { + color: #546e00; + } +} + +@media print { + body { + color: #000; + } + + a, + h1 a, + h2 a, + h3 a, + h4 a, + h5 a, + h6 a { + color: #000; + } + + a:link { + color: #000; + } + + a:visited { + color: #000; + } +} + +/* Mandoc specific style */ + +/* stylelint-disable selector-class-pattern */ + +table.head { + font-size: 0.708em; + margin: 0.438em 0 1.854em; + width: 100%; +} + +table.foot { + font-size: 0.708em; + margin: 2.618em 0 0.438em; + width: 100%; +} + +td.head-rtitle, +td.foot-os { + text-align: right; +} + +td.head-vol { + text-align: center; +} + +div.Pp { + margin: 1ex 0; +} + +a.permalink { + color: #222; +} + +div.Nd, +div.Bf, +div.Op { + display: inline; +} + +span.Pa, +span.Ad { + font-style: italic; +} + +span.Ms { + font-weight: bold; +} + +dl.Bl-diag > dt { + font-weight: bold; +} + +table.Nm tbody tr { + vertical-align: baseline; +} + +code.Nm, +code.Fl, +code.Cm, +code.Ic, +code.In, +code.Fd, +code.Fn, +code.Cd { + font-weight: bold; + color: #444; +} + +code.Ev { + font-weight: bold; + color: #444; +} + +code.Li { + color: #333; +} + +var.Ar { + font-style: italic; +} + +/* stylelint-enable selector-class-pattern */ + +/* Dark mode */ +@media (prefers-color-scheme: dark) { + html { + background: #222; + color: #ddd; + } + + a { + color: #b4c342; + } + + a.permalink { + color: #ddd; + } + + h1 a, + h2 a, + h3 a, + h4 a, + h5 a, + h6 a { + color: #ddd; + } + + h1 a:link, + h2 a:link, + h3 a:link, + h4 a:link, + h5 a:link, + h6 a:link { + color: #ddd; + } + + h1 a:visited, + h2 a:visited, + h3 a:visited, + h4 a:visited, + h5 a:visited, + h6 a:visited { + color: #ddd; + } + + /* stylelint-disable selector-class-pattern */ + + code.Nm, + code.Fl, + code.Cm, + code.Ic, + code.In, + code.Fd, + code.Fn, + code.Cd { + color: #aaa; + } + + code.Ev { + color: #aaa; + } + + code.Li { + color: #ccc; + } + + /* stylelint-enable selector-class-pattern */ +} + +/* Hard black for dark mode on mobile (since it's likely to be an OLED screen) */ +@media only screen and (hover: none) and (pointer: coarse) and (prefers-color-scheme: dark) { + html { + background: #000; + color: #ccc; + } +} diff --git a/doc/meson.build b/doc/meson.build new file mode 100644 index 0000000..9a00094 --- /dev/null +++ b/doc/meson.build @@ -0,0 +1,60 @@ +# Copyright 2022-2024 David Robillard <d@drobilla.net> +# SPDX-License-Identifier: 0BSD OR ISC + +docdir = get_option('datadir') / 'doc' + +if not get_option('man').disabled() + install_man(files('jalv.1')) + + if not get_option('gtk3').disabled() + install_man(files('jalv.gtk3.1')) + endif + + if not get_option('qt5').disabled() + install_man(files('jalv.qt5.1')) + endif + + if not get_option('qt6').disabled() + install_man(files('jalv.qt6.1')) + endif +endif + +# Build/install HTML man pages if mandoc is present +mandoc = find_program('mandoc', required: get_option('man_html')) +if mandoc.found() + configure_file( + copy: true, + input: files('mandoc.css'), + output: 'mandoc.css', + install_dir: docdir / meson.project_name() / 'man', + ) + + mandoc_html_command = [ + mandoc, + '-Kutf-8', + '-Ostyle=mandoc.css,man=%N.html', + '-Thtml', + '-Wwarning,stop', '@INPUT@', + ] + + html_mandir = docdir / meson.project_name() / 'man' + foreach name : ['jalv', 'jalv.gtk3', 'jalv.qt5', 'jalv.qt6'] + custom_target( + name + '.html', + capture: true, + command: mandoc_html_command, + input: files(name + '.1'), + install: true, + install_dir: html_mandir, + output: name + '.html', + ) + endforeach + + if not meson.is_subproject() + summary( + 'HTML man pages', + get_option('prefix') / html_mandir, + section: 'Directories', + ) + endif +endif diff --git a/jalv.desktop.in b/jalv.desktop.in new file mode 100644 index 0000000..6a99e50 --- /dev/null +++ b/jalv.desktop.in @@ -0,0 +1,9 @@ +[Desktop Entry] +Name=@APP_HUMAN_NAME@ +Comment=Simple LV2 plugin host +Comment[fr]=Hôte de greffon LV2 simple +Exec=@BINDIR@/@APP_INSTALL_NAME@ +Terminal=false +Type=Application +Categories=AudioVideo;Audio; +Keywords=music;midi;alsa;jack; diff --git a/jalv.ttl b/jalv.ttl new file mode 100644 index 0000000..317ae54 --- /dev/null +++ b/jalv.ttl @@ -0,0 +1,29 @@ +@prefix rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#> . +@prefix rdfs: <http://www.w3.org/2000/01/rdf-schema#> . +@prefix doap: <http://usefulinc.com/ns/doap#> . +@prefix foaf: <http://xmlns.com/foaf/0.1/> . + +<http://drobilla.net/drobilla#me> + a foaf:Person ; + rdfs:seeAlso <http://drobilla.net/drobilla> ; + foaf:mbox <mailto:d@drobilla.net> ; + foaf:name "David Robillard" ; + foaf:nick "drobilla" . + +<http://drobilla.net/software/jalv> + a doap:Project ; + doap:blog <https://drobilla.net/category/jalv/> ; + doap:bug-database <https://gitlab.com/drobilla/jalv/issues> ; + doap:description "C library for hosting LV2 plugins" ; + doap:developer <http://drobilla.net/drobilla#me> ; + doap:download-page <http://download.drobilla.net/> ; + doap:homepage <http://drobilla.net/software/jalv> ; + doap:implements <http://lv2plug.in/ns/lv2core#> ; + doap:license <http://opensource.org/licenses/isc> ; + doap:maintainer <http://drobilla.net/drobilla#me> ; + doap:name "Jalv" ; + doap:programming-language "C" ; + doap:repository [ + a doap:GitBranch ; + doap:location <https://gitlab.com/drobilla/jalv.git> + ] . diff --git a/meson.build b/meson.build new file mode 100644 index 0000000..8b6cf66 --- /dev/null +++ b/meson.build @@ -0,0 +1,657 @@ +# Copyright 2020-2024 David Robillard <d@drobilla.net> +# SPDX-License-Identifier: 0BSD OR ISC + +project( + 'jalv', + ['c', 'cpp'], + default_options: [ + 'b_ndebug=if-release', + 'buildtype=release', + 'c_std=c99', + 'cpp_std=c++17', + ], + license: 'ISC', + meson_version: '>= 0.56.0', + version: '1.6.9', +) + +jalv_src_root = meson.current_source_dir() +jalv_build_root = meson.current_build_dir() +major_version = meson.project_version().split('.')[0] +version_suffix = '@0@-@1@'.format(meson.project_name(), major_version) + +############# +# Compilers # +############# + +# Required tools +cc = meson.get_compiler('c') + +# Optional C++ support +if add_languages(['cpp'], native: false, required: get_option('cxx')) + cpp = meson.get_compiler('cpp') +endif + +######################## +# Warning Suppressions # +######################## + +warning_level = get_option('warning_level') + +# C +c_suppressions = [] +if cc.get_id() == 'clang' + if warning_level == 'everything' + c_suppressions += [ + '-Wno-bad-function-cast', + '-Wno-cast-align', + '-Wno-cast-function-type-strict', + '-Wno-cast-qual', + '-Wno-declaration-after-statement', + '-Wno-disabled-macro-expansion', + '-Wno-double-promotion', + '-Wno-float-conversion', + '-Wno-float-equal', + '-Wno-implicit-float-conversion', + '-Wno-missing-noreturn', + '-Wno-padded', + '-Wno-shorten-64-to-32', + '-Wno-sign-conversion', + '-Wno-switch-default', + '-Wno-unsafe-buffer-usage', + ] + + if not meson.is_cross_build() + c_suppressions += [ + '-Wno-poison-system-directories', + ] + endif + + if host_machine.system() == 'darwin' + c_suppressions += [ + '-Wno-documentation-unknown-command', + '-Wno-reserved-id-macro', + ] + endif + endif + + if warning_level in ['everything', '3'] + c_suppressions += [ + '-Wno-nullability-extension', + ] + endif + + if host_machine.system() == 'darwin' + c_suppressions += [ + '-Wno-documentation', # JACK + '-Wno-documentation-deprecated-sync', # JACK + ] + elif host_machine.system() == 'freebsd' + c_suppressions += [ + '-Wno-c11-extensions', # isnan and friends + ] + endif + +elif cc.get_id() == 'gcc' + if warning_level == 'everything' + c_suppressions += [ + '-Wno-bad-function-cast', + '-Wno-c++-compat', + '-Wno-cast-align', + '-Wno-cast-qual', + '-Wno-conversion', + '-Wno-double-promotion', + '-Wno-float-equal', + '-Wno-inline', + '-Wno-padded', + '-Wno-strict-overflow', + '-Wno-suggest-attribute=const', + '-Wno-suggest-attribute=pure', + '-Wno-switch-default', + '-Wno-unsuffixed-float-constants', + '-Wno-unused-const-variable', + ] + endif + +elif cc.get_id() == 'msvc' + if warning_level == 'everything' + c_suppressions += [ + '/wd4062', # enumerator in switch is not handled + '/wd4191', # unsafe function conversion + '/wd4200', # zero-sized array in struct/union + '/wd4242', # possible loss of data from float conversion + '/wd4365', # signed/unsigned mismatch + '/wd4514', # unreferenced inline function has been removed + '/wd4668', # not defined as a preprocessor macro + '/wd4706', # assignment within conditional expression + '/wd4710', # function not inlined + '/wd4711', # function selected for automatic inline expansion + '/wd4800', # implicit conversion from int to bool + '/wd4820', # padding added after construct + '/wd5045', # compiler will insert Spectre mitigation + ] + endif + + if warning_level in ['everything', '3', '2'] + c_suppressions += [ + '/wd4267', # possible loss of data from size conversion + '/wd4996', # POSIX name for this item is deprecated + ] + endif + + if warning_level in ['everything', '3', '2', '1'] + c_suppressions += [ + '/wd4244', # conversion from unsigned long to float + ] + endif +endif + +c_suppressions = cc.get_supported_arguments(c_suppressions) + +# C++ +if is_variable('cpp') + cpp_suppressions = [] + + if cpp.get_id() == 'clang' + if warning_level == 'everything' + cpp_suppressions += [ + '-Wno-c++98-compat-pedantic', + '-Wno-cast-align', # MacOS + '-Wno-cast-qual', # MacOS + '-Wno-documentation-unknown-command', # MacOS + '-Wno-double-promotion', + '-Wno-float-conversion', + '-Wno-implicit-float-conversion', + '-Wno-old-style-cast', # MacOS + '-Wno-padded', + '-Wno-redundant-parens', + '-Wno-reserved-id-macro', # MacOS + '-Wno-shorten-64-to-32', + '-Wno-sign-conversion', + '-Wno-unsafe-buffer-usage', + '-Wno-weak-vtables', + '-Wno-zero-as-null-pointer-constant', # MacOS + ] + + if not meson.is_cross_build() + cpp_suppressions += [ + '-Wno-poison-system-directories', + ] + endif + endif + + if warning_level in ['everything', '3'] + cpp_suppressions += [ + '-Wno-nullability-extension', + ] + endif + + elif cpp.get_id() == 'gcc' + if warning_level == 'everything' + cpp_suppressions += [ + '-Wno-cast-align', # LV2 + '-Wno-cast-qual', # LV2 + '-Wno-conversion', + '-Wno-effc++', + '-Wno-inline', + '-Wno-padded', + '-Wno-strict-overflow', + '-Wno-suggest-attribute=const', + '-Wno-suggest-attribute=pure', + '-Wno-unused-const-variable', + ] + endif + endif + + cpp_suppressions = cpp.get_supported_arguments(cpp_suppressions) +endif + +####################### +# Common Dependencies # +####################### + +m_dep = cc.find_library('m', required: false) + +thread_dep = dependency('threads') + +zix_dep = dependency( + 'zix-0', + default_options: [ + 'benchmarks=disabled', + 'docs=disabled', + 'tests=disabled', + 'tests_cpp=disabled', + ], + fallback: ['zix', 'zix_dep'], + include_type: 'system', + version: '>= 0.4.0', +) + +serd_dep = dependency( + 'serd-0', + default_options: [ + 'docs=disabled', + 'tests=disabled', + 'tools=disabled', + ], + fallback: ['serd', 'serd_dep'], + include_type: 'system', + version: '>= 0.32.2', +) + +sord_dep = dependency( + 'sord-0', + default_options: [ + 'docs=disabled', + 'tests=disabled', + 'tools=disabled', + ], + fallback: ['sord', 'sord_dep'], + include_type: 'system', + version: '>= 0.16.16', +) + +lv2_dep = dependency( + 'lv2', + default_options: [ + 'docs=disabled', + 'old_headers=false', + 'plugins=disabled', + 'tests=disabled', + ], + fallback: ['lv2', 'lv2_dep'], + include_type: 'system', + version: '>= 1.18.0', +) + +sratom_dep = dependency( + 'sratom-0', + default_options: [ + 'docs=disabled', + 'tests=disabled', + ], + fallback: ['sratom', 'sratom_dep'], + include_type: 'system', + version: '>= 0.6.4', +) + +lilv_dep = dependency( + 'lilv-0', + default_options: [ + 'bindings_py=disabled', + 'docs=disabled', + 'tests=disabled', + 'tools=disabled', + ], + fallback: ['lilv', 'lilv_dep'], + include_type: 'system', + version: '>= 0.24.24', +) + +suil_dep = dependency( + 'suil-0', + default_options: [ + 'docs=disabled', + 'tests=disabled', + ], + fallback: ['suil', 'suil_dep'], + include_type: 'system', + required: get_option('suil'), + version: '>= 0.10.0', +) + +########### +# Drivers # +########### + +portaudio_dep = dependency( + 'portaudio-2.0', + include_type: 'system', + required: get_option('portaudio'), + version: '>= 2.0.0', +) + +jack_dep = dependency( + 'jack', + include_type: 'system', + required: get_option('jack'), + version: '>= 0.120.0', +) + +backend_sources = files() +if get_option('jack').enabled() and get_option('portaudio').enabled() + error('Only one of jack and portaudio can be enabled') +elif get_option('jack').enabled() + backend_dep = jack_dep + backend_sources += files('src/jack.c') +elif get_option('portaudio').enabled() + backend_dep = portaudio_dep + backend_sources += files('src/portaudio.c') +elif jack_dep.found() + backend_dep = jack_dep + backend_sources += files('src/jack.c') +else + backend_dep = portaudio_dep + backend_sources += files('src/portaudio.c') +endif + +if not backend_dep.found() + error('No backend found, either jack or portaudio is required') +endif + +########################## +# Platform Configuration # +########################## + +platform_defines = [ + '-DJALV_VERSION="@0@"'.format(meson.project_version()), +] + +suil_defines = ['-DHAVE_SUIL=@0@'.format(suil_dep.found().to_int())] + +# Determine whether to use POSIX +no_posix = get_option('posix').disabled() or host_machine.system() == 'windows' +if no_posix + platform_defines += ['-DJALV_NO_POSIX'] +elif host_machine.system() == 'darwin' + platform_defines += ['-D_POSIX_C_SOURCE=200809L'] +else + platform_defines += ['-D_POSIX_C_SOURCE=200809L'] +endif + +# Build platform-specific configuration arguments +if get_option('checks').disabled() + # Generic build without platform-specific features + platform_defines += ['-DJALV_NO_DEFAULT_CONFIG'] +elif get_option('checks').enabled() + # Only use the features detected by the build system + platform_defines += ['-DJALV_NO_DEFAULT_CONFIG'] + + if no_posix + platform_defines += ['-DHAVE_FILENO=0'] + platform_defines += ['-DHAVE_ISATTY=0'] + platform_defines += ['-DHAVE_POSIX_MEMALIGN=0'] + platform_defines += ['-DHAVE_SIGACTION=0'] + else + fileno_code = '''#include <stdio.h> +int main(void) { return fileno(stdin); }''' + + isatty_code = '''#include <unistd.h> +int main(void) { return isatty(0); }''' + + posix_memalign_code = '''#include <stdlib.h> +int main(void) { void* mem; posix_memalign(&mem, 8, 8); }''' + + sigaction_code = '''#include <signal.h> +int main(void) { return sigaction(SIGINT, 0, 0); }''' + + platform_defines += '-DHAVE_FILENO=@0@'.format( + cc.compiles(fileno_code, args: platform_defines, name: 'fileno').to_int(), + ) + + platform_defines += '-DHAVE_ISATTY=@0@'.format( + cc.compiles(isatty_code, args: platform_defines, name: 'isatty').to_int(), + ) + + platform_defines += '-DHAVE_POSIX_MEMALIGN=@0@'.format( + cc.compiles( + posix_memalign_code, + args: platform_defines, + name: 'posix_memalign', + ).to_int(), + ) + + platform_defines += '-DHAVE_SIGACTION=@0@'.format( + cc.compiles(sigaction_code, args: platform_defines, name: 'sigaction').to_int(), + ) + endif + + jack_metadata_code = '''#include <jack/metadata.h> +int main(void) { return !!&jack_set_property; }''' + + jack_port_type_get_buffer_size_code = '''#include <jack/jack.h> +int main(void) { return !!&jack_port_type_get_buffer_size; }''' + + platform_defines += '-DHAVE_JACK_METADATA=@0@'.format( + cc.compiles( + jack_metadata_code, + args: platform_defines, + name: 'jack_metadata', + ).to_int(), + ) + + platform_defines += '-DHAVE_JACK_PORT_TYPE_GET_BUFFER_SIZE=@0@'.format( + cc.compiles( + jack_port_type_get_buffer_size_code, + args: platform_defines, + name: 'jack_port_type_get_buffer_size', + ).to_int(), + ) +endif + +############ +# Programs # +############ + +common_sources = files( + 'src/comm.c', + 'src/control.c', + 'src/dumper.c', + 'src/features.c', + 'src/jalv.c', + 'src/log.c', + 'src/lv2_evbuf.c', + 'src/mapper.c', + 'src/nodes.c', + 'src/process.c', + 'src/process_setup.c', + 'src/query.c', + 'src/state.c', + 'src/string_utils.c', + 'src/symap.c', + 'src/urids.c', + 'src/worker.c', +) + +sources = backend_sources + common_sources +program_sources = sources + files('src/main.c') + +common_dependencies = [ + backend_dep, + lilv_dep, + m_dep, + serd_dep, + sratom_dep, + suil_dep, + thread_dep, + zix_dep, +] + +common_c_args = c_suppressions + platform_defines + suil_defines + +# Internal JACK client library +if jack_dep.found() and host_machine.system() != 'windows' + shared_library( + 'jalv', + sources + files('src/jack_internal.c', 'src/jalv_console.c'), + c_args: c_suppressions + platform_defines + ['-DHAVE_SUIL=0'], + dependencies: common_dependencies, + install: true, + install_dir: get_option('prefix') / get_option('libdir') / 'jack', + name_prefix: '', + ) +endif + +# Console version +executable( + 'jalv', + program_sources + files('src/jalv_console.c'), + c_args: common_c_args, + dependencies: common_dependencies + [suil_dep], + install: true, +) + +# Gtk 3.0 GUI version +if not get_option('gtk3').disabled() + gdk3_dep = dependency( + 'gdk-3.0', + include_type: 'system', + required: get_option('gtk3'), + version: '>= 3.12.0', + ) + + gtk3_dep = dependency( + 'gtk+-3.0', + include_type: 'system', + required: get_option('gtk3'), + version: '>= 3.12.0', + ) + + if gdk3_dep.found() and gtk3_dep.found() + config = configuration_data() + config.set('APP_INSTALL_NAME', 'jalv.gtk3') + config.set('APP_HUMAN_NAME', 'Jalv') + config.set('BINDIR', get_option('prefix') / get_option('bindir')) + + configure_file( + configuration: config, + input: files('jalv.desktop.in'), + install: true, + install_dir: get_option('datadir') / 'applications', + output: 'jalv.desktop', + ) + + executable( + 'jalv.gtk3', + program_sources + files('src/jalv_gtk.c'), + c_args: common_c_args, + dependencies: common_dependencies + [gdk3_dep, gtk3_dep, suil_dep], + install: true, + ) + endif +endif + +if is_variable('cpp') + common_cpp_args = cpp_suppressions + platform_defines + suil_defines + + qt_args = [] + if cpp.get_id() in ['clang', 'gcc'] + qt_args = ['-fPIC'] + endif + + jalv_qt_cpp = files('src' / 'jalv_qt.cpp') + jalv_qt_hpp = files(jalv_src_root / 'src' / 'jalv_qt.hpp') + + # Qt 5 GUI version + qt5_opt = get_option('qt5') + if not qt5_opt.disabled() + qt5_dep = dependency( + 'Qt5Widgets', + include_type: 'system', + required: qt5_opt, + version: '>= 5.1.0', + ) + + if qt5_dep.found() + if get_option('qt5_moc') != '' + moc_qt5 = find_program(get_option('qt5_moc'), required: qt5_opt) + else + moc_qt5 = find_program('moc-qt5', required: false) + if not moc_qt5.found() + moc_qt5 = find_program( + 'moc', + required: qt5_opt, + version: ['>=5.0.0', '<=6.0.0'], + ) + endif + endif + + if moc_qt5.found() + jalv_qt5_meta_cpp = custom_target( + 'jalv_qt5_meta.cpp', + capture: true, + command: [moc_qt5, '@INPUT@'], + input: jalv_qt_hpp, + output: 'jalv_qt5_meta.cpp', + ) + + executable( + 'jalv.qt5', + program_sources + jalv_qt_cpp + [jalv_qt5_meta_cpp], + c_args: common_c_args, + cpp_args: common_cpp_args + qt_args, + dependencies: common_dependencies + [qt5_dep, suil_dep], + install: true, + ) + endif + endif + endif + + # Qt 6 GUI version + qt6_opt = get_option('qt6') + if not qt6_opt.disabled() + qt6_dep = dependency( + 'Qt6Widgets', + include_type: 'system', + required: qt6_opt, + version: '>= 6.2.0', + ) + + if qt6_dep.found() + moc_qt6_name = get_option('qt6_moc') + if moc_qt6_name == '' + qt6_libexecdir = qt6_dep.get_variable( + default_value: get_option('prefix') / get_option('libexecdir'), + internal: 'libexecdir', + pkgconfig: 'libexecdir', + ) + + moc_qt6_name = qt6_libexecdir / 'moc' + endif + + moc_qt6 = find_program(moc_qt6_name, required: qt6_opt) + if moc_qt6.found() + jalv_qt6_meta_cpp = custom_target( + 'jalv_qt6_meta.cpp', + capture: true, + command: [moc_qt6, '@INPUT@'], + input: jalv_qt_hpp, + output: 'jalv_qt6_meta.cpp', + ) + + executable( + 'jalv.qt6', + program_sources + jalv_qt_cpp + [jalv_qt6_meta_cpp], + c_args: common_c_args, + cpp_args: common_cpp_args + qt_args, + dependencies: common_dependencies + [qt6_dep, suil_dep], + install: true, + ) + endif + endif + endif +endif + +################# +# Documentation # +################# + +if not get_option('man').disabled() + subdir('doc') +endif + +######### +# Tests # +######### + +if not get_option('tests').disabled() + subdir('test') +endif + +if not meson.is_subproject() + summary('Install prefix', get_option('prefix')) + summary('Executables', get_option('prefix') / get_option('bindir')) + summary('Man pages', get_option('prefix') / get_option('mandir')) + + summary('Backend', backend_dep.name()) +endif diff --git a/meson_options.txt b/meson_options.txt new file mode 100644 index 0000000..f0577ef --- /dev/null +++ b/meson_options.txt @@ -0,0 +1,50 @@ +# Copyright 2020-2024 David Robillard <d@drobilla.net> +# SPDX-License-Identifier: 0BSD OR ISC + +option('checks', type: 'feature', value: 'enabled', yield: true, + description: 'Check for platform-specific features') + +option('cxx', type: 'feature', yield: true, + description: 'Build C++ programs') + +option('gtk3', type: 'feature', yield: true, + description: 'Build Gtk3 GUI') + +option('portaudio', type: 'feature', yield: true, + description: 'Build PortAudio driver') + +option('jack', type: 'feature', yield: true, + description: 'Build JACK driver') + +option('lint', type: 'boolean', value: false, yield: true, + description: 'Run code quality checks') + +option('man', type: 'feature', value: 'enabled', yield: true, + description: 'Install man pages') + +option('man_html', type: 'feature', yield: true, + description: 'Build HTML man pages') + +option('posix', type: 'feature', yield: true, + description: 'Use POSIX system facilities') + +option('qt5', type: 'feature', yield: true, + description: 'Build Qt5 GUI') + +option('qt5_moc', type: 'string', yield: true, + description: 'Path to Qt5 moc executable') + +option('qt6', type: 'feature', yield: true, + description: 'Build Qt6 GUI') + +option('qt6_moc', type: 'string', yield: true, + description: 'Path to Qt6 moc executable') + +option('suil', type: 'feature', yield: true, + description: 'Use suil to load plugin UIs') + +option('title', type: 'string', value: 'Jalv', + description: 'Project title') + +option('tests', type: 'feature', yield: true, + description: 'Build tests') diff --git a/src/attributes.h b/src/attributes.h new file mode 100644 index 0000000..88a3e41 --- /dev/null +++ b/src/attributes.h @@ -0,0 +1,15 @@ +// Copyright 2022 David Robillard <d@drobilla.net> +// SPDX-License-Identifier: ISC + +#ifndef JALV_ATTRIBUTES_H +#define JALV_ATTRIBUTES_H + +#ifdef __cplusplus +# define JALV_BEGIN_DECLS extern "C" { +# define JALV_END_DECLS } +#else +# define JALV_BEGIN_DECLS +# define JALV_END_DECLS +#endif + +#endif // JALV_ATTRIBUTES_H diff --git a/src/backend.h b/src/backend.h new file mode 100644 index 0000000..2f34c58 --- /dev/null +++ b/src/backend.h @@ -0,0 +1,64 @@ +// Copyright 2007-2024 David Robillard <d@drobilla.net> +// SPDX-License-Identifier: ISC + +#ifndef JALV_BACKEND_H +#define JALV_BACKEND_H + +#include "attributes.h" +#include "process.h" +#include "settings.h" +#include "types.h" +#include "urids.h" + +#include <zix/attributes.h> +#include <zix/sem.h> + +#include <stdbool.h> +#include <stdint.h> + +// Interface that must be implemented by audio/MIDI backends +JALV_BEGIN_DECLS + +/// Allocate a new uninitialized backend +ZIX_MALLOC_FUNC JalvBackend* +jalv_backend_allocate(void); + +/// Free a backend allocated with jalv_backend_allocate() +void +jalv_backend_free(JalvBackend* backend); + +/// Open the audio/MIDI system +int +jalv_backend_open(JalvBackend* backend, + const JalvURIDs* urids, + JalvSettings* settings, + JalvProcess* process, + ZixSem* done, + const char* name, + bool exact_name); + +/// Close the audio/MIDI system +void +jalv_backend_close(JalvBackend* backend); + +/// Activate the backend and start processing audio +void +jalv_backend_activate(JalvBackend* backend); + +/// Deactivate the backend and stop processing audio +void +jalv_backend_deactivate(JalvBackend* backend); + +/// Expose a port to the system (if applicable) and connect it to its buffer +void +jalv_backend_activate_port(JalvBackend* backend, + JalvProcess* process, + uint32_t port_index); + +/// Recompute latencies based on plugin port latencies if necessary +void +jalv_backend_recompute_latencies(JalvBackend* backend); + +JALV_END_DECLS + +#endif // JALV_BACKEND_H diff --git a/src/comm.c b/src/comm.c new file mode 100644 index 0000000..b3bdfd1 --- /dev/null +++ b/src/comm.c @@ -0,0 +1,64 @@ +// Copyright 2007-2024 David Robillard <d@drobilla.net> +// SPDX-License-Identifier: ISC + +#include "comm.h" + +#include <lv2/urid/urid.h> +#include <zix/ring.h> +#include <zix/status.h> + +ZixStatus +jalv_write_split_message(ZixRing* const target, + const void* const header, + const uint32_t header_size, + const void* const body, + const uint32_t body_size) +{ + ZixRingTransaction tx = zix_ring_begin_write(target); + + ZixStatus st = ZIX_STATUS_SUCCESS; + if (!(st = zix_ring_amend_write(target, &tx, header, header_size)) && + !(st = zix_ring_amend_write(target, &tx, body, body_size))) { + st = zix_ring_commit_write(target, &tx); + } + + return st; +} + +ZixStatus +jalv_write_event(ZixRing* const target, + const uint32_t port_index, + const uint32_t size, + const LV2_URID type, + const void* const body) +{ + // TODO: Be more discriminate about what to send + + typedef struct { + JalvMessageHeader message; + JalvEventTransfer event; + } Header; + + const Header header = {{EVENT_TRANSFER, sizeof(JalvEventTransfer) + size}, + {port_index, {size, type}}}; + + return jalv_write_split_message(target, &header, sizeof(header), body, size); +} + +ZixStatus +jalv_write_control(ZixRing* const target, + const uint32_t port_index, + const float value) +{ + typedef struct { + JalvMessageHeader message; + JalvControlChange control; + } Message; + + const Message msg = {{CONTROL_PORT_CHANGE, sizeof(JalvControlChange)}, + {port_index, value}}; + + return zix_ring_write(target, &msg, sizeof(msg)) == sizeof(msg) + ? ZIX_STATUS_SUCCESS + : ZIX_STATUS_ERROR; +} diff --git a/src/comm.h b/src/comm.h new file mode 100644 index 0000000..5106ba3 --- /dev/null +++ b/src/comm.h @@ -0,0 +1,136 @@ +// Copyright 2007-2024 David Robillard <d@drobilla.net> +// SPDX-License-Identifier: ISC + +#ifndef JALV_COMM_H +#define JALV_COMM_H + +#include "attributes.h" +#include "types.h" + +#include <lv2/atom/atom.h> +#include <lv2/urid/urid.h> +#include <zix/ring.h> +#include <zix/status.h> + +#include <stdint.h> + +// Communication between the audio and main threads via rings +JALV_BEGIN_DECLS + +/// Type of an internal message in a communication ring +typedef enum { + NO_MESSAGE, ///< Sentinel type for uninitialized messages + CONTROL_PORT_CHANGE, ///< Value change for a control port (float) + EVENT_TRANSFER, ///< Event transfer for a sequence port (atom) + LATENCY_CHANGE, ///< Change to plugin latency + STATE_REQUEST, ///< Request for a plugin state update (no payload) + RUN_STATE_CHANGE, ///< Request to pause or resume running +} JalvMessageType; + +/** + Message between the audio thread and the main thread. + + This is the general header for any type of message in a communication ring. + The type determines how the message must be handled by the receiver. This + header is followed immediately by `size` bytes of data in the ring. +*/ +typedef struct { + JalvMessageType type; ///< Type of this message + uint32_t size; ///< Size of payload following this header in bytes +} JalvMessageHeader; + +/** + The payload of a CONTROL_PORT_CHANGE message. + + This message has a fixed size, this struct defines the entire payload. +*/ +typedef struct { + uint32_t port_index; ///< Control port index + float value; ///< Control value +} JalvControlChange; + +/** + The start of the payload of an EVENT_TRANSFER message. + + This message has a variable size, the start, described by this struct, is + followed immediately by `atom.size` bytes of data (the atom body). +*/ +typedef struct { + uint32_t port_index; ///< Sequence port index + LV2_Atom atom; ///< Event payload header +} JalvEventTransfer; + +/** + The payload of a LATENCY_CHANGE message. + + This message has a fixed size, this struct defines the entire payload. +*/ +typedef struct { + float value; ///< Latency in frames at the current sample rate +} JalvLatencyChange; + +/** + The payload of a RUN_STATE_CHANGE message. + + This message has a fixed size, this struct defines the entire payload. +*/ +typedef struct { + JalvRunState state; ///< Run state to change to +} JalvRunStateChange; + +/** + Write a message in two parts to a ring. + + This is used to conveniently write a message with a fixed-size header and + possibly variably-sized body in a single call. + + @param target Communication ring (jalv->plugin_to_ui or jalv->ui_to_plugin). + @param header Pointer to start of header data. + @param header_size Size of header in bytes. + @param body Pointer to start of body data. + @param body_size Size of body in bytes. + @return 0 on success, non-zero on failure (overflow). +*/ +ZixStatus +jalv_write_split_message(ZixRing* target, + const void* header, + uint32_t header_size, + const void* body, + uint32_t body_size); + +/** + Write a port event using the atom:eventTransfer protocol. + + This is used to transfer atoms between the plugin and UI via sequence ports. + + @param target Communication ring (jalv->plugin_to_ui or jalv->ui_to_plugin). + @param port_index Index of the port this change is for. + @param size Size of body in bytes. + @param type Atom type URID. + @param body Atom body. + @return 0 on success, non-zero on failure (overflow). +*/ +ZixStatus +jalv_write_event(ZixRing* target, + uint32_t port_index, + uint32_t size, + LV2_URID type, + const void* body); + +/** + Write a control port change using the default (0) protocol. + + This is used to transfer control port value changes between the plugin and + UI. + + @param target Communication ring (jalv->plugin_to_ui or jalv->ui_to_plugin). + @param port_index Index of the port this change is for. + @param value New control port value. + @return 0 on success, non-zero on failure (overflow). +*/ +ZixStatus +jalv_write_control(ZixRing* target, uint32_t port_index, float value); + +JALV_END_DECLS + +#endif // JALV_COMM_H diff --git a/src/control.c b/src/control.c index 2326280..41a2b70 100644 --- a/src/control.c +++ b/src/control.c @@ -1,165 +1,206 @@ -/* - Copyright 2007-2016 David Robillard <http://drobilla.net> +// Copyright 2007-2022 David Robillard <d@drobilla.net> +// SPDX-License-Identifier: ISC - Permission to use, copy, modify, and/or distribute this software for any - purpose with or without fee is hereby granted, provided that the above - copyright notice and this permission notice appear in all copies. +#include "control.h" - THIS SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES - WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF - MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR - ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES - WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN - ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF - OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. -*/ +#include "log.h" +#include "nodes.h" +#include "string_utils.h" -#include "jalv_internal.h" +#include <lilv/lilv.h> +#include <lv2/atom/atom.h> +#include <lv2/atom/forge.h> +#include <lv2/urid/urid.h> -int +#include <stdbool.h> +#include <stdint.h> +#include <stdlib.h> + +/// Order scale points by value +static int scale_point_cmp(const ScalePoint* a, const ScalePoint* b) { - if (a->value < b->value) { - return -1; - } else if (a->value == b->value) { - return 0; - } - return 1; + if (a->value < b->value) { + return -1; + } + + if (a->value == b->value) { + return 0; + } + + return 1; } ControlID* -new_port_control(Jalv* jalv, uint32_t index) +new_port_control(LilvWorld* const world, + const LilvPlugin* const plugin, + const LilvPort* const port, + uint32_t port_index, + const float sample_rate, + const JalvNodes* const nodes, + const LV2_Atom_Forge* const forge) { - struct Port* port = &jalv->ports[index]; - const LilvPort* lport = port->lilv_port; - const LilvPlugin* plug = jalv->plugin; - const JalvNodes* nodes = &jalv->nodes; - - ControlID* id = (ControlID*)calloc(1, sizeof(ControlID)); - id->jalv = jalv; - id->type = PORT; - id->node = lilv_node_duplicate(lilv_port_get_node(plug, lport)); - id->symbol = lilv_node_duplicate(lilv_port_get_symbol(plug, lport)); - id->label = lilv_port_get_name(plug, lport); - id->index = index; - id->group = lilv_port_get(plug, lport, jalv->nodes.pg_group); - id->value_type = jalv->forge.Float; - id->is_writable = lilv_port_is_a(plug, lport, nodes->lv2_InputPort); - id->is_readable = lilv_port_is_a(plug, lport, nodes->lv2_OutputPort); - id->is_toggle = lilv_port_has_property(plug, lport, nodes->lv2_toggled); - id->is_integer = lilv_port_has_property(plug, lport, nodes->lv2_integer); - id->is_enumeration = lilv_port_has_property(plug, lport, nodes->lv2_enumeration); - id->is_logarithmic = lilv_port_has_property(plug, lport, nodes->pprops_logarithmic); - - lilv_port_get_range(plug, lport, &id->def, &id->min, &id->max); - if (lilv_port_has_property(plug, lport, jalv->nodes.lv2_sampleRate)) { - /* Adjust range for lv2:sampleRate controls */ - if (lilv_node_is_float(id->min) || lilv_node_is_int(id->min)) { - const float min = lilv_node_as_float(id->min) * jalv->sample_rate; - lilv_node_free(id->min); - id->min = lilv_new_float(jalv->world, min); - } - if (lilv_node_is_float(id->max) || lilv_node_is_int(id->max)) { - const float max = lilv_node_as_float(id->max) * jalv->sample_rate; - lilv_node_free(id->max); - id->max = lilv_new_float(jalv->world, max); - } - } - - /* Get scale points */ - LilvScalePoints* sp = lilv_port_get_scale_points(plug, lport); - if (sp) { - id->points = (ScalePoint*)malloc( - lilv_scale_points_size(sp) * sizeof(ScalePoint)); - size_t np = 0; - LILV_FOREACH(scale_points, s, sp) { - const LilvScalePoint* p = lilv_scale_points_get(sp, s); - if (lilv_node_is_float(lilv_scale_point_get_value(p)) || - lilv_node_is_int(lilv_scale_point_get_value(p))) { - id->points[np].value = lilv_node_as_float( - lilv_scale_point_get_value(p)); - id->points[np].label = strdup( - lilv_node_as_string(lilv_scale_point_get_label(p))); - ++np; - } - /* TODO: Non-float scale points? */ - } - - qsort(id->points, np, sizeof(ScalePoint), - (int (*)(const void*, const void*))scale_point_cmp); - id->n_points = np; - - lilv_scale_points_free(sp); - } - - return id; + ControlID* id = (ControlID*)calloc(1, sizeof(ControlID)); + + id->type = PORT; + id->id.index = port_index; + id->node = lilv_node_duplicate(lilv_port_get_node(plugin, port)); + id->symbol = lilv_node_duplicate(lilv_port_get_symbol(plugin, port)); + id->label = lilv_port_get_name(plugin, port); + id->group = lilv_port_get(plugin, port, nodes->pg_group); + id->value_type = forge->Float; + id->is_writable = lilv_port_is_a(plugin, port, nodes->lv2_InputPort); + id->is_readable = lilv_port_is_a(plugin, port, nodes->lv2_OutputPort); + id->is_toggle = lilv_port_has_property(plugin, port, nodes->lv2_toggled); + id->is_integer = lilv_port_has_property(plugin, port, nodes->lv2_integer); + + id->is_enumeration = + lilv_port_has_property(plugin, port, nodes->lv2_enumeration); + + id->is_logarithmic = + lilv_port_has_property(plugin, port, nodes->pprops_logarithmic); + + lilv_port_get_range(plugin, port, &id->def, &id->min, &id->max); + if (lilv_port_has_property(plugin, port, nodes->lv2_sampleRate)) { + // Adjust range for lv2:sampleRate controls + if (lilv_node_is_float(id->min) || lilv_node_is_int(id->min)) { + const float min = lilv_node_as_float(id->min) * sample_rate; + lilv_node_free(id->min); + id->min = lilv_new_float(world, min); + } + if (lilv_node_is_float(id->max) || lilv_node_is_int(id->max)) { + const float max = lilv_node_as_float(id->max) * sample_rate; + lilv_node_free(id->max); + id->max = lilv_new_float(world, max); + } + } + + // Get scale points + LilvScalePoints* sp = lilv_port_get_scale_points(plugin, port); + if (sp) { + id->points = + (ScalePoint*)malloc(lilv_scale_points_size(sp) * sizeof(ScalePoint)); + + size_t np = 0; + LILV_FOREACH (scale_points, s, sp) { + const LilvScalePoint* p = lilv_scale_points_get(sp, s); + if (lilv_node_is_float(lilv_scale_point_get_value(p)) || + lilv_node_is_int(lilv_scale_point_get_value(p))) { + id->points[np].value = + lilv_node_as_float(lilv_scale_point_get_value(p)); + id->points[np].label = + jalv_strdup(lilv_node_as_string(lilv_scale_point_get_label(p))); + ++np; + } + // TODO: Non-float scale points? + } + + qsort(id->points, + np, + sizeof(ScalePoint), + (int (*)(const void*, const void*))scale_point_cmp); + + id->n_points = np; + lilv_scale_points_free(sp); + } + + return id; } static bool -has_range(Jalv* jalv, const LilvNode* subject, const char* range_uri) +has_range(LilvWorld* const world, + const JalvNodes* const nodes, + const LilvNode* const subject, + const char* const range_uri) { - LilvNode* range = lilv_new_uri(jalv->world, range_uri); - const bool result = lilv_world_ask( - jalv->world, subject, jalv->nodes.rdfs_range, range); - lilv_node_free(range); - return result; + LilvNode* range = lilv_new_uri(world, range_uri); + const bool result = lilv_world_ask(world, subject, nodes->rdfs_range, range); + + lilv_node_free(range); + return result; } ControlID* -new_property_control(Jalv* jalv, const LilvNode* property) +new_property_control(LilvWorld* const world, + const LilvNode* property, + const JalvNodes* const nodes, + LV2_URID_Map* const map, + const LV2_Atom_Forge* const forge) +{ + ControlID* id = (ControlID*)calloc(1, sizeof(ControlID)); + id->type = PROPERTY; + id->id.property = map->map(map->handle, lilv_node_as_uri(property)); + id->node = lilv_node_duplicate(property); + id->symbol = lilv_world_get_symbol(world, property); + + id->label = lilv_world_get(world, property, nodes->rdfs_label, NULL); + id->min = lilv_world_get(world, property, nodes->lv2_minimum, NULL); + id->max = lilv_world_get(world, property, nodes->lv2_maximum, NULL); + id->def = lilv_world_get(world, property, nodes->lv2_default, NULL); + + const char* const types[] = {LV2_ATOM__Int, + LV2_ATOM__Long, + LV2_ATOM__Float, + LV2_ATOM__Double, + LV2_ATOM__Bool, + LV2_ATOM__String, + LV2_ATOM__Path, + NULL}; + + for (const char* const* t = types; *t; ++t) { + if (has_range(world, nodes, property, *t)) { + id->value_type = map->map(map->handle, *t); + break; + } + } + + id->is_toggle = (id->value_type == forge->Bool); + id->is_integer = + (id->value_type == forge->Int || id->value_type == forge->Long); + + if (!id->value_type) { + jalv_log(JALV_LOG_WARNING, + "Unknown value type for property <%s>\n", + lilv_node_as_string(property)); + } + + return id; +} + +void +free_control(ControlID* const control) { - ControlID* id = (ControlID*)calloc(1, sizeof(ControlID)); - id->jalv = jalv; - id->type = PROPERTY; - id->node = lilv_node_duplicate(property); - id->symbol = lilv_world_get_symbol(jalv->world, property); - id->label = lilv_world_get(jalv->world, property, jalv->nodes.rdfs_label, NULL); - id->property = jalv->map.map(jalv, lilv_node_as_uri(property)); - - id->min = lilv_world_get(jalv->world, property, jalv->nodes.lv2_minimum, NULL); - id->max = lilv_world_get(jalv->world, property, jalv->nodes.lv2_maximum, NULL); - id->def = lilv_world_get(jalv->world, property, jalv->nodes.lv2_default, NULL); - - const char* const types[] = { - LV2_ATOM__Int, LV2_ATOM__Long, LV2_ATOM__Float, LV2_ATOM__Double, - LV2_ATOM__Bool, LV2_ATOM__String, LV2_ATOM__Path, NULL - }; - - for (const char*const* t = types; *t; ++t) { - if (has_range(jalv, property, *t)) { - id->value_type = jalv->map.map(jalv, *t); - break; - } - } - - id->is_toggle = (id->value_type == jalv->forge.Bool); - id->is_integer = (id->value_type == jalv->forge.Int || - id->value_type == jalv->forge.Long); - - if (!id->value_type) { - fprintf(stderr, "Unknown value type for property <%s>\n", - lilv_node_as_string(property)); - } - - return id; + lilv_node_free(control->node); + lilv_node_free(control->symbol); + lilv_node_free(control->label); + lilv_node_free(control->group); + lilv_node_free(control->min); + lilv_node_free(control->max); + lilv_node_free(control->def); + free(control); } void add_control(Controls* controls, ControlID* control) { - controls->controls = (ControlID**)realloc( - controls->controls, (controls->n_controls + 1) * sizeof(ControlID*)); - controls->controls[controls->n_controls++] = control; + ControlID** const new_controls = (ControlID**)realloc( + controls->controls, (controls->n_controls + 1) * sizeof(ControlID*)); + + if (new_controls) { + controls->controls = new_controls; + controls->controls[controls->n_controls++] = control; + } } ControlID* get_property_control(const Controls* controls, LV2_URID property) { - for (size_t i = 0; i < controls->n_controls; ++i) { - if (controls->controls[i]->property == property) { - return controls->controls[i]; - } - } - - return NULL; + for (size_t i = 0; i < controls->n_controls; ++i) { + if (controls->controls[i]->type == PROPERTY && + controls->controls[i]->id.property == property) { + return controls->controls[i]; + } + } + + return NULL; } diff --git a/src/control.h b/src/control.h new file mode 100644 index 0000000..0109e60 --- /dev/null +++ b/src/control.h @@ -0,0 +1,97 @@ +// Copyright 2007-2022 David Robillard <d@drobilla.net> +// SPDX-License-Identifier: ISC + +#ifndef JALV_CONTROL_H +#define JALV_CONTROL_H + +#include "attributes.h" +#include "nodes.h" + +#include <lilv/lilv.h> +#include <lv2/atom/forge.h> +#include <lv2/urid/urid.h> + +#include <stdbool.h> +#include <stddef.h> +#include <stdint.h> + +// Support for plugin controls (control port or event-based) +JALV_BEGIN_DECLS + +/// Type of plugin control +typedef enum { + PORT, ///< Control port + PROPERTY ///< Property (set via atom message) +} ControlType; + +// "Interesting" value in a control's value range +typedef struct { + float value; + char* label; +} ScalePoint; + +/// Plugin control +typedef struct { + ControlType type; ///< Type of control + union { + LV2_URID property; ///< Iff type == PROPERTY + uint32_t index; ///< Iff type == PORT + } id; + LilvNode* node; ///< Port or property + LilvNode* symbol; ///< Symbol + LilvNode* label; ///< Human readable label + LilvNode* group; ///< Port/control group, or NULL + void* widget; ///< Control Widget + size_t n_points; ///< Number of scale points + ScalePoint* points; ///< Scale points + LV2_URID value_type; ///< Type of control value + LilvNode* min; ///< Minimum value + LilvNode* max; ///< Maximum value + LilvNode* def; ///< Default value + bool is_toggle; ///< Boolean (0 and 1 only) + bool is_integer; ///< Integer values only + bool is_enumeration; ///< Point values only + bool is_logarithmic; ///< Logarithmic scale + bool is_writable; ///< Writable (input) + bool is_readable; ///< Readable (output) +} ControlID; + +/// Set of plugin controls +typedef struct { + size_t n_controls; + ControlID** controls; +} Controls; + +/// Create a new ID for a control port +ControlID* +new_port_control(LilvWorld* world, + const LilvPlugin* plugin, + const LilvPort* port, + uint32_t port_index, + float sample_rate, + const JalvNodes* nodes, + const LV2_Atom_Forge* forge); + +/// Create a new ID for a property-based parameter +ControlID* +new_property_control(LilvWorld* world, + const LilvNode* property, + const JalvNodes* nodes, + LV2_URID_Map* map, + const LV2_Atom_Forge* forge); + +/// Free a control allocated with new_port_control() or new_property_control() +void +free_control(ControlID* control); + +/// Add a control to the given controls set, reallocating as necessary +void +add_control(Controls* controls, ControlID* control); + +/// Return a pointer to the control for the given property, or null +ControlID* +get_property_control(const Controls* controls, LV2_URID property); + +JALV_END_DECLS + +#endif // JALV_CONTROL_H diff --git a/src/dumper.c b/src/dumper.c new file mode 100644 index 0000000..06722d8 --- /dev/null +++ b/src/dumper.c @@ -0,0 +1,81 @@ +// Copyright 2012-2024 David Robillard <d@drobilla.net> +// SPDX-License-Identifier: ISC + +#include "dumper.h" + +#include "log.h" + +#include <lilv/lilv.h> +#include <lv2/atom/atom.h> +#include <lv2/patch/patch.h> +#include <lv2/time/time.h> +#include <lv2/urid/urid.h> +#include <serd/serd.h> +#include <sratom/sratom.h> + +#include <stdint.h> +#include <stdlib.h> + +struct JalvDumperImpl { + LV2_URID_Unmap* unmap; + SerdEnv* env; + Sratom* sratom; +}; + +JalvDumper* +jalv_dumper_new(LV2_URID_Map* const map, LV2_URID_Unmap* const unmap) +{ + JalvDumper* const dumper = (JalvDumper*)calloc(1, sizeof(JalvDumper)); + SerdEnv* const env = serd_env_new(NULL); + Sratom* const sratom = sratom_new(map); + if (!dumper || !env || !sratom) { + jalv_dumper_free(dumper); + return NULL; + } + + serd_env_set_prefix_from_strings( + env, (const uint8_t*)"patch", (const uint8_t*)LV2_PATCH_PREFIX); + serd_env_set_prefix_from_strings( + env, (const uint8_t*)"time", (const uint8_t*)LV2_TIME_PREFIX); + serd_env_set_prefix_from_strings( + env, (const uint8_t*)"xsd", (const uint8_t*)LILV_NS_XSD); + + dumper->env = env; + dumper->sratom = sratom; + dumper->unmap = unmap; + return dumper; +} + +void +jalv_dumper_free(JalvDumper* const dumper) +{ + if (dumper) { + sratom_free(dumper->sratom); + serd_env_free(dumper->env); + free(dumper); + } +} + +void +jalv_dump_atom(JalvDumper* const dumper, + FILE* const stream, + const char* const label, + const LV2_Atom* const atom, + const int color) +{ + if (dumper) { + char* const str = sratom_to_turtle(dumper->sratom, + dumper->unmap, + "jalv:", + NULL, + NULL, + atom->type, + atom->size, + LV2_ATOM_BODY_CONST(atom)); + + jalv_ansi_start(stream, color); + fprintf(stream, "\n# %s (%u bytes):\n%s\n", label, atom->size, str); + jalv_ansi_reset(stream); + free(str); + } +} diff --git a/src/dumper.h b/src/dumper.h new file mode 100644 index 0000000..60dcfe1 --- /dev/null +++ b/src/dumper.h @@ -0,0 +1,38 @@ +// Copyright 2012-2024 David Robillard <d@drobilla.net> +// SPDX-License-Identifier: ISC + +#ifndef JALV_DUMPER_H +#define JALV_DUMPER_H + +#include "attributes.h" + +#include <lv2/atom/atom.h> +#include <lv2/urid/urid.h> + +#include <stdio.h> + +// LV2 atom dumper +JALV_BEGIN_DECLS + +/// Dumper for writing atoms as Turtle for debugging +typedef struct JalvDumperImpl JalvDumper; + +/// Allocate, configure, and return a new atom dumper +JalvDumper* +jalv_dumper_new(LV2_URID_Map* map, LV2_URID_Unmap* unmap); + +/// Free memory allocated by jalv_init_dumper() +void +jalv_dumper_free(JalvDumper* dumper); + +/// Dump an atom to stdout +void +jalv_dump_atom(JalvDumper* dumper, + FILE* stream, + const char* label, + const LV2_Atom* atom, + int color); + +JALV_END_DECLS + +#endif // JALV_DUMPER_H diff --git a/src/features.c b/src/features.c new file mode 100644 index 0000000..82d8c27 --- /dev/null +++ b/src/features.c @@ -0,0 +1,62 @@ +// Copyright 2018-2024 David Robillard <d@drobilla.net> +// SPDX-License-Identifier: ISC + +#include "features.h" + +#include "macros.h" +#include "settings.h" +#include "urids.h" + +#include <lv2/options/options.h> + +#include <stdint.h> +#include <string.h> + +void +jalv_init_lv2_options(JalvFeatures* const features, + const JalvURIDs* const urids, + const JalvSettings* const settings) +{ + const LV2_Options_Option options[ARRAY_SIZE(features->options)] = { + {LV2_OPTIONS_INSTANCE, + 0, + urids->param_sampleRate, + sizeof(float), + urids->atom_Float, + &settings->sample_rate}, + {LV2_OPTIONS_INSTANCE, + 0, + urids->bufsz_minBlockLength, + sizeof(int32_t), + urids->atom_Int, + &settings->block_length}, + {LV2_OPTIONS_INSTANCE, + 0, + urids->bufsz_maxBlockLength, + sizeof(int32_t), + urids->atom_Int, + &settings->block_length}, + {LV2_OPTIONS_INSTANCE, + 0, + urids->bufsz_sequenceSize, + sizeof(int32_t), + urids->atom_Int, + &settings->midi_buf_size}, + {LV2_OPTIONS_INSTANCE, + 0, + urids->ui_updateRate, + sizeof(float), + urids->atom_Float, + &settings->ui_update_hz}, + {LV2_OPTIONS_INSTANCE, + 0, + urids->ui_scaleFactor, + sizeof(float), + urids->atom_Float, + &settings->ui_scale_factor}, + {LV2_OPTIONS_INSTANCE, 0, 0, 0, 0, NULL}}; + + memcpy(features->options, options, sizeof(features->options)); + features->options_feature.URI = LV2_OPTIONS__options; + features->options_feature.data = (void*)features->options; +} diff --git a/src/features.h b/src/features.h new file mode 100644 index 0000000..54742d7 --- /dev/null +++ b/src/features.h @@ -0,0 +1,50 @@ +// Copyright 2018-2024 David Robillard <d@drobilla.net> +// SPDX-License-Identifier: ISC + +#ifndef JALV_FEATURES_H +#define JALV_FEATURES_H + +#include "attributes.h" +#include "settings.h" +#include "urids.h" + +#include <lv2/core/lv2.h> +#include <lv2/data-access/data-access.h> +#include <lv2/log/log.h> +#include <lv2/options/options.h> +#include <lv2/state/state.h> +#include <lv2/ui/ui.h> +#include <lv2/worker/worker.h> + +// LV2 feature support +JALV_BEGIN_DECLS + +/// LV2 features and associated data to be passed to plugins +typedef struct { + LV2_Feature map_feature; + LV2_Feature unmap_feature; + LV2_State_Make_Path make_path; + LV2_Feature make_path_feature; + LV2_Worker_Schedule sched; + LV2_Feature sched_feature; + LV2_Worker_Schedule ssched; + LV2_Feature state_sched_feature; + LV2_Log_Log llog; + LV2_Feature log_feature; + LV2_Options_Option options[7]; + LV2_Feature options_feature; + LV2_Feature safe_restore_feature; + LV2UI_Request_Value request_value; + LV2_Feature request_value_feature; + LV2_Extension_Data_Feature ext_data; +} JalvFeatures; + +/// Set LV2 options feature for passing to plugin after settings are determined +void +jalv_init_lv2_options(JalvFeatures* features, + const JalvURIDs* urids, + const JalvSettings* settings); + +JALV_END_DECLS + +#endif // JALV_FEATURES_H diff --git a/src/frontend.h b/src/frontend.h new file mode 100644 index 0000000..e95fa6d --- /dev/null +++ b/src/frontend.h @@ -0,0 +1,70 @@ +// Copyright 2007-2022 David Robillard <d@drobilla.net> +// SPDX-License-Identifier: ISC + +#ifndef JALV_UI_H +#define JALV_UI_H + +#include "attributes.h" +#include "options.h" +#include "types.h" + +#include <lilv/lilv.h> + +#include <stdbool.h> +#include <stdint.h> + +// Interface that must be implemented by UIs +JALV_BEGIN_DECLS + +/// Arbitrary return code for successful early exit (for --help and so on) +#define JALV_EARLY_EXIT_STATUS (-431) + +/// Command-line arguments passed to an executable +typedef struct { + int* argc; ///< Pointer to `argc` like in `main` + char*** argv; ///< Pointer to `argv` like in `main` +} JalvFrontendArgs; + +/// Consume command-line arguments and set `opts` accordingly +int +jalv_frontend_init(JalvFrontendArgs* args, JalvOptions* opts); + +/// Return the URI of the "native" LV2 UI type +const char* +jalv_frontend_ui_type(void); + +/// Return true if an interactive frontend is available +bool +jalv_frontend_discover(const Jalv* jalv); + +/// Return the ideal refresh rate of the frontend in Hz +float +jalv_frontend_refresh_rate(const Jalv* jalv); + +/// Return the scale factor of the frontend (for example 2.0 for double sized) +float +jalv_frontend_scale_factor(const Jalv* jalv); + +/// Attempt to get a plugin URI selection from the user +LilvNode* +jalv_frontend_select_plugin(Jalv* jalv); + +/// Open and run the frontend interface, signalling jalv.done when finished +int +jalv_frontend_open(Jalv* jalv); + +/// Quit and close the frontend interface +int +jalv_frontend_close(Jalv* jalv); + +/// Called when a port event (control change or other message) is sent to the UI +void +jalv_frontend_port_event(Jalv* jalv, + uint32_t port_index, + uint32_t buffer_size, + uint32_t protocol, + const void* buffer); + +JALV_END_DECLS + +#endif // JALV_UI_H @@ -1,577 +1,481 @@ -/* - Copyright 2007-2016 David Robillard <http://drobilla.net> - - Permission to use, copy, modify, and/or distribute this software for any - purpose with or without fee is hereby granted, provided that the above - copyright notice and this permission notice appear in all copies. - - THIS SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES - WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF - MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR - ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES - WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN - ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF - OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. -*/ - -#include "jalv_internal.h" -#include "worker.h" +// Copyright 2007-2024 David Robillard <d@drobilla.net> +// SPDX-License-Identifier: ISC + +#include "backend.h" + +#include "comm.h" +#include "jack_impl.h" +#include "jalv_config.h" +#include "log.h" +#include "lv2_evbuf.h" +#include "process.h" +#include "process_setup.h" +#include "settings.h" +#include "string_utils.h" +#include "types.h" +#include "urids.h" + +#include <lilv/lilv.h> +#include <lv2/atom/atom.h> +#include <lv2/atom/forge.h> +#include <lv2/urid/urid.h> +#include <zix/sem.h> #include <jack/jack.h> #include <jack/midiport.h> -#ifdef JALV_JACK_SESSION -# include <jack/session.h> -#endif -#ifdef HAVE_JACK_METADATA -# include <jack/metadata.h> -#endif +#include <jack/transport.h> +#include <jack/types.h> -#include <ctype.h> +#if USE_JACK_METADATA +# include <jack/metadata.h> +#endif -struct JalvBackend { - jack_client_t* client; ///< Jack client - bool is_internal_client; ///< Running inside jackd -}; +#include <stdbool.h> +#include <stdint.h> +#include <stdio.h> +#include <stdlib.h> +#include <string.h> -/** Internal Jack client initialization entry point */ -int jack_initialize(jack_client_t* client, const char* load_init); +#ifdef __clang__ +# define REALTIME __attribute__((annotate("realtime"))) +#else +# define REALTIME +#endif -/** Internal Jack client finalization entry point */ -void jack_finish(void* arg); +/// Maximum supported latency in frames (at most 2^24 so all integers work) +static const float max_latency = 16777216.0f; -/** Jack buffer size callback. */ +/// Jack buffer size callback static int -jack_buffer_size_cb(jack_nframes_t nframes, void* data) +buffer_size_cb(jack_nframes_t nframes, void* data) { - Jalv* const jalv = (Jalv*)data; - jalv->block_length = nframes; - jalv->buf_size_set = true; -#ifdef HAVE_JACK_PORT_TYPE_GET_BUFFER_SIZE - jalv->midi_buf_size = jack_port_type_get_buffer_size( - jalv->backend->client, JACK_DEFAULT_MIDI_TYPE); + JalvBackend* const backend = (JalvBackend*)data; + JalvSettings* const settings = backend->settings; + JalvProcess* const proc = backend->process; + + settings->block_length = nframes; +#if USE_JACK_PORT_TYPE_GET_BUFFER_SIZE + settings->midi_buf_size = + jack_port_type_get_buffer_size(backend->client, JACK_DEFAULT_MIDI_TYPE); #endif - jalv_allocate_port_buffers(jalv); - return 0; + if (proc->run_state == JALV_RUNNING) { + jalv_process_activate(proc, backend->urids, proc->instance, settings); + } + return 0; } -/** Jack shutdown callback. */ +/// Jack shutdown callback static void -jack_shutdown_cb(void* data) +shutdown_cb(void* data) { - Jalv* const jalv = (Jalv*)data; - jalv_close_ui(jalv); - zix_sem_post(&jalv->done); + JalvBackend* const backend = (JalvBackend*)data; + zix_sem_post(backend->done); } -/** Jack process callback. */ -static REALTIME int -jack_process_cb(jack_nframes_t nframes, void* data) +static void +forge_position(LV2_Atom_Forge* const forge, + const JalvURIDs* const urids, + const jack_transport_state_t state, + const jack_position_t pos) { - Jalv* const jalv = (Jalv*)data; - jack_client_t* client = jalv->backend->client; - - /* Get Jack transport position */ - jack_position_t pos; - const bool rolling = (jack_transport_query(client, &pos) - == JackTransportRolling); - - /* If transport state is not as expected, then something has changed */ - const bool xport_changed = (rolling != jalv->rolling || - pos.frame != jalv->position || - pos.beats_per_minute != jalv->bpm); - - uint8_t pos_buf[256]; - LV2_Atom* lv2_pos = (LV2_Atom*)pos_buf; - if (xport_changed) { - /* Build an LV2 position object to report change to plugin */ - lv2_atom_forge_set_buffer(&jalv->forge, pos_buf, sizeof(pos_buf)); - LV2_Atom_Forge* forge = &jalv->forge; - LV2_Atom_Forge_Frame frame; - lv2_atom_forge_object(forge, &frame, 0, jalv->urids.time_Position); - lv2_atom_forge_key(forge, jalv->urids.time_frame); - lv2_atom_forge_long(forge, pos.frame); - lv2_atom_forge_key(forge, jalv->urids.time_speed); - lv2_atom_forge_float(forge, rolling ? 1.0 : 0.0); - if (pos.valid & JackPositionBBT) { - lv2_atom_forge_key(forge, jalv->urids.time_barBeat); - lv2_atom_forge_float( - forge, pos.beat - 1 + (pos.tick / pos.ticks_per_beat)); - lv2_atom_forge_key(forge, jalv->urids.time_bar); - lv2_atom_forge_long(forge, pos.bar - 1); - lv2_atom_forge_key(forge, jalv->urids.time_beatUnit); - lv2_atom_forge_int(forge, pos.beat_type); - lv2_atom_forge_key(forge, jalv->urids.time_beatsPerBar); - lv2_atom_forge_float(forge, pos.beats_per_bar); - lv2_atom_forge_key(forge, jalv->urids.time_beatsPerMinute); - lv2_atom_forge_float(forge, pos.beats_per_minute); - } - - if (jalv->opts.dump) { - char* str = sratom_to_turtle( - jalv->sratom, &jalv->unmap, "time:", NULL, NULL, - lv2_pos->type, lv2_pos->size, LV2_ATOM_BODY(lv2_pos)); - jalv_ansi_start(stdout, 36); - printf("\n## Position ##\n%s\n", str); - jalv_ansi_reset(stdout); - free(str); - } - } - - /* Update transport state to expected values for next cycle */ - jalv->position = rolling ? pos.frame + nframes : pos.frame; - jalv->bpm = pos.beats_per_minute; - jalv->rolling = rolling; - - switch (jalv->play_state) { - case JALV_PAUSE_REQUESTED: - jalv->play_state = JALV_PAUSED; - zix_sem_post(&jalv->paused); - break; - case JALV_PAUSED: - for (uint32_t p = 0; p < jalv->num_ports; ++p) { - jack_port_t* jport = jalv->ports[p].sys_port; - if (jport && jalv->ports[p].flow == FLOW_OUTPUT) { - void* buf = jack_port_get_buffer(jport, nframes); - if (jalv->ports[p].type == TYPE_EVENT) { - jack_midi_clear_buffer(buf); - } else { - memset(buf, '\0', nframes * sizeof(float)); - } - } - } - return 0; - default: - break; - } - - /* Prepare port buffers */ - for (uint32_t p = 0; p < jalv->num_ports; ++p) { - struct Port* port = &jalv->ports[p]; - if (port->type == TYPE_AUDIO && port->sys_port) { - /* Connect plugin port directly to Jack port buffer */ - lilv_instance_connect_port( - jalv->instance, p, - jack_port_get_buffer(port->sys_port, nframes)); -#ifdef HAVE_JACK_METADATA - } else if (port->type == TYPE_CV && port->sys_port) { - /* Connect plugin port directly to Jack port buffer */ - lilv_instance_connect_port( - jalv->instance, p, - jack_port_get_buffer(port->sys_port, nframes)); -#endif - } else if (port->type == TYPE_EVENT && port->flow == FLOW_INPUT) { - lv2_evbuf_reset(port->evbuf, true); - - /* Write transport change event if applicable */ - LV2_Evbuf_Iterator iter = lv2_evbuf_begin(port->evbuf); - if (xport_changed) { - lv2_evbuf_write(&iter, 0, 0, - lv2_pos->type, lv2_pos->size, - (const uint8_t*)LV2_ATOM_BODY(lv2_pos)); - } - - if (jalv->request_update) { - /* Plugin state has changed, request an update */ - const LV2_Atom_Object get = { - { sizeof(LV2_Atom_Object_Body), jalv->urids.atom_Object }, - { 0, jalv->urids.patch_Get } }; - lv2_evbuf_write(&iter, 0, 0, - get.atom.type, get.atom.size, - (const uint8_t*)LV2_ATOM_BODY(&get)); - } - - if (port->sys_port) { - /* Write Jack MIDI input */ - void* buf = jack_port_get_buffer(port->sys_port, nframes); - for (uint32_t i = 0; i < jack_midi_get_event_count(buf); ++i) { - jack_midi_event_t ev; - jack_midi_event_get(&ev, buf, i); - lv2_evbuf_write(&iter, - ev.time, 0, - jalv->urids.midi_MidiEvent, - ev.size, ev.buffer); - } - } - } else if (port->type == TYPE_EVENT) { - /* Clear event output for plugin to write to */ - lv2_evbuf_reset(port->evbuf, false); - } - } - jalv->request_update = false; - - /* Run plugin for this cycle */ - const bool send_ui_updates = jalv_run(jalv, nframes); - - /* Deliver MIDI output and UI events */ - for (uint32_t p = 0; p < jalv->num_ports; ++p) { - struct Port* const port = &jalv->ports[p]; - if (port->flow == FLOW_OUTPUT && port->type == TYPE_CONTROL && - lilv_port_has_property(jalv->plugin, port->lilv_port, - jalv->nodes.lv2_reportsLatency)) { - if (jalv->plugin_latency != port->control) { - jalv->plugin_latency = port->control; - jack_recompute_total_latencies(client); - } - } else if (port->flow == FLOW_OUTPUT && port->type == TYPE_EVENT) { - void* buf = NULL; - if (port->sys_port) { - buf = jack_port_get_buffer(port->sys_port, nframes); - jack_midi_clear_buffer(buf); - } - - for (LV2_Evbuf_Iterator i = lv2_evbuf_begin(port->evbuf); - lv2_evbuf_is_valid(i); - i = lv2_evbuf_next(i)) { - // Get event from LV2 buffer - uint32_t frames, subframes, type, size; - uint8_t* body; - lv2_evbuf_get(i, &frames, &subframes, &type, &size, &body); - - if (buf && type == jalv->urids.midi_MidiEvent) { - // Write MIDI event to Jack output - jack_midi_event_write(buf, frames, body, size); - } - - if (jalv->has_ui) { - // Forward event to UI - jalv_send_to_ui(jalv, p, type, size, body); - } - } - } else if (send_ui_updates && - port->flow == FLOW_OUTPUT && port->type == TYPE_CONTROL) { - char buf[sizeof(ControlChange) + sizeof(float)]; - ControlChange* ev = (ControlChange*)buf; - ev->index = p; - ev->protocol = 0; - ev->size = sizeof(float); - *(float*)ev->body = port->control; - if (zix_ring_write(jalv->plugin_events, buf, sizeof(buf)) - < sizeof(buf)) { - fprintf(stderr, "Plugin => UI buffer overflow!\n"); - } - } - } - - return 0; + LV2_Atom_Forge_Frame frame; + lv2_atom_forge_object(forge, &frame, 0, urids->time_Position); + lv2_atom_forge_key(forge, urids->time_frame); + lv2_atom_forge_long(forge, pos.frame); + lv2_atom_forge_key(forge, urids->time_speed); + lv2_atom_forge_float(forge, (state == JackTransportRolling) ? 1.0 : 0.0); + if ((pos.valid & JackPositionBBT)) { + lv2_atom_forge_key(forge, urids->time_barBeat); + lv2_atom_forge_float(forge, pos.beat - 1 + (pos.tick / pos.ticks_per_beat)); + lv2_atom_forge_key(forge, urids->time_bar); + lv2_atom_forge_long(forge, pos.bar - 1); + lv2_atom_forge_key(forge, urids->time_beatUnit); + lv2_atom_forge_int(forge, pos.beat_type); + lv2_atom_forge_key(forge, urids->time_beatsPerBar); + lv2_atom_forge_float(forge, pos.beats_per_bar); + lv2_atom_forge_key(forge, urids->time_beatsPerMinute); + lv2_atom_forge_float(forge, pos.beats_per_minute); + } } -/** Calculate latency assuming all ports depend on each other. */ -static void -jack_latency_cb(jack_latency_callback_mode_t mode, void* data) +static int +process_silent(JalvProcess* const proc, const jack_nframes_t nframes) +{ + for (uint32_t p = 0U; p < proc->num_ports; ++p) { + const JalvProcessPort* const port = &proc->ports[p]; + jack_port_t* const jport = (jack_port_t*)proc->ports[p].sys_port; + if (jport && port->flow == FLOW_OUTPUT) { + void* const buf = jack_port_get_buffer(jport, nframes); + if (port->type == TYPE_EVENT) { + jack_midi_clear_buffer(buf); + } else { + memset(buf, '\0', nframes * sizeof(float)); + } + } + } + + return jalv_bypass(proc, nframes); +} + +static bool +process_transport(JalvProcess* const proc, + const jack_transport_state_t state, + const jack_position_t pos, + const jack_nframes_t nframes) { - Jalv* const jalv = (Jalv*)data; - const enum PortFlow flow = ((mode == JackCaptureLatency) - ? FLOW_INPUT : FLOW_OUTPUT); - - /* First calculate the min/max latency of all feeding ports */ - uint32_t ports_found = 0; - jack_latency_range_t range = { UINT32_MAX, 0 }; - for (uint32_t p = 0; p < jalv->num_ports; ++p) { - struct Port* port = &jalv->ports[p]; - if (port->sys_port && port->flow == flow) { - jack_latency_range_t r; - jack_port_get_latency_range(port->sys_port, mode, &r); - if (r.min < range.min) { range.min = r.min; } - if (r.max > range.max) { range.max = r.max; } - ++ports_found; - } - } - - if (ports_found == 0) { - range.min = 0; - } - - /* Add the plugin's own latency */ - range.min += jalv->plugin_latency; - range.max += jalv->plugin_latency; - - /* Tell Jack about it */ - for (uint32_t p = 0; p < jalv->num_ports; ++p) { - struct Port* port = &jalv->ports[p]; - if (port->sys_port && port->flow == flow) { - jack_port_set_latency_range(port->sys_port, mode, &range); - } - } + // If transport state is not as expected, then something has changed + const bool rolling = state == JackTransportRolling; + const bool has_bbt = (pos.valid & JackPositionBBT); + const bool xport_changed = + (rolling != proc->rolling || pos.frame != proc->position || + (has_bbt && pos.beats_per_minute != proc->bpm)); + + // Update transport state to expected values for next cycle + proc->position = rolling ? pos.frame + nframes : pos.frame; + proc->bpm = has_bbt ? pos.beats_per_minute : proc->bpm; + proc->rolling = rolling; + + return xport_changed; } -#ifdef JALV_JACK_SESSION +/// Jack process callback +static REALTIME int +process_cb(jack_nframes_t nframes, void* data) +{ + JalvBackend* const backend = (JalvBackend*)data; + const JalvURIDs* const urids = backend->urids; + JalvProcess* const proc = backend->process; + jack_client_t* const client = backend->client; + uint64_t pos_buf[64] = {0U}; + LV2_Atom* const lv2_pos = (LV2_Atom*)pos_buf; + + // If execution is paused, emit silence and return + if (proc->run_state == JALV_PAUSED) { + return process_silent(proc, nframes); + } + + // Get transport state and position + jack_position_t pos = {0U}; + const jack_transport_state_t state = jack_transport_query(client, &pos); + + // Check if transport is discontinuous from last time and update state + const bool xport_changed = process_transport(proc, state, pos, nframes); + if (xport_changed) { + // Build an LV2 position object to report change to plugin + lv2_atom_forge_set_buffer(&proc->forge, (uint8_t*)pos_buf, sizeof(pos_buf)); + forge_position(&proc->forge, urids, state, pos); + } + + // Prepare port buffers + for (uint32_t p = 0; p < proc->num_ports; ++p) { + JalvProcessPort* const port = &proc->ports[p]; + if (port->sys_port && (port->type == TYPE_AUDIO || port->type == TYPE_CV)) { + // Connect plugin port directly to Jack port buffer + lilv_instance_connect_port( + proc->instance, p, jack_port_get_buffer(port->sys_port, nframes)); + } else if (port->type == TYPE_EVENT && port->flow == FLOW_INPUT) { + lv2_evbuf_reset(port->evbuf, true); + LV2_Evbuf_Iterator iter = lv2_evbuf_begin(port->evbuf); + + if (port->is_primary && xport_changed) { + // Write new transport position + lv2_evbuf_write( + &iter, 0, 0, lv2_pos->type, lv2_pos->size, LV2_ATOM_BODY(lv2_pos)); + } + + if (port->sys_port) { + // Write Jack MIDI input + void* buf = jack_port_get_buffer(port->sys_port, nframes); + for (uint32_t i = 0; i < jack_midi_get_event_count(buf); ++i) { + jack_midi_event_t ev; + jack_midi_event_get(&ev, buf, i); + lv2_evbuf_write( + &iter, ev.time, 0, urids->midi_MidiEvent, ev.size, ev.buffer); + } + } + } else if (port->type == TYPE_EVENT) { + // Clear event output for plugin to write to + lv2_evbuf_reset(port->evbuf, false); + } + } + + // Run plugin for this cycle + const bool send_ui_updates = jalv_run(proc, nframes); + + // Deliver MIDI output and UI events + for (uint32_t p = 0; p < proc->num_ports; ++p) { + JalvProcessPort* const port = &proc->ports[p]; + if (port->flow == FLOW_OUTPUT && port->type == TYPE_CONTROL && + port->reports_latency) { + // Get the latency in frames from the control output truncated to integer + const float value = proc->controls_buf[p]; + const uint32_t frames = + (value >= 0.0f && value <= max_latency) ? (uint32_t)value : 0U; + + if (proc->plugin_latency != frames) { + // Update the cached value and notify the UI if the latency changed + proc->plugin_latency = frames; + + const JalvLatencyChange body = {frames}; + const JalvMessageHeader header = {LATENCY_CHANGE, sizeof(body)}; + jalv_write_split_message( + proc->plugin_to_ui, &header, sizeof(header), &body, sizeof(body)); + } + } else if (port->flow == FLOW_OUTPUT && port->type == TYPE_EVENT) { + void* buf = NULL; + if (port->sys_port) { + buf = jack_port_get_buffer(port->sys_port, nframes); + jack_midi_clear_buffer(buf); + } + + for (LV2_Evbuf_Iterator i = lv2_evbuf_begin(port->evbuf); + lv2_evbuf_is_valid(i); + i = lv2_evbuf_next(i)) { + // Get event from LV2 buffer + uint32_t frames = 0; + uint32_t subframes = 0; + LV2_URID type = 0; + uint32_t size = 0; + void* body = NULL; + lv2_evbuf_get(i, &frames, &subframes, &type, &size, &body); + + if (buf && type == urids->midi_MidiEvent) { + // Write MIDI event to Jack output + jack_midi_event_write(buf, frames, body, size); + } + + if (proc->has_ui) { + // Forward event to UI + jalv_write_event(proc->plugin_to_ui, p, size, type, body); + } + } + } else if (send_ui_updates && port->flow == FLOW_OUTPUT && + port->type == TYPE_CONTROL) { + jalv_write_control(proc->plugin_to_ui, p, proc->controls_buf[p]); + } + } + + return 0; +} + +/// Jack latency callback static void -jack_session_cb(jack_session_event_t* event, void* arg) +latency_cb(const jack_latency_callback_mode_t mode, void* const data) { - Jalv* const jalv = (Jalv*)arg; - - #define MAX_CMD_LEN 256 - event->command_line = (char*)malloc(MAX_CMD_LEN); - snprintf(event->command_line, MAX_CMD_LEN, "%s -u %s -l \"${SESSION_DIR}\"", - jalv->prog_name, - event->client_uuid); - - switch (event->type) { - case JackSessionSave: - case JackSessionSaveTemplate: - jalv_save(jalv, event->session_dir); - break; - case JackSessionSaveAndQuit: - jalv_save(jalv, event->session_dir); - jalv_close_ui(jalv); - break; - } - - jack_session_reply(jalv->backend->client, event); - jack_session_event_free(event); + // Calculate latency assuming all ports depend on each other + + const JalvBackend* const backend = (JalvBackend*)data; + const JalvProcess* const proc = backend->process; + const PortFlow flow = + ((mode == JackCaptureLatency) ? FLOW_INPUT : FLOW_OUTPUT); + + // First calculate the min/max latency of all feeding ports + uint32_t ports_found = 0; + jack_latency_range_t range = {UINT32_MAX, 0}; + for (uint32_t p = 0; p < proc->num_ports; ++p) { + JalvProcessPort* const port = &proc->ports[p]; + if (port->sys_port && port->flow == flow) { + jack_latency_range_t r; + jack_port_get_latency_range(port->sys_port, mode, &r); + if (r.min < range.min) { + range.min = r.min; + } + if (r.max > range.max) { + range.max = r.max; + } + ++ports_found; + } + } + + if (ports_found == 0) { + range.min = 0; + } + + // Add the plugin's own latency + range.min += proc->plugin_latency; + range.max += proc->plugin_latency; + + // Tell Jack about it + for (uint32_t p = 0; p < proc->num_ports; ++p) { + const JalvProcessPort* const port = &proc->ports[p]; + if (port->sys_port && port->flow == flow) { + jack_port_set_latency_range(port->sys_port, mode, &range); + } + } } -#endif /* JALV_JACK_SESSION */ static jack_client_t* -jack_create_client(Jalv* jalv) +create_client(const char* const name, const bool exact_name) { - jack_client_t* client = NULL; - - /* Determine the name of the JACK client */ - char* jack_name = NULL; - if (jalv->opts.name) { - /* Name given on command line */ - jack_name = jalv_strdup(jalv->opts.name); - } else { - /* Use plugin name */ - LilvNode* name = lilv_plugin_get_name(jalv->plugin); - jack_name = jalv_strdup(lilv_node_as_string(name)); - lilv_node_free(name); - } - - /* Truncate client name to suit JACK if necessary */ - if (strlen(jack_name) >= (unsigned)jack_client_name_size() - 1) { - jack_name[jack_client_name_size() - 1] = '\0'; - } - - /* Connect to JACK */ -#ifdef JALV_JACK_SESSION - if (jalv->opts.uuid) { - client = jack_client_open( - jack_name, - (jack_options_t)(JackSessionID | - (jalv->opts.name_exact ? JackUseExactName : 0)), - NULL, - jalv->opts.uuid); - } -#endif + char* const jack_name = jalv_strdup(name); + + // Truncate client name to suit JACK if necessary + if (strlen(jack_name) >= (unsigned)jack_client_name_size() - 1) { + jack_name[jack_client_name_size() - 1] = '\0'; + } - if (!client) { - client = jack_client_open( - jack_name, - (jalv->opts.name_exact ? JackUseExactName : JackNullOption), - NULL); - } + // Connect to JACK + jack_client_t* const client = jack_client_open( + jack_name, (exact_name ? JackUseExactName : JackNullOption), NULL); - free(jack_name); + free(jack_name); - return client; + return client; } JalvBackend* -jalv_backend_init(Jalv* jalv) +jalv_backend_allocate(void) { - jack_client_t* const client = - jalv->backend ? jalv->backend->client : jack_create_client(jalv); - - if (!client) { - return NULL; - } - - printf("JACK Name: %s\n", jack_get_client_name(client)); - - /* Set audio engine properties */ - jalv->sample_rate = (float)jack_get_sample_rate(client); - jalv->block_length = jack_get_buffer_size(client); - jalv->midi_buf_size = 4096; -#ifdef HAVE_JACK_PORT_TYPE_GET_BUFFER_SIZE - jalv->midi_buf_size = jack_port_type_get_buffer_size( - client, JACK_DEFAULT_MIDI_TYPE); -#endif + return (JalvBackend*)calloc(1, sizeof(JalvBackend)); +} + +void +jalv_backend_free(JalvBackend* const backend) +{ + free(backend); +} - /* Set JACK callbacks */ - void* const arg = (void*)jalv; - jack_set_process_callback(client, &jack_process_cb, arg); - jack_set_buffer_size_callback(client, &jack_buffer_size_cb, arg); - jack_on_shutdown(client, &jack_shutdown_cb, arg); - jack_set_latency_callback(client, &jack_latency_cb, arg); -#ifdef JALV_JACK_SESSION - jack_set_session_callback(client, &jack_session_cb, arg); +int +jalv_backend_open(JalvBackend* const backend, + const JalvURIDs* const urids, + JalvSettings* const settings, + JalvProcess* const process, + ZixSem* const done, + const char* const name, + const bool exact_name) +{ + jack_client_t* const client = + backend->client ? backend->client : create_client(name, exact_name); + + if (!client) { + return 1; + } + + jalv_log(JALV_LOG_INFO, "JACK name: %s\n", jack_get_client_name(client)); + + // Set audio engine properties + settings->sample_rate = (float)jack_get_sample_rate(client); + settings->block_length = jack_get_buffer_size(client); + settings->midi_buf_size = 4096; +#if USE_JACK_PORT_TYPE_GET_BUFFER_SIZE + settings->midi_buf_size = + jack_port_type_get_buffer_size(client, JACK_DEFAULT_MIDI_TYPE); #endif - if (jalv->backend) { - /* Internal JACK client, jalv->backend->is_internal_client was already - set in jack_initialize() when allocating the backend */ - return jalv->backend; - } - - /* External JACK client, allocate and return opaque backend */ - JalvBackend* backend = (JalvBackend*)calloc(1, sizeof(JalvBackend)); - backend->client = client; - backend->is_internal_client = false; - return backend; + // Set JACK callbacks + void* const arg = (void*)backend; + jack_set_process_callback(client, &process_cb, arg); + jack_set_buffer_size_callback(client, &buffer_size_cb, arg); + jack_on_shutdown(client, &shutdown_cb, arg); + jack_set_latency_callback(client, &latency_cb, arg); + + backend->urids = urids; + backend->settings = settings; + backend->process = process; + backend->done = done; + backend->client = client; + backend->is_internal_client = false; + return 0; } void -jalv_backend_close(Jalv* jalv) +jalv_backend_close(JalvBackend* const backend) { - if (jalv->backend) { - if (!jalv->backend->is_internal_client) { - jack_client_close(jalv->backend->client); - } - - free(jalv->backend); - jalv->backend = NULL; - } + if (backend && backend->client && !backend->is_internal_client) { + jack_client_close(backend->client); + } } void -jalv_backend_activate(Jalv* jalv) +jalv_backend_activate(JalvBackend* const backend) { - jack_activate(jalv->backend->client); + jack_activate(backend->client); } void -jalv_backend_deactivate(Jalv* jalv) +jalv_backend_deactivate(JalvBackend* const backend) { - if (jalv->backend && !jalv->backend->is_internal_client) { - jack_deactivate(jalv->backend->client); - } + if (!backend->is_internal_client && backend->client) { + jack_deactivate(backend->client); + } } void -jalv_backend_activate_port(Jalv* jalv, uint32_t port_index) +jalv_backend_activate_port(JalvBackend* const backend, + JalvProcess* const proc, + const uint32_t port_index) { - jack_client_t* client = jalv->backend->client; - struct Port* const port = &jalv->ports[port_index]; - - const LilvNode* sym = lilv_port_get_symbol(jalv->plugin, port->lilv_port); - - /* Connect unsupported ports to NULL (known to be optional by this point) */ - if (port->flow == FLOW_UNKNOWN || port->type == TYPE_UNKNOWN) { - lilv_instance_connect_port(jalv->instance, port_index, NULL); - return; - } - - /* Build Jack flags for port */ - enum JackPortFlags jack_flags = (port->flow == FLOW_INPUT) - ? JackPortIsInput - : JackPortIsOutput; - - /* Connect the port based on its type */ - switch (port->type) { - case TYPE_CONTROL: - lilv_instance_connect_port(jalv->instance, port_index, &port->control); - break; - case TYPE_AUDIO: - port->sys_port = jack_port_register( - client, lilv_node_as_string(sym), - JACK_DEFAULT_AUDIO_TYPE, jack_flags, 0); - break; -#ifdef HAVE_JACK_METADATA - case TYPE_CV: - port->sys_port = jack_port_register( - client, lilv_node_as_string(sym), - JACK_DEFAULT_AUDIO_TYPE, jack_flags, 0); - if (port->sys_port) { - jack_set_property(client, jack_port_uuid(port->sys_port), - "http://jackaudio.org/metadata/signal-type", "CV", - "text/plain"); - } - break; + jack_client_t* const client = backend->client; + JalvProcessPort* const port = &proc->ports[port_index]; + + // Connect unsupported ports to NULL (known to be optional by this point) + if (port->flow == FLOW_UNKNOWN || port->type == TYPE_UNKNOWN) { + lilv_instance_connect_port(proc->instance, port_index, NULL); + return; + } + + // Build Jack flags for port + enum JackPortFlags jack_flags = + (port->flow == FLOW_INPUT) ? JackPortIsInput : JackPortIsOutput; + + // Connect the port based on its type + switch (port->type) { + case TYPE_UNKNOWN: + break; + case TYPE_CONTROL: + lilv_instance_connect_port( + proc->instance, port_index, &proc->controls_buf[port_index]); + break; + case TYPE_AUDIO: + port->sys_port = jack_port_register( + client, port->symbol, JACK_DEFAULT_AUDIO_TYPE, jack_flags, 0); + break; +#if USE_JACK_METADATA + case TYPE_CV: + port->sys_port = jack_port_register( + client, port->symbol, JACK_DEFAULT_AUDIO_TYPE, jack_flags, 0); + if (port->sys_port) { + jack_set_property(client, + jack_port_uuid(port->sys_port), + "http://jackaudio.org/metadata/signal-type", + "CV", + "text/plain"); + } + break; #endif - case TYPE_EVENT: - if (lilv_port_supports_event( - jalv->plugin, port->lilv_port, jalv->nodes.midi_MidiEvent)) { - port->sys_port = jack_port_register( - client, lilv_node_as_string(sym), - JACK_DEFAULT_MIDI_TYPE, jack_flags, 0); - } - break; - default: - break; - } - -#ifdef HAVE_JACK_METADATA - if (port->sys_port) { - // Set port order to index - char index_str[16]; - snprintf(index_str, sizeof(index_str), "%d", port_index); - jack_set_property(client, jack_port_uuid(port->sys_port), - "http://jackaudio.org/metadata/order", index_str, - "http://www.w3.org/2001/XMLSchema#integer"); - - // Set port pretty name to label - LilvNode* name = lilv_port_get_name(jalv->plugin, port->lilv_port); - jack_set_property(client, jack_port_uuid(port->sys_port), - JACK_METADATA_PRETTY_NAME, lilv_node_as_string(name), - "text/plain"); - lilv_node_free(name); - } + case TYPE_EVENT: + if (port->supports_midi) { + port->sys_port = jack_port_register( + client, port->symbol, JACK_DEFAULT_MIDI_TYPE, jack_flags, 0); + } + break; + } + +#if USE_JACK_METADATA + if (port->sys_port) { + // Set port order to index + char index_str[16]; + snprintf(index_str, sizeof(index_str), "%u", port_index); + jack_set_property(client, + jack_port_uuid(port->sys_port), + "http://jackaudio.org/metadata/order", + index_str, + "http://www.w3.org/2001/XMLSchema#integer"); + + // Set port pretty name to label + if (port->label) { + jack_set_property(client, + jack_port_uuid(port->sys_port), + JACK_METADATA_PRETTY_NAME, + port->label, + "text/plain"); + } + } #endif } -int -jack_initialize(jack_client_t* const client, const char* const load_init) -{ - const size_t args_len = strlen(load_init); - if (args_len > JACK_LOAD_INIT_LIMIT) { - fprintf(stderr, "error: Too many arguments given\n"); - return -1; - } - - Jalv* const jalv = (Jalv*)calloc(1, sizeof(Jalv)); - if (!jalv) { - return -1; - } - - if (!(jalv->backend = (JalvBackend*)calloc(1, sizeof(JalvBackend)))) { - free(jalv); - return -1; - } - - jalv->backend->client = client; - jalv->backend->is_internal_client = true; - - /* Build full command line with "program" name for building argv */ - const size_t cmd_len = strlen("jalv ") + args_len; - char* const cmd = (char*)calloc(cmd_len + 1, 1); - strcat(cmd, "jalv "); - strcat(cmd, load_init); - - /* Build argv */ - int argc = 0; - char** argv = NULL; - char* tok = cmd; - for (size_t i = 0; i <= cmd_len; ++i) { - if (isspace(cmd[i]) || !cmd[i]) { - argv = (char**)realloc(argv, sizeof(char*) * ++argc); - cmd[i] = '\0'; - argv[argc - 1] = tok; - tok = cmd + i + 1; - } - } - - const int err = jalv_open(jalv, &argc, &argv); - if (err) { - jalv_backend_close(jalv); - free(jalv); - } - - free(argv); - free(cmd); - return err; -} - void -jack_finish(void* const arg) +jalv_backend_recompute_latencies(JalvBackend* const backend) { - Jalv* const jalv = (Jalv*)arg; - if (jalv) { - if (jalv_close(jalv)) { - fprintf(stderr, "Failed to close Jalv\n"); - } - - free(jalv); - } + jack_recompute_total_latencies(backend->client); } diff --git a/src/jack_impl.h b/src/jack_impl.h new file mode 100644 index 0000000..241ea85 --- /dev/null +++ b/src/jack_impl.h @@ -0,0 +1,31 @@ +// Copyright 2007-2024 David Robillard <d@drobilla.net> +// SPDX-License-Identifier: ISC + +#ifndef JALV_JACK_IMPL_H +#define JALV_JACK_IMPL_H + +#include "attributes.h" +#include "process.h" +#include "settings.h" +#include "urids.h" + +#include <jack/types.h> +#include <zix/sem.h> + +#include <stdbool.h> + +// Definition of Jack backend structure (private to implementation) +JALV_BEGIN_DECLS + +struct JalvBackendImpl { + const JalvURIDs* urids; ///< Application vocabulary + JalvSettings* settings; ///< Run settings + JalvProcess* process; ///< Process thread state + ZixSem* done; ///< Shutdown semaphore + jack_client_t* client; ///< Jack client + bool is_internal_client; ///< Running inside jackd +}; + +JALV_END_DECLS + +#endif // JALV_JACK_IMPL_H diff --git a/src/jack_internal.c b/src/jack_internal.c new file mode 100644 index 0000000..5157e43 --- /dev/null +++ b/src/jack_internal.c @@ -0,0 +1,109 @@ +// Copyright 2007-2024 David Robillard <d@drobilla.net> +// SPDX-License-Identifier: ISC + +#include "backend.h" +#include "jack_impl.h" +#include "jalv.h" +#include "log.h" +#include "types.h" + +#include <jack/types.h> + +#include <ctype.h> +#include <stdbool.h> +#include <stdio.h> +#include <stdlib.h> +#include <string.h> + +/// Internal Jack client initialization entry point +int +jack_initialize(jack_client_t* client, const char* load_init); + +/// Internal Jack client finalization entry point +void +jack_finish(void* arg); + +int +jack_initialize(jack_client_t* const client, const char* const load_init) +{ +#ifndef E2BIG +# define E2BIG 7 +#endif +#ifndef ENOMEM +# define ENOMEM 12 +#endif + + const size_t args_len = strlen(load_init); + if (args_len > JACK_LOAD_INIT_LIMIT) { + jalv_log(JALV_LOG_ERR, "Too many arguments given\n"); + return E2BIG; + } + + Jalv* const jalv = (Jalv*)calloc(1, sizeof(Jalv)); + if (!jalv) { + return ENOMEM; + } + + if (!(jalv->backend = jalv_backend_allocate())) { + free(jalv); + return ENOMEM; + } + + jalv->backend->client = client; + jalv->backend->is_internal_client = true; + + // Build full command line with "program" name for building argv + const size_t cmd_len = strlen("jalv ") + args_len; + char* const cmd = (char*)calloc(cmd_len + 1, 1); + memcpy(cmd, "jalv ", strlen("jalv ") + 1); + memcpy(cmd + 5, load_init, args_len + 1); + + // Build argv + int argc = 0; + char** argv = NULL; + char* tok = cmd; + int err = 0; + for (size_t i = 0; !err && i <= cmd_len; ++i) { + if (isspace(cmd[i]) || !cmd[i]) { + char** const new_argv = (char**)realloc(argv, sizeof(char*) * ++argc); + if (!new_argv) { + err = ENOMEM; + break; + } + + argv = new_argv; + cmd[i] = '\0'; + argv[argc - 1] = tok; + tok = cmd + i + 1; + } + } + + if (err || (err = jalv_open(jalv, &argc, &argv))) { + jalv_close(jalv); + free(jalv); + } else { + jalv_activate(jalv); + } + + free(argv); + free(cmd); + return err; + +#undef ENOMEM +#undef E2BIG +} + +void +jack_finish(void* const arg) +{ + Jalv* const jalv = (Jalv*)arg; + if (jalv) { + jalv_deactivate(jalv); + if (jalv_close(jalv)) { + jalv_log(JALV_LOG_ERR, "Failed to close Jalv\n"); + } + + jalv_backend_free(jalv->backend); + free(jalv); + } +} @@ -1,264 +1,180 @@ -/* - Copyright 2007-2016 David Robillard <http://drobilla.net> - - Permission to use, copy, modify, and/or distribute this software for any - purpose with or without fee is hereby granted, provided that the above - copyright notice and this permission notice appear in all copies. - - THIS SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES - WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF - MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR - ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES - WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN - ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF - OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. -*/ +// Copyright 2007-2024 David Robillard <d@drobilla.net> +// SPDX-License-Identifier: ISC -#define _POSIX_C_SOURCE 200809L /* for mkdtemp */ -#define _DARWIN_C_SOURCE /* for mkdtemp on OSX */ +#include "jalv.h" +#include "backend.h" +#include "comm.h" +#include "control.h" +#include "dumper.h" +#include "features.h" +#include "frontend.h" #include "jalv_config.h" -#include "jalv_internal.h" -#include "lv2_evbuf.h" +#include "log.h" +#include "macros.h" +#include "mapper.h" +#include "nodes.h" +#include "options.h" +#include "port.h" +#include "process.h" +#include "process_setup.h" +#include "settings.h" +#include "state.h" +#include "string_utils.h" +#include "types.h" +#include "urids.h" #include "worker.h" -#include "lv2/atom/atom.h" -#include "lv2/buf-size/buf-size.h" -#include "lv2/data-access/data-access.h" -#include "lv2/options/options.h" -#include "lv2/parameters/parameters.h" -#include "lv2/patch/patch.h" -#include "lv2/port-groups/port-groups.h" -#include "lv2/port-props/port-props.h" -#include "lv2/presets/presets.h" -#include "lv2/state/state.h" -#include "lv2/time/time.h" -#include "lv2/ui/ui.h" -#include "lv2/urid/urid.h" -#include "lv2/worker/worker.h" - -#include "lilv/lilv.h" - -#ifdef HAVE_SUIL -#include "suil/suil.h" -#endif - -#ifdef _WIN32 -# include <io.h> /* for _mktemp */ -# define snprintf _snprintf -#else -# include <unistd.h> +#include <lilv/lilv.h> +#include <lv2/atom/atom.h> +#include <lv2/atom/forge.h> +#include <lv2/atom/util.h> +#include <lv2/buf-size/buf-size.h> +#include <lv2/core/lv2.h> +#include <lv2/data-access/data-access.h> +#include <lv2/instance-access/instance-access.h> +#include <lv2/log/log.h> +#include <lv2/patch/patch.h> +#include <lv2/state/state.h> +#include <lv2/ui/ui.h> +#include <lv2/urid/urid.h> +#include <lv2/worker/worker.h> +#include <zix/allocator.h> +#include <zix/filesystem.h> +#include <zix/path.h> +#include <zix/ring.h> +#include <zix/sem.h> +#include <zix/status.h> + +#if USE_SUIL +# include <suil/suil.h> #endif -#include <assert.h> -#include <math.h> -#include <signal.h> +#include <stdbool.h> +#include <stdint.h> #include <stdio.h> #include <stdlib.h> #include <string.h> -#include <sys/stat.h> -#include <sys/types.h> - -#define NS_RDF "http://www.w3.org/1999/02/22-rdf-syntax-ns#" -#define NS_XSD "http://www.w3.org/2001/XMLSchema#" - -#ifndef MIN -# define MIN(a, b) (((a) < (b)) ? (a) : (b)) -#endif -#ifndef MAX -# define MAX(a, b) (((a) > (b)) ? (a) : (b)) -#endif - -#ifndef ARRAY_SIZE -# define ARRAY_SIZE(arr) (sizeof(arr) / sizeof(arr[0])) -#endif +/** + Size factor for UI ring buffers. -/* Size factor for UI ring buffers. The ring size is a few times the size of - an event output to give the UI a chance to keep up. Experiments with Ingen, - which can highly saturate its event output, led me to this value. It - really ought to be enough for anybody(TM). + The ring size is a few times the size of an event output to give the UI a + chance to keep up. Experiments with Ingen, which can highly saturate its + event output, led me to this value. It really ought to be enough for + anybody(TM). */ #define N_BUFFER_CYCLES 16 -static ZixSem* exit_sem = NULL; /**< Exit semaphore used by signal handler*/ - -static LV2_URID -map_uri(LV2_URID_Map_Handle handle, - const char* uri) -{ - Jalv* jalv = (Jalv*)handle; - zix_sem_wait(&jalv->symap_lock); - const LV2_URID id = symap_map(jalv->symap, uri); - zix_sem_post(&jalv->symap_lock); - return id; -} - -static const char* -unmap_uri(LV2_URID_Unmap_Handle handle, - LV2_URID urid) -{ - Jalv* jalv = (Jalv*)handle; - zix_sem_wait(&jalv->symap_lock); - const char* uri = symap_unmap(jalv->symap, urid); - zix_sem_post(&jalv->symap_lock); - return uri; -} - -#define NS_EXT "http://lv2plug.in/ns/ext/" - -/** These features have no data */ +/// These features have no data static const LV2_Feature static_features[] = { - { LV2_STATE__loadDefaultState, NULL }, - { LV2_BUF_SIZE__powerOf2BlockLength, NULL }, - { LV2_BUF_SIZE__fixedBlockLength, NULL }, - { LV2_BUF_SIZE__boundedBlockLength, NULL } }; + {LV2_STATE__loadDefaultState, NULL}, + {LV2_BUF_SIZE__powerOf2BlockLength, NULL}, + {LV2_BUF_SIZE__fixedBlockLength, NULL}, + {LV2_BUF_SIZE__boundedBlockLength, NULL}}; -/** Return true iff Jalv supports the given feature. */ +/// Return true iff Jalv supports the given feature static bool -feature_is_supported(Jalv* jalv, const char* uri) +feature_is_supported(const Jalv* jalv, const char* uri) { - if (!strcmp(uri, "http://lv2plug.in/ns/lv2core#isLive")) { - return true; - } - - for (const LV2_Feature*const* f = jalv->feature_list; *f; ++f) { - if (!strcmp(uri, (*f)->URI)) { - return true; - } - } - return false; -} - -/** Abort and exit on error */ -static void -die(const char* msg) -{ - fprintf(stderr, "%s\n", msg); - exit(EXIT_FAILURE); + if (!strcmp(uri, "http://lv2plug.in/ns/lv2core#isLive") || + !strcmp(uri, "http://lv2plug.in/ns/lv2core#inPlaceBroken")) { + return true; + } + + for (const LV2_Feature* const* f = jalv->feature_list; *f; ++f) { + if (!strcmp(uri, (*f)->URI)) { + return true; + } + } + return false; } /** - Create a port structure from data description. This is called before plugin - and Jack instantiation. The remaining instance-specific setup - (e.g. buffers) is done later in activate_port(). -*/ -static void -create_port(Jalv* jalv, - uint32_t port_index, - float default_value) -{ - struct Port* const port = &jalv->ports[port_index]; - - port->lilv_port = lilv_plugin_get_port_by_index(jalv->plugin, port_index); - port->sys_port = NULL; - port->evbuf = NULL; - port->buf_size = 0; - port->index = port_index; - port->control = 0.0f; - port->flow = FLOW_UNKNOWN; - - const bool optional = lilv_port_has_property( - jalv->plugin, port->lilv_port, jalv->nodes.lv2_connectionOptional); - - /* Set the port flow (input or output) */ - if (lilv_port_is_a(jalv->plugin, port->lilv_port, jalv->nodes.lv2_InputPort)) { - port->flow = FLOW_INPUT; - } else if (lilv_port_is_a(jalv->plugin, port->lilv_port, - jalv->nodes.lv2_OutputPort)) { - port->flow = FLOW_OUTPUT; - } else if (!optional) { - die("Mandatory port has unknown type (neither input nor output)"); - } - - const bool hidden = !jalv->opts.show_hidden && - lilv_port_has_property(jalv->plugin, - port->lilv_port, - jalv->nodes.pprops_notOnGUI); - - /* Set control values */ - if (lilv_port_is_a(jalv->plugin, port->lilv_port, jalv->nodes.lv2_ControlPort)) { - port->type = TYPE_CONTROL; - port->control = isnan(default_value) ? 0.0f : default_value; - if (!hidden) { - add_control(&jalv->controls, new_port_control(jalv, port->index)); - } - } else if (lilv_port_is_a(jalv->plugin, port->lilv_port, - jalv->nodes.lv2_AudioPort)) { - port->type = TYPE_AUDIO; -#ifdef HAVE_JACK_METADATA - } else if (lilv_port_is_a(jalv->plugin, port->lilv_port, - jalv->nodes.lv2_CVPort)) { - port->type = TYPE_CV; -#endif - } else if (lilv_port_is_a(jalv->plugin, port->lilv_port, - jalv->nodes.atom_AtomPort)) { - port->type = TYPE_EVENT; - } else if (!optional) { - die("Mandatory port has unknown data type"); - } - - LilvNode* min_size = lilv_port_get( - jalv->plugin, port->lilv_port, jalv->nodes.rsz_minimumSize); - if (min_size && lilv_node_is_int(min_size)) { - port->buf_size = lilv_node_as_int(min_size); - jalv->opts.buffer_size = MAX( - jalv->opts.buffer_size, port->buf_size * N_BUFFER_CYCLES); - } - lilv_node_free(min_size); -} + Create a port structure from data description. -/** - Create port structures from data (via create_port()) for all ports. + This is called before plugin and Jack instantiation. The remaining + instance-specific setup (e.g. buffers) is done later in activate_port(). */ -void -jalv_create_ports(Jalv* jalv) +static int +create_port(Jalv* jalv, uint32_t port_index) { - jalv->num_ports = lilv_plugin_get_num_ports(jalv->plugin); - jalv->ports = (struct Port*)calloc(jalv->num_ports, sizeof(struct Port)); - float* default_values = (float*)calloc( - lilv_plugin_get_num_ports(jalv->plugin), sizeof(float)); - lilv_plugin_get_port_ranges_float(jalv->plugin, NULL, NULL, default_values); - - for (uint32_t i = 0; i < jalv->num_ports; ++i) { - create_port(jalv, i, default_values[i]); - } - - const LilvPort* control_input = lilv_plugin_get_port_by_designation( - jalv->plugin, jalv->nodes.lv2_InputPort, jalv->nodes.lv2_control); - if (control_input) { - jalv->control_in = lilv_port_get_index(jalv->plugin, control_input); - } - - free(default_values); + JalvPort* const port = &jalv->ports[port_index]; + + port->lilv_port = lilv_plugin_get_port_by_index(jalv->plugin, port_index); + port->index = port_index; + port->flow = FLOW_UNKNOWN; + + JalvProcessPort* const pport = &jalv->process.ports[port_index]; + if (jalv_process_port_init(&jalv->process.ports[port_index], + &jalv->nodes, + jalv->plugin, + port->lilv_port)) { + return 1; + } + + port->type = pport->type; + port->flow = pport->flow; + + if (lilv_port_is_a( + jalv->plugin, port->lilv_port, jalv->nodes.lv2_ControlPort)) { + const bool hidden = !jalv->opts.show_hidden && + lilv_port_has_property(jalv->plugin, + port->lilv_port, + jalv->nodes.pprops_notOnGUI); + + if (!hidden) { + add_control(&jalv->controls, + new_port_control(jalv->world, + jalv->plugin, + port->lilv_port, + port->index, + jalv->settings.sample_rate, + &jalv->nodes, + &jalv->forge)); + } + } + + // Store index if this is the designated control input port + if (jalv->process.control_in == UINT32_MAX && pport->is_primary && + port->flow == FLOW_INPUT && port->type == TYPE_EVENT) { + jalv->process.control_in = port_index; + } + + // Update maximum buffer sizes + const uint32_t buf_size = pport->buf_size; + jalv->opts.ring_size = MAX(jalv->opts.ring_size, buf_size * N_BUFFER_CYCLES); + if (port->flow == FLOW_OUTPUT) { + jalv->ui_msg_size = MAX(jalv->ui_msg_size, buf_size); + } + + return 0; } -/** - Allocate port buffers (only necessary for MIDI). -*/ -void -jalv_allocate_port_buffers(Jalv* jalv) +/// Create port structures from data (via create_port()) for all ports +static int +jalv_create_ports(Jalv* jalv) { - for (uint32_t i = 0; i < jalv->num_ports; ++i) { - struct Port* const port = &jalv->ports[i]; - switch (port->type) { - case TYPE_EVENT: { - lv2_evbuf_free(port->evbuf); - const size_t buf_size = (port->buf_size > 0) - ? port->buf_size - : jalv->midi_buf_size; - port->evbuf = lv2_evbuf_new( - buf_size, - jalv->map.map(jalv->map.handle, - lilv_node_as_string(jalv->nodes.atom_Chunk)), - jalv->map.map(jalv->map.handle, - lilv_node_as_string(jalv->nodes.atom_Sequence))); - lilv_instance_connect_port( - jalv->instance, i, lv2_evbuf_get_buffer(port->evbuf)); - } - default: break; - } - } + const uint32_t n_ports = lilv_plugin_get_num_ports(jalv->plugin); + + jalv->num_ports = n_ports; + jalv->ports = (JalvPort*)calloc(n_ports, sizeof(JalvPort)); + jalv->process.num_ports = n_ports; + jalv->process.ports = + (JalvProcessPort*)calloc(n_ports, sizeof(JalvProcessPort)); + + // Allocate control port buffers array and set to default values + jalv->process.controls_buf = (float*)calloc(n_ports, sizeof(float)); + lilv_plugin_get_port_ranges_float( + jalv->plugin, NULL, NULL, jalv->process.controls_buf); + + for (uint32_t i = 0; i < jalv->num_ports; ++i) { + if (create_port(jalv, i)) { + return 1; + } + } + + return 0; } /** @@ -267,999 +183,863 @@ jalv_allocate_port_buffers(Jalv* jalv) TODO: Build an index to make this faster, currently O(n) which may be a problem when restoring the state of plugins with many ports. */ -struct Port* +JalvPort* jalv_port_by_symbol(Jalv* jalv, const char* sym) { - for (uint32_t i = 0; i < jalv->num_ports; ++i) { - struct Port* const port = &jalv->ports[i]; - const LilvNode* port_sym = lilv_port_get_symbol(jalv->plugin, - port->lilv_port); + for (uint32_t i = 0; i < jalv->num_ports; ++i) { + JalvPort* const port = &jalv->ports[i]; + const LilvNode* port_sym = + lilv_port_get_symbol(jalv->plugin, port->lilv_port); - if (!strcmp(lilv_node_as_string(port_sym), sym)) { - return port; - } - } + if (!strcmp(lilv_node_as_string(port_sym), sym)) { + return port; + } + } - return NULL; + return NULL; } -ControlID* +static ControlID* jalv_control_by_symbol(Jalv* jalv, const char* sym) { - for (size_t i = 0; i < jalv->controls.n_controls; ++i) { - if (!strcmp(lilv_node_as_string(jalv->controls.controls[i]->symbol), - sym)) { - return jalv->controls.controls[i]; - } - } - return NULL; + for (size_t i = 0; i < jalv->controls.n_controls; ++i) { + if (!strcmp(lilv_node_as_string(jalv->controls.controls[i]->symbol), sym)) { + return jalv->controls.controls[i]; + } + } + return NULL; } -void +static void jalv_create_controls(Jalv* jalv, bool writable) { - const LilvPlugin* plugin = jalv->plugin; - LilvWorld* world = jalv->world; - LilvNode* patch_writable = lilv_new_uri(world, LV2_PATCH__writable); - LilvNode* patch_readable = lilv_new_uri(world, LV2_PATCH__readable); - - LilvNodes* properties = lilv_world_find_nodes( - world, - lilv_plugin_get_uri(plugin), - writable ? patch_writable : patch_readable, - NULL); - LILV_FOREACH(nodes, p, properties) { - const LilvNode* property = lilv_nodes_get(properties, p); - ControlID* record = NULL; - - if (!writable && lilv_world_ask(world, - lilv_plugin_get_uri(plugin), - patch_writable, - property)) { - // Find existing writable control - for (size_t i = 0; i < jalv->controls.n_controls; ++i) { - if (lilv_node_equals(jalv->controls.controls[i]->node, property)) { - record = jalv->controls.controls[i]; - record->is_readable = true; - break; - } - } - - if (record) { - continue; - } - } - - record = new_property_control(jalv, property); - if (writable) { - record->is_writable = true; - } else { - record->is_readable = true; - } - - if (record->value_type) { - add_control(&jalv->controls, record); - } else { - fprintf(stderr, "Parameter <%s> has unknown value type, ignored\n", - lilv_node_as_string(record->node)); - free(record); - } - } - lilv_nodes_free(properties); - - lilv_node_free(patch_readable); - lilv_node_free(patch_writable); + const LilvPlugin* plugin = jalv->plugin; + LilvWorld* world = jalv->world; + LilvNode* patch_writable = lilv_new_uri(world, LV2_PATCH__writable); + LilvNode* patch_readable = lilv_new_uri(world, LV2_PATCH__readable); + + LilvNodes* properties = + lilv_world_find_nodes(world, + lilv_plugin_get_uri(plugin), + writable ? patch_writable : patch_readable, + NULL); + LILV_FOREACH (nodes, p, properties) { + const LilvNode* property = lilv_nodes_get(properties, p); + ControlID* record = NULL; + + if (!writable && + lilv_world_ask( + world, lilv_plugin_get_uri(plugin), patch_writable, property)) { + // Find existing writable control + for (size_t i = 0; i < jalv->controls.n_controls; ++i) { + if (lilv_node_equals(jalv->controls.controls[i]->node, property)) { + record = jalv->controls.controls[i]; + record->is_readable = true; + break; + } + } + + if (record) { + continue; + } + } + + record = new_property_control(jalv->world, + property, + &jalv->nodes, + jalv_mapper_urid_map(jalv->mapper), + &jalv->forge); + + if (writable) { + record->is_writable = true; + } else { + record->is_readable = true; + } + + if (record->value_type) { + add_control(&jalv->controls, record); + } else { + jalv_log(JALV_LOG_WARNING, + "Parameter <%s> has unknown value type, ignored\n", + lilv_node_as_string(record->node)); + free(record); + } + } + lilv_nodes_free(properties); + + lilv_node_free(patch_readable); + lilv_node_free(patch_writable); } -void -jalv_set_control(const ControlID* control, - uint32_t size, - LV2_URID type, - const void* body) +static void +jalv_send_to_plugin(void* const jalv_handle, + const uint32_t port_index, + const uint32_t buffer_size, + const uint32_t protocol, + const void* const buffer) { - Jalv* jalv = control->jalv; - if (control->type == PORT && type == jalv->forge.Float) { - struct Port* port = &control->jalv->ports[control->index]; - port->control = *(const float*)body; - } else if (control->type == PROPERTY) { - // Copy forge since it is used by process thread - LV2_Atom_Forge forge = jalv->forge; - LV2_Atom_Forge_Frame frame; - uint8_t buf[1024]; - lv2_atom_forge_set_buffer(&forge, buf, sizeof(buf)); - - lv2_atom_forge_object(&forge, &frame, 0, jalv->urids.patch_Set); - lv2_atom_forge_key(&forge, jalv->urids.patch_property); - lv2_atom_forge_urid(&forge, control->property); - lv2_atom_forge_key(&forge, jalv->urids.patch_value); - lv2_atom_forge_atom(&forge, size, type); - lv2_atom_forge_write(&forge, body, size); - - const LV2_Atom* atom = lv2_atom_forge_deref(&forge, frame.ref); - jalv_ui_write(jalv, - jalv->control_in, - lv2_atom_total_size(atom), - jalv->urids.atom_eventTransfer, - atom); - } + Jalv* const jalv = (Jalv*)jalv_handle; + JalvProcess* const proc = &jalv->process; + ZixStatus st = ZIX_STATUS_SUCCESS; + + if (port_index >= jalv->num_ports) { + jalv_log(JALV_LOG_ERR, "UI wrote to invalid port index %u\n", port_index); + + } else if (protocol == 0U) { + if (buffer_size != sizeof(float)) { + st = ZIX_STATUS_BAD_ARG; + } else { + const float value = *(const float*)buffer; + st = jalv_write_control(proc->ui_to_plugin, port_index, value); + } + + } else if (protocol == jalv->urids.atom_eventTransfer) { + const LV2_Atom* const atom = (const LV2_Atom*)buffer; + if (buffer_size < sizeof(LV2_Atom) || + (sizeof(LV2_Atom) + atom->size != buffer_size)) { + st = ZIX_STATUS_BAD_ARG; + } else { + jalv_dump_atom(jalv->dumper, stdout, "UI => Plugin", atom, 36); + st = jalv_write_event( + proc->ui_to_plugin, port_index, atom->size, atom->type, atom + 1U); + } + + } else { + jalv_log(JALV_LOG_ERR, + "UI wrote with unsupported protocol %u (%s)\n", + protocol, + jalv_mapper_unmap_uri(jalv->mapper, protocol)); + } + + if (st) { + jalv_log(JALV_LOG_ERR, + "Failed to write to plugin from UI (%s)\n", + zix_strerror(st)); + } } void -jalv_ui_instantiate(Jalv* jalv, const char* native_ui_type, void* parent) +jalv_set_control(Jalv* jalv, + const ControlID* control, + uint32_t size, + LV2_URID type, + const void* body) { -#ifdef HAVE_SUIL - jalv->ui_host = suil_host_new(jalv_ui_write, jalv_ui_port_index, NULL, NULL); - - const LV2_Feature parent_feature = { - LV2_UI__parent, parent - }; - const LV2_Feature instance_feature = { - NS_EXT "instance-access", lilv_instance_get_handle(jalv->instance) - }; - const LV2_Feature data_feature = { - LV2_DATA_ACCESS_URI, &jalv->features.ext_data - }; - const LV2_Feature idle_feature = { - LV2_UI__idleInterface, NULL - }; - const LV2_Feature* ui_features[] = { - &jalv->features.map_feature, - &jalv->features.unmap_feature, - &instance_feature, - &data_feature, - &jalv->features.log_feature, - &parent_feature, - &jalv->features.options_feature, - &idle_feature, - NULL - }; - - const char* bundle_uri = lilv_node_as_uri(lilv_ui_get_bundle_uri(jalv->ui)); - const char* binary_uri = lilv_node_as_uri(lilv_ui_get_binary_uri(jalv->ui)); - char* bundle_path = lilv_file_uri_parse(bundle_uri, NULL); - char* binary_path = lilv_file_uri_parse(binary_uri, NULL); - - jalv->ui_instance = suil_instance_new( - jalv->ui_host, - jalv, - native_ui_type, - lilv_node_as_uri(lilv_plugin_get_uri(jalv->plugin)), - lilv_node_as_uri(lilv_ui_get_uri(jalv->ui)), - lilv_node_as_uri(jalv->ui_type), - bundle_path, - binary_path, - ui_features); - - lilv_free(binary_path); - lilv_free(bundle_path); -#endif + if (control->type == PORT && type == jalv->forge.Float) { + const float value = *(const float*)body; + jalv_write_control(jalv->process.ui_to_plugin, control->id.index, value); + } else if (control->type == PROPERTY && + jalv->process.control_in != UINT32_MAX) { + LV2_Atom_Forge_Frame frame; + lv2_atom_forge_set_buffer(&jalv->forge, jalv->ui_msg, jalv->ui_msg_size); + + lv2_atom_forge_object(&jalv->forge, &frame, 0, jalv->urids.patch_Set); + lv2_atom_forge_key(&jalv->forge, jalv->urids.patch_property); + lv2_atom_forge_urid(&jalv->forge, control->id.property); + lv2_atom_forge_key(&jalv->forge, jalv->urids.patch_value); + lv2_atom_forge_atom(&jalv->forge, size, type); + lv2_atom_forge_write(&jalv->forge, body, size); + + const LV2_Atom* atom = lv2_atom_forge_deref(&jalv->forge, frame.ref); + jalv_send_to_plugin(jalv, + jalv->process.control_in, + lv2_atom_total_size(atom), + jalv->urids.atom_eventTransfer, + atom); + } } -bool -jalv_ui_is_resizable(Jalv* jalv) +#if USE_SUIL +static uint32_t +jalv_ui_port_index(void* const controller, const char* symbol) { - if (!jalv->ui) { - return false; - } - - const LilvNode* s = lilv_ui_get_uri(jalv->ui); - LilvNode* p = lilv_new_uri(jalv->world, LV2_CORE__optionalFeature); - LilvNode* fs = lilv_new_uri(jalv->world, LV2_UI__fixedSize); - LilvNode* nrs = lilv_new_uri(jalv->world, LV2_UI__noUserResize); - - LilvNodes* fs_matches = lilv_world_find_nodes(jalv->world, s, p, fs); - LilvNodes* nrs_matches = lilv_world_find_nodes(jalv->world, s, p, nrs); + Jalv* const jalv = (Jalv*)controller; + JalvPort* const port = jalv_port_by_symbol(jalv, symbol); - lilv_nodes_free(nrs_matches); - lilv_nodes_free(fs_matches); - lilv_node_free(nrs); - lilv_node_free(fs); - lilv_node_free(p); - - return !fs_matches && !nrs_matches; + return port ? port->index : LV2UI_INVALID_PORT_INDEX; } +#endif void -jalv_ui_write(void* const jalv_handle, - uint32_t port_index, - uint32_t buffer_size, - uint32_t protocol, - const void* buffer) +jalv_ui_instantiate(Jalv* jalv, const char* native_ui_type, void* parent) { - Jalv* const jalv = (Jalv*)jalv_handle; - - if (protocol != 0 && protocol != jalv->urids.atom_eventTransfer) { - fprintf(stderr, "UI write with unsupported protocol %d (%s)\n", - protocol, unmap_uri(jalv, protocol)); - return; - } - - if (port_index >= jalv->num_ports) { - fprintf(stderr, "UI write to out of range port index %d\n", - port_index); - return; - } - - if (jalv->opts.dump && protocol == jalv->urids.atom_eventTransfer) { - const LV2_Atom* atom = (const LV2_Atom*)buffer; - char* str = sratom_to_turtle( - jalv->sratom, &jalv->unmap, "jalv:", NULL, NULL, - atom->type, atom->size, LV2_ATOM_BODY_CONST(atom)); - jalv_ansi_start(stdout, 36); - printf("\n## UI => Plugin (%u bytes) ##\n%s\n", atom->size, str); - jalv_ansi_reset(stdout); - free(str); - } - - char buf[sizeof(ControlChange) + buffer_size]; - ControlChange* ev = (ControlChange*)buf; - ev->index = port_index; - ev->protocol = protocol; - ev->size = buffer_size; - memcpy(ev->body, buffer, buffer_size); - zix_ring_write(jalv->ui_events, buf, sizeof(buf)); +#if USE_SUIL + const LilvInstance* const instance = jalv->process.instance; + + jalv->ui_host = + suil_host_new(jalv_send_to_plugin, jalv_ui_port_index, NULL, NULL); + + const LV2_Feature parent_feature = {LV2_UI__parent, parent}; + + const LV2_Feature instance_feature = {LV2_INSTANCE_ACCESS_URI, + lilv_instance_get_handle(instance)}; + + const LV2_Feature data_feature = {LV2_DATA_ACCESS_URI, + &jalv->features.ext_data}; + + const LV2_Feature idle_feature = {LV2_UI__idleInterface, NULL}; + + const LV2_Feature* ui_features[] = {&jalv->features.map_feature, + &jalv->features.unmap_feature, + &instance_feature, + &data_feature, + &jalv->features.log_feature, + &parent_feature, + &jalv->features.options_feature, + &idle_feature, + &jalv->features.request_value_feature, + NULL}; + + const char* bundle_uri = lilv_node_as_uri(lilv_ui_get_bundle_uri(jalv->ui)); + const char* binary_uri = lilv_node_as_uri(lilv_ui_get_binary_uri(jalv->ui)); + char* bundle_path = lilv_file_uri_parse(bundle_uri, NULL); + char* binary_path = lilv_file_uri_parse(binary_uri, NULL); + + jalv->ui_instance = + suil_instance_new(jalv->ui_host, + jalv, + native_ui_type, + lilv_node_as_uri(lilv_plugin_get_uri(jalv->plugin)), + lilv_node_as_uri(lilv_ui_get_uri(jalv->ui)), + lilv_node_as_uri(jalv->ui_type), + bundle_path, + binary_path, + ui_features); + + lilv_free(binary_path); + lilv_free(bundle_path); +#else + (void)jalv; + (void)native_ui_type; + (void)parent; +#endif } void -jalv_apply_ui_events(Jalv* jalv, uint32_t nframes) +jalv_init_ui(Jalv* jalv) { - if (!jalv->has_ui) { - return; - } - - ControlChange ev; - const size_t space = zix_ring_read_space(jalv->ui_events); - for (size_t i = 0; i < space; i += sizeof(ev) + ev.size) { - zix_ring_read(jalv->ui_events, (char*)&ev, sizeof(ev)); - char body[ev.size]; - if (zix_ring_read(jalv->ui_events, body, ev.size) != ev.size) { - fprintf(stderr, "error: Error reading from UI ring buffer\n"); - break; - } - assert(ev.index < jalv->num_ports); - struct Port* const port = &jalv->ports[ev.index]; - if (ev.protocol == 0) { - assert(ev.size == sizeof(float)); - port->control = *(float*)body; - } else if (ev.protocol == jalv->urids.atom_eventTransfer) { - LV2_Evbuf_Iterator e = lv2_evbuf_end(port->evbuf); - const LV2_Atom* const atom = (const LV2_Atom*)body; - lv2_evbuf_write(&e, nframes, 0, atom->type, atom->size, - (const uint8_t*)LV2_ATOM_BODY_CONST(atom)); - } else { - fprintf(stderr, "error: Unknown control change protocol %d\n", - ev.protocol); - } - } + // Set initial control port values + for (uint32_t i = 0; i < jalv->num_ports; ++i) { + if (jalv->ports[i].type == TYPE_CONTROL) { + jalv_frontend_port_event( + jalv, i, sizeof(float), 0, &jalv->process.controls_buf[i]); + } + } + + if (jalv->process.control_in != UINT32_MAX) { + // Send patch:Get message for initial parameters/etc + LV2_Atom_Forge_Frame frame; + uint64_t buf[4U] = {0U, 0U, 0U, 0U}; + lv2_atom_forge_set_buffer(&jalv->forge, (uint8_t*)buf, sizeof(buf)); + lv2_atom_forge_object(&jalv->forge, &frame, 0, jalv->urids.patch_Get); + + const LV2_Atom* atom = lv2_atom_forge_deref(&jalv->forge, frame.ref); + jalv_send_to_plugin(jalv, + jalv->process.control_in, + lv2_atom_total_size(atom), + jalv->urids.atom_eventTransfer, + atom); + lv2_atom_forge_pop(&jalv->forge, &frame); + } } -uint32_t -jalv_ui_port_index(void* const controller, const char* symbol) +static int +ring_error(const char* const message) { - Jalv* const jalv = (Jalv*)controller; - struct Port* port = jalv_port_by_symbol(jalv, symbol); - - return port ? port->index : LV2UI_INVALID_PORT_INDEX; + jalv_log(JALV_LOG_ERR, "%s", message); + return 1; } -void -jalv_init_ui(Jalv* jalv) +int +jalv_update(Jalv* jalv) { - // Set initial control port values - for (uint32_t i = 0; i < jalv->num_ports; ++i) { - if (jalv->ports[i].type == TYPE_CONTROL) { - jalv_ui_port_event(jalv, i, - sizeof(float), 0, - &jalv->ports[i].control); - } - } - - if (jalv->control_in != (uint32_t)-1) { - // Send patch:Get message for initial parameters/etc - LV2_Atom_Forge forge = jalv->forge; - LV2_Atom_Forge_Frame frame; - uint8_t buf[1024]; - lv2_atom_forge_set_buffer(&forge, buf, sizeof(buf)); - lv2_atom_forge_object(&forge, &frame, 0, jalv->urids.patch_Get); - - const LV2_Atom* atom = lv2_atom_forge_deref(&forge, frame.ref); - jalv_ui_write(jalv, - jalv->control_in, - lv2_atom_total_size(atom), - jalv->urids.atom_eventTransfer, - atom); - lv2_atom_forge_pop(&forge, &frame); - } + // Check quit flag and close if set + if (!zix_sem_try_wait(&jalv->done)) { + jalv_frontend_close(jalv); + return 0; + } + + // Emit UI events + ZixRing* const ring = jalv->process.plugin_to_ui; + JalvMessageHeader header = {NO_MESSAGE, 0U}; + const size_t space = zix_ring_read_space(ring); + for (size_t i = 0; i < space; i += sizeof(header) + header.size) { + // Read message header (which includes the body size) + if (zix_ring_read(ring, &header, sizeof(header)) != sizeof(header)) { + return ring_error("Failed to read header from process ring\n"); + } + + // Read message body + void* const body = jalv->ui_msg; + if (zix_ring_read(ring, body, header.size) != header.size) { + return ring_error("Failed to read message from process ring\n"); + } + + if (header.type == CONTROL_PORT_CHANGE) { + const JalvControlChange* const msg = (const JalvControlChange*)body; + jalv_frontend_port_event(jalv, msg->port_index, sizeof(float), 0, body); + } else if (header.type == EVENT_TRANSFER) { + const JalvEventTransfer* const msg = (const JalvEventTransfer*)body; + jalv_dump_atom(jalv->dumper, stdout, "Plugin => UI", &msg->atom, 35); + jalv_frontend_port_event(jalv, + msg->port_index, + sizeof(LV2_Atom) + msg->atom.size, + jalv->urids.atom_eventTransfer, + &msg->atom); + } else if (header.type == LATENCY_CHANGE) { + jalv_backend_recompute_latencies(jalv->backend); + } else { + return ring_error("Unknown message type received from process ring\n"); + } + } + + return 1; } -bool -jalv_send_to_ui(Jalv* jalv, - uint32_t port_index, - uint32_t type, - uint32_t size, - const void* body) +static bool +jalv_apply_control_arg(Jalv* jalv, const char* s) { - /* TODO: Be more disciminate about what to send */ - char evbuf[sizeof(ControlChange) + sizeof(LV2_Atom)]; - ControlChange* ev = (ControlChange*)evbuf; - ev->index = port_index; - ev->protocol = jalv->urids.atom_eventTransfer; - ev->size = sizeof(LV2_Atom) + size; - - LV2_Atom* atom = (LV2_Atom*)ev->body; - atom->type = type; - atom->size = size; - - if (zix_ring_write_space(jalv->plugin_events) >= sizeof(evbuf) + size) { - zix_ring_write(jalv->plugin_events, evbuf, sizeof(evbuf)); - zix_ring_write(jalv->plugin_events, (const char*)body, size); - return true; - } else { - fprintf(stderr, "Plugin => UI buffer overflow!\n"); - return false; - } + char sym[256] = {'\0'}; + float val = 0.0f; + if (sscanf(s, "%240[^=]=%f", sym, &val) != 2) { + jalv_log(JALV_LOG_WARNING, "Ignoring invalid value `%s'\n", s); + return false; + } + + const ControlID* control = jalv_control_by_symbol(jalv, sym); + if (!control) { + jalv_log( + JALV_LOG_WARNING, "Ignoring value for unknown control `%s'\n", sym); + return false; + } + + jalv_set_control(jalv, control, sizeof(float), jalv->urids.atom_Float, &val); + jalv_log(JALV_LOG_INFO, "%s = %f\n", sym, val); + + return true; } -bool -jalv_run(Jalv* jalv, uint32_t nframes) +static void +init_feature(LV2_Feature* const dest, const char* const URI, void* data) { - /* Read and apply control change events from UI */ - jalv_apply_ui_events(jalv, nframes); - - /* Run plugin for this cycle */ - lilv_instance_run(jalv->instance, nframes); - - /* Process any worker replies. */ - jalv_worker_emit_responses(&jalv->state_worker, jalv->instance); - jalv_worker_emit_responses(&jalv->worker, jalv->instance); - - /* Notify the plugin the run() cycle is finished */ - if (jalv->worker.iface && jalv->worker.iface->end_run) { - jalv->worker.iface->end_run(jalv->instance->lv2_handle); - } - - /* Check if it's time to send updates to the UI */ - jalv->event_delta_t += nframes; - bool send_ui_updates = false; - float update_frames = jalv->sample_rate / jalv->ui_update_hz; - if (jalv->has_ui && (jalv->event_delta_t > update_frames)) { - send_ui_updates = true; - jalv->event_delta_t = 0; - } - - return send_ui_updates; + dest->URI = URI; + dest->data = data; } -int -jalv_update(Jalv* jalv) +static const LilvUI* +jalv_select_custom_ui(const Jalv* const jalv) { - /* Check quit flag and close if set. */ - if (zix_sem_try_wait(&jalv->done)) { - jalv_close_ui(jalv); - return 0; - } - - /* Emit UI events. */ - ControlChange ev; - const size_t space = zix_ring_read_space(jalv->plugin_events); - for (size_t i = 0; - i + sizeof(ev) < space; - i += sizeof(ev) + ev.size) { - /* Read event header to get the size */ - zix_ring_read(jalv->plugin_events, (char*)&ev, sizeof(ev)); - - /* Resize read buffer if necessary */ - jalv->ui_event_buf = realloc(jalv->ui_event_buf, ev.size); - void* const buf = jalv->ui_event_buf; - - /* Read event body */ - zix_ring_read(jalv->plugin_events, (char*)buf, ev.size); - - if (jalv->opts.dump && ev.protocol == jalv->urids.atom_eventTransfer) { - /* Dump event in Turtle to the console */ - LV2_Atom* atom = (LV2_Atom*)buf; - char* str = sratom_to_turtle( - jalv->ui_sratom, &jalv->unmap, "jalv:", NULL, NULL, - atom->type, atom->size, LV2_ATOM_BODY(atom)); - jalv_ansi_start(stdout, 35); - printf("\n## Plugin => UI (%u bytes) ##\n%s\n", atom->size, str); - jalv_ansi_reset(stdout); - free(str); - } - - jalv_ui_port_event(jalv, ev.index, ev.size, ev.protocol, buf); - - if (ev.protocol == 0 && jalv->opts.print_controls) { - jalv_print_control(jalv, &jalv->ports[ev.index], *(float*)buf); - } - } - - return 1; -} + const char* const native_ui_type_uri = jalv_frontend_ui_type(); + + if (jalv->opts.ui_uri) { + // Specific UI explicitly requested by user + LilvNode* uri = lilv_new_uri(jalv->world, jalv->opts.ui_uri); + const LilvUI* ui = lilv_uis_get_by_uri(jalv->uis, uri); + + lilv_node_free(uri); + return ui; + } + +#if USE_SUIL + if (native_ui_type_uri) { + // Try to find an embeddable UI + LilvNode* native_type = lilv_new_uri(jalv->world, native_ui_type_uri); + + LILV_FOREACH (uis, u, jalv->uis) { + const LilvUI* ui = lilv_uis_get(jalv->uis, u); + const LilvNode* type = NULL; + const bool supported = + lilv_ui_is_supported(ui, suil_ui_supported, native_type, &type); + + if (supported) { + lilv_node_free(native_type); + return ui; + } + } + + lilv_node_free(native_type); + } +#endif -static bool -jalv_apply_control_arg(Jalv* jalv, const char* s) -{ - char sym[256]; - float val = 0.0f; - if (sscanf(s, "%[^=]=%f", sym, &val) != 2) { - fprintf(stderr, "warning: Ignoring invalid value `%s'\n", s); - return false; - } - - ControlID* control = jalv_control_by_symbol(jalv, sym); - if (!control) { - fprintf(stderr, "warning: Ignoring value for unknown control `%s'\n", sym); - return false; - } - - jalv_set_control(control, sizeof(float), jalv->urids.atom_Float, &val); - printf("%s = %f\n", sym, val); - - return true; + if (!native_ui_type_uri && jalv->opts.show_ui) { + // Try to find a UI with ui:showInterface + LILV_FOREACH (uis, u, jalv->uis) { + const LilvUI* ui = lilv_uis_get(jalv->uis, u); + const LilvNode* ui_node = lilv_ui_get_uri(ui); + + lilv_world_load_resource(jalv->world, ui_node); + + const bool supported = lilv_world_ask(jalv->world, + ui_node, + jalv->nodes.lv2_extensionData, + jalv->nodes.ui_showInterface); + + lilv_world_unload_resource(jalv->world, ui_node); + + if (supported) { + return ui; + } + } + } + + return NULL; } static void -signal_handler(ZIX_UNUSED int sig) +jalv_init_features(Jalv* const jalv) { - zix_sem_post(exit_sem); + // urid:map + init_feature(&jalv->features.map_feature, + LV2_URID__map, + jalv_mapper_urid_map(jalv->mapper)); + + // urid:unmap + init_feature(&jalv->features.unmap_feature, + LV2_URID__unmap, + jalv_mapper_urid_unmap(jalv->mapper)); + + // state:makePath + jalv->features.make_path.handle = jalv; + jalv->features.make_path.path = jalv_make_path; + init_feature(&jalv->features.make_path_feature, + LV2_STATE__makePath, + &jalv->features.make_path); + + // worker:schedule (normal) + jalv->features.sched.schedule_work = jalv_worker_schedule; + init_feature( + &jalv->features.sched_feature, LV2_WORKER__schedule, &jalv->features.sched); + + // worker:schedule (state) + jalv->features.ssched.schedule_work = jalv_worker_schedule; + init_feature(&jalv->features.state_sched_feature, + LV2_WORKER__schedule, + &jalv->features.ssched); + + // log:log + jalv->features.llog.handle = &jalv->log; + jalv->features.llog.printf = jalv_printf; + jalv->features.llog.vprintf = jalv_vprintf; + init_feature(&jalv->features.log_feature, LV2_LOG__log, &jalv->features.llog); + + // (options:options is initialized later by jalv_init_options()) + + // state:threadSafeRestore + init_feature( + &jalv->features.safe_restore_feature, LV2_STATE__threadSafeRestore, NULL); + + // ui:requestValue + jalv->features.request_value.handle = jalv; + init_feature(&jalv->features.request_value_feature, + LV2_UI__requestValue, + &jalv->features.request_value); } static void -init_feature(LV2_Feature* const dest, const char* const URI, void* data) +jalv_init_ui_settings(Jalv* const jalv) { - dest->URI = URI; - dest->data = data; + const JalvOptions* const opts = &jalv->opts; + JalvSettings* const settings = &jalv->settings; + + if (!settings->ring_size) { + /* The UI ring is fed by plugin output ports (usually one), and the UI + updates roughly once per cycle. The ring size is a few times the size + of the MIDI output to give the UI a chance to keep up. */ + settings->ring_size = settings->midi_buf_size * N_BUFFER_CYCLES; + } + + if (opts->update_rate <= 0.0f) { + // Calculate a reasonable UI update frequency + settings->ui_update_hz = jalv_frontend_refresh_rate(jalv); + } + + if (opts->scale_factor <= 0.0f) { + // Calculate the monitor's scale factor + settings->ui_scale_factor = jalv_frontend_scale_factor(jalv); + } + + // The UI can only go so fast, clamp to reasonable limits + settings->ui_update_hz = MAX(1.0f, MIN(60.0f, settings->ui_update_hz)); + settings->ring_size = MAX(4096, settings->ring_size); + jalv_log(JALV_LOG_INFO, "Comm buffers: %u bytes\n", settings->ring_size); + jalv_log(JALV_LOG_INFO, "Update rate: %.01f Hz\n", settings->ui_update_hz); + jalv_log(JALV_LOG_INFO, "Scale factor: %.01f\n", settings->ui_scale_factor); } -static void -setup_signals(Jalv* const jalv) +static LilvState* +initial_state(LilvWorld* const world, + LV2_URID_Map* const urid_map, + const char* const state_path) { - exit_sem = &jalv->done; - -#ifdef HAVE_SIGACTION - struct sigaction action; - sigemptyset(&action.sa_mask); - action.sa_flags = 0; - action.sa_handler = signal_handler; - sigaction(SIGINT, &action, NULL); - sigaction(SIGTERM, &action, NULL); -#else - /* May not work in combination with fgets in the console interface */ - signal(SIGINT, signal_handler); - signal(SIGTERM, signal_handler); -#endif + LilvState* state = NULL; + if (state_path) { + if (zix_file_type(state_path) == ZIX_FILE_TYPE_DIRECTORY) { + char* const path = zix_path_join(NULL, state_path, "state.ttl"); + state = lilv_state_new_from_file(world, urid_map, NULL, path); + free(path); + } else { + state = lilv_state_new_from_file(world, urid_map, NULL, state_path); + } + } + return state; } int jalv_open(Jalv* const jalv, int* argc, char*** argv) { - jalv->prog_name = (*argv)[0]; - jalv->block_length = 4096; /* Should be set by backend */ - jalv->midi_buf_size = 1024; /* Should be set by backend */ - jalv->play_state = JALV_PAUSED; - jalv->bpm = 120.0f; - jalv->control_in = (uint32_t)-1; - -#ifdef HAVE_SUIL - suil_init(argc, argv, SUIL_ARG_NONE); +#if USE_SUIL + suil_init(argc, argv, SUIL_ARG_NONE); #endif - if (jalv_init(argc, argv, &jalv->opts)) { - jalv_close(jalv); - return -1; - } - - if (jalv->opts.uuid) { - printf("UUID: %s\n", jalv->opts.uuid); - } - - jalv->symap = symap_new(); - zix_sem_init(&jalv->symap_lock, 1); - zix_sem_init(&jalv->work_lock, 1); - - jalv->map.handle = jalv; - jalv->map.map = map_uri; - init_feature(&jalv->features.map_feature, LV2_URID__map, &jalv->map); - - jalv->worker.jalv = jalv; - jalv->state_worker.jalv = jalv; - - jalv->unmap.handle = jalv; - jalv->unmap.unmap = unmap_uri; - init_feature(&jalv->features.unmap_feature, LV2_URID__unmap, &jalv->unmap); - - lv2_atom_forge_init(&jalv->forge, &jalv->map); - - jalv->env = serd_env_new(NULL); - serd_env_set_prefix_from_strings( - jalv->env, (const uint8_t*)"patch", (const uint8_t*)LV2_PATCH_PREFIX); - serd_env_set_prefix_from_strings( - jalv->env, (const uint8_t*)"time", (const uint8_t*)LV2_TIME_PREFIX); - serd_env_set_prefix_from_strings( - jalv->env, (const uint8_t*)"xsd", (const uint8_t*)NS_XSD); - - jalv->sratom = sratom_new(&jalv->map); - jalv->ui_sratom = sratom_new(&jalv->map); - sratom_set_env(jalv->sratom, jalv->env); - sratom_set_env(jalv->ui_sratom, jalv->env); - - jalv->urids.atom_Float = symap_map(jalv->symap, LV2_ATOM__Float); - jalv->urids.atom_Int = symap_map(jalv->symap, LV2_ATOM__Int); - jalv->urids.atom_Object = symap_map(jalv->symap, LV2_ATOM__Object); - jalv->urids.atom_Path = symap_map(jalv->symap, LV2_ATOM__Path); - jalv->urids.atom_String = symap_map(jalv->symap, LV2_ATOM__String); - jalv->urids.atom_eventTransfer = symap_map(jalv->symap, LV2_ATOM__eventTransfer); - jalv->urids.bufsz_maxBlockLength = symap_map(jalv->symap, LV2_BUF_SIZE__maxBlockLength); - jalv->urids.bufsz_minBlockLength = symap_map(jalv->symap, LV2_BUF_SIZE__minBlockLength); - jalv->urids.bufsz_sequenceSize = symap_map(jalv->symap, LV2_BUF_SIZE__sequenceSize); - jalv->urids.log_Error = symap_map(jalv->symap, LV2_LOG__Error); - jalv->urids.log_Trace = symap_map(jalv->symap, LV2_LOG__Trace); - jalv->urids.log_Warning = symap_map(jalv->symap, LV2_LOG__Warning); - jalv->urids.midi_MidiEvent = symap_map(jalv->symap, LV2_MIDI__MidiEvent); - jalv->urids.param_sampleRate = symap_map(jalv->symap, LV2_PARAMETERS__sampleRate); - jalv->urids.patch_Get = symap_map(jalv->symap, LV2_PATCH__Get); - jalv->urids.patch_Put = symap_map(jalv->symap, LV2_PATCH__Put); - jalv->urids.patch_Set = symap_map(jalv->symap, LV2_PATCH__Set); - jalv->urids.patch_body = symap_map(jalv->symap, LV2_PATCH__body); - jalv->urids.patch_property = symap_map(jalv->symap, LV2_PATCH__property); - jalv->urids.patch_value = symap_map(jalv->symap, LV2_PATCH__value); - jalv->urids.time_Position = symap_map(jalv->symap, LV2_TIME__Position); - jalv->urids.time_bar = symap_map(jalv->symap, LV2_TIME__bar); - jalv->urids.time_barBeat = symap_map(jalv->symap, LV2_TIME__barBeat); - jalv->urids.time_beatUnit = symap_map(jalv->symap, LV2_TIME__beatUnit); - jalv->urids.time_beatsPerBar = symap_map(jalv->symap, LV2_TIME__beatsPerBar); - jalv->urids.time_beatsPerMinute = symap_map(jalv->symap, LV2_TIME__beatsPerMinute); - jalv->urids.time_frame = symap_map(jalv->symap, LV2_TIME__frame); - jalv->urids.time_speed = symap_map(jalv->symap, LV2_TIME__speed); - jalv->urids.ui_updateRate = symap_map(jalv->symap, LV2_UI__updateRate); - -#ifdef _WIN32 - jalv->temp_dir = jalv_strdup("jalvXXXXXX"); - _mktemp(jalv->temp_dir); -#else - char* templ = jalv_strdup("/tmp/jalv-XXXXXX"); - jalv->temp_dir = jalv_strjoin(mkdtemp(templ), "/"); - free(templ); + // Parse command-line arguments + JalvFrontendArgs args = {argc, argv}; + const int ret = jalv_frontend_init(&args, &jalv->opts); + if (ret) { + return ret; + } + + JalvSettings* const settings = &jalv->settings; + + settings->block_length = 4096U; + settings->midi_buf_size = 1024U; + settings->ring_size = jalv->opts.ring_size; + settings->ui_update_hz = jalv->opts.update_rate; + settings->ui_scale_factor = jalv->opts.scale_factor; + + // Load the LV2 world + LilvWorld* const world = lilv_world_new(); + lilv_world_load_all(world); + + jalv->world = world; + jalv->mapper = jalv_mapper_new(); + jalv->log.urids = &jalv->urids; + jalv->log.tracing = jalv->opts.trace; + + // Set up atom dumping for debugging if enabled + LV2_URID_Map* const urid_map = jalv_mapper_urid_map(jalv->mapper); + LV2_URID_Unmap* const urid_unmap = jalv_mapper_urid_unmap(jalv->mapper); + if (jalv->opts.dump) { + jalv->dumper = jalv_dumper_new(urid_map, urid_unmap); + } + + zix_sem_init(&jalv->work_lock, 1); + zix_sem_init(&jalv->done, 0); + jalv_init_urids(jalv->mapper, &jalv->urids); + jalv_init_nodes(world, &jalv->nodes); + jalv_init_features(jalv); + lv2_atom_forge_init(&jalv->forge, urid_map); + + // Create temporary directory for plugin state + jalv->temp_dir = zix_create_temporary_directory(NULL, "jalvXXXXXX"); + if (!jalv->temp_dir) { + jalv_log(JALV_LOG_WARNING, "Failed to create temporary state directory\n"); + } + + // Load initial state given in options if any + LilvState* state = initial_state(world, urid_map, jalv->opts.load); + if (jalv->opts.load && !state) { + jalv_log(JALV_LOG_ERR, "Failed to load state from %s\n", jalv->opts.load); + return -2; + } + + // Get plugin URI from loaded state or command line + LilvNode* plugin_uri = NULL; + if (state) { + plugin_uri = lilv_node_duplicate(lilv_state_get_plugin_uri(state)); + } else if (*args.argc == 0) { + if (!(plugin_uri = jalv_frontend_select_plugin(jalv))) { + jalv_log(JALV_LOG_ERR, "Missing plugin URI, try lv2ls to list plugins\n"); + return -3; + } + } else if (*args.argc == 1) { + plugin_uri = lilv_new_uri(world, (*args.argv)[0]); + } else { + jalv_log(JALV_LOG_ERR, "Unexpected trailing arguments\n"); + return -1; + } + + // Find plugin + const char* const plugin_uri_str = lilv_node_as_string(plugin_uri); + const LilvPlugins* const plugins = lilv_world_get_all_plugins(world); + jalv_log(JALV_LOG_INFO, "Plugin: %s\n", plugin_uri_str); + jalv->plugin = lilv_plugins_get_by_uri(plugins, plugin_uri); + lilv_node_free(plugin_uri); + if (!jalv->plugin) { + jalv_log(JALV_LOG_ERR, "Failed to find plugin\n"); + return -4; + } + + if (!jalv->opts.name) { + jalv->opts.name = + jalv_strdup(lilv_node_as_string(lilv_plugin_get_name(jalv->plugin))); + } + + // Create workers if necessary + if (lilv_plugin_has_extension_data(jalv->plugin, + jalv->nodes.work_interface)) { + jalv->process.worker = jalv_worker_new(&jalv->work_lock, true); + jalv->features.sched.handle = jalv->process.worker; + if (jalv->safe_restore) { + jalv->process.state_worker = jalv_worker_new(&jalv->work_lock, false); + jalv->features.ssched.handle = jalv->process.state_worker; + } + } + + // Load preset, if specified + if (jalv->opts.preset) { + LilvNode* preset = lilv_new_uri(jalv->world, jalv->opts.preset); + + jalv_load_presets(jalv, NULL, NULL); + state = lilv_state_new_from_world(jalv->world, urid_map, preset); + jalv->preset = state; + lilv_node_free(preset); + if (!state) { + jalv_log(JALV_LOG_ERR, "Failed to find preset <%s>\n", jalv->opts.preset); + return -5; + } + } + + // Check for thread-safe state restore() method + jalv->safe_restore = + lilv_plugin_has_feature(jalv->plugin, jalv->nodes.state_threadSafeRestore); + + if (!state) { + // Not restoring state, load the plugin as a preset to get default + state = lilv_state_new_from_world( + jalv->world, urid_map, lilv_plugin_get_uri(jalv->plugin)); + } + + // Get a plugin UI + jalv->uis = lilv_plugin_get_uis(jalv->plugin); + if (!jalv->opts.generic_ui) { + if ((jalv->ui = jalv_select_custom_ui(jalv))) { +#if USE_SUIL + const char* host_type_uri = jalv_frontend_ui_type(); + if (host_type_uri) { + LilvNode* host_type = lilv_new_uri(jalv->world, host_type_uri); + + if (!lilv_ui_is_supported( + jalv->ui, suil_ui_supported, host_type, &jalv->ui_type)) { + jalv->ui = NULL; + } + + lilv_node_free(host_type); + } #endif - jalv->features.make_path.handle = jalv; - jalv->features.make_path.path = jalv_make_path; - init_feature(&jalv->features.make_path_feature, - LV2_STATE__makePath, &jalv->features.make_path); - - jalv->features.sched.handle = &jalv->worker; - jalv->features.sched.schedule_work = jalv_worker_schedule; - init_feature(&jalv->features.sched_feature, - LV2_WORKER__schedule, &jalv->features.sched); - - jalv->features.ssched.handle = &jalv->state_worker; - jalv->features.ssched.schedule_work = jalv_worker_schedule; - init_feature(&jalv->features.state_sched_feature, - LV2_WORKER__schedule, &jalv->features.ssched); - - jalv->features.llog.handle = jalv; - jalv->features.llog.printf = jalv_printf; - jalv->features.llog.vprintf = jalv_vprintf; - init_feature(&jalv->features.log_feature, - LV2_LOG__log, &jalv->features.llog); - - zix_sem_init(&jalv->done, 0); - - zix_sem_init(&jalv->paused, 0); - zix_sem_init(&jalv->worker.sem, 0); - - /* Find all installed plugins */ - LilvWorld* world = lilv_world_new(); - lilv_world_load_all(world); - jalv->world = world; - const LilvPlugins* plugins = lilv_world_get_all_plugins(world); - - /* Cache URIs for concepts we'll use */ - jalv->nodes.atom_AtomPort = lilv_new_uri(world, LV2_ATOM__AtomPort); - jalv->nodes.atom_Chunk = lilv_new_uri(world, LV2_ATOM__Chunk); - jalv->nodes.atom_Float = lilv_new_uri(world, LV2_ATOM__Float); - jalv->nodes.atom_Path = lilv_new_uri(world, LV2_ATOM__Path); - jalv->nodes.atom_Sequence = lilv_new_uri(world, LV2_ATOM__Sequence); - jalv->nodes.lv2_AudioPort = lilv_new_uri(world, LV2_CORE__AudioPort); - jalv->nodes.lv2_CVPort = lilv_new_uri(world, LV2_CORE__CVPort); - jalv->nodes.lv2_ControlPort = lilv_new_uri(world, LV2_CORE__ControlPort); - jalv->nodes.lv2_InputPort = lilv_new_uri(world, LV2_CORE__InputPort); - jalv->nodes.lv2_OutputPort = lilv_new_uri(world, LV2_CORE__OutputPort); - jalv->nodes.lv2_connectionOptional = lilv_new_uri(world, LV2_CORE__connectionOptional); - jalv->nodes.lv2_control = lilv_new_uri(world, LV2_CORE__control); - jalv->nodes.lv2_default = lilv_new_uri(world, LV2_CORE__default); - jalv->nodes.lv2_enumeration = lilv_new_uri(world, LV2_CORE__enumeration); - jalv->nodes.lv2_integer = lilv_new_uri(world, LV2_CORE__integer); - jalv->nodes.lv2_maximum = lilv_new_uri(world, LV2_CORE__maximum); - jalv->nodes.lv2_minimum = lilv_new_uri(world, LV2_CORE__minimum); - jalv->nodes.lv2_name = lilv_new_uri(world, LV2_CORE__name); - jalv->nodes.lv2_reportsLatency = lilv_new_uri(world, LV2_CORE__reportsLatency); - jalv->nodes.lv2_sampleRate = lilv_new_uri(world, LV2_CORE__sampleRate); - jalv->nodes.lv2_symbol = lilv_new_uri(world, LV2_CORE__symbol); - jalv->nodes.lv2_toggled = lilv_new_uri(world, LV2_CORE__toggled); - jalv->nodes.midi_MidiEvent = lilv_new_uri(world, LV2_MIDI__MidiEvent); - jalv->nodes.pg_group = lilv_new_uri(world, LV2_PORT_GROUPS__group); - jalv->nodes.pprops_logarithmic = lilv_new_uri(world, LV2_PORT_PROPS__logarithmic); - jalv->nodes.pprops_notOnGUI = lilv_new_uri(world, LV2_PORT_PROPS__notOnGUI); - jalv->nodes.pprops_rangeSteps = lilv_new_uri(world, LV2_PORT_PROPS__rangeSteps); - jalv->nodes.pset_Preset = lilv_new_uri(world, LV2_PRESETS__Preset); - jalv->nodes.pset_bank = lilv_new_uri(world, LV2_PRESETS__bank); - jalv->nodes.rdfs_comment = lilv_new_uri(world, LILV_NS_RDFS "comment"); - jalv->nodes.rdfs_label = lilv_new_uri(world, LILV_NS_RDFS "label"); - jalv->nodes.rdfs_range = lilv_new_uri(world, LILV_NS_RDFS "range"); - jalv->nodes.rsz_minimumSize = lilv_new_uri(world, LV2_RESIZE_PORT__minimumSize); - jalv->nodes.work_interface = lilv_new_uri(world, LV2_WORKER__interface); - jalv->nodes.work_schedule = lilv_new_uri(world, LV2_WORKER__schedule); - jalv->nodes.end = NULL; - - /* Get plugin URI from loaded state or command line */ - LilvState* state = NULL; - LilvNode* plugin_uri = NULL; - if (jalv->opts.load) { - struct stat info; - stat(jalv->opts.load, &info); - if (S_ISDIR(info.st_mode)) { - char* path = jalv_strjoin(jalv->opts.load, "/state.ttl"); - state = lilv_state_new_from_file(jalv->world, &jalv->map, NULL, path); - free(path); - } else { - state = lilv_state_new_from_file(jalv->world, &jalv->map, NULL, - jalv->opts.load); - } - if (!state) { - fprintf(stderr, "Failed to load state from %s\n", jalv->opts.load); - jalv_close(jalv); - return -2; - } - plugin_uri = lilv_node_duplicate(lilv_state_get_plugin_uri(state)); - } else if (*argc > 1) { - plugin_uri = lilv_new_uri(world, (*argv)[*argc - 1]); - } - - if (!plugin_uri) { - fprintf(stderr, "Missing plugin URI, try lv2ls to list plugins\n"); - jalv_close(jalv); - return -3; - } - - /* Find plugin */ - printf("Plugin: %s\n", lilv_node_as_string(plugin_uri)); - jalv->plugin = lilv_plugins_get_by_uri(plugins, plugin_uri); - lilv_node_free(plugin_uri); - if (!jalv->plugin) { - fprintf(stderr, "Failed to find plugin\n"); - jalv_close(jalv); - return -4; - } - - /* Load preset, if specified */ - if (jalv->opts.preset) { - LilvNode* preset = lilv_new_uri(jalv->world, jalv->opts.preset); - - jalv_load_presets(jalv, NULL, NULL); - state = lilv_state_new_from_world(jalv->world, &jalv->map, preset); - jalv->preset = state; - lilv_node_free(preset); - if (!state) { - fprintf(stderr, "Failed to find preset <%s>\n", jalv->opts.preset); - jalv_close(jalv); - return -5; - } - } - - /* Check for thread-safe state restore() method. */ - LilvNode* state_threadSafeRestore = lilv_new_uri( - jalv->world, LV2_STATE__threadSafeRestore); - if (lilv_plugin_has_feature(jalv->plugin, state_threadSafeRestore)) { - jalv->safe_restore = true; - } - lilv_node_free(state_threadSafeRestore); - - if (!state) { - /* Not restoring state, load the plugin as a preset to get default */ - state = lilv_state_new_from_world( - jalv->world, &jalv->map, lilv_plugin_get_uri(jalv->plugin)); - } - - /* Get a plugin UI */ - const char* native_ui_type_uri = jalv_native_ui_type(); - jalv->uis = lilv_plugin_get_uis(jalv->plugin); - if (!jalv->opts.generic_ui && native_ui_type_uri) { -#ifdef HAVE_SUIL - const LilvNode* native_ui_type = lilv_new_uri(jalv->world, native_ui_type_uri); - LILV_FOREACH(uis, u, jalv->uis) { - const LilvUI* this_ui = lilv_uis_get(jalv->uis, u); - if (lilv_ui_is_supported(this_ui, - suil_ui_supported, - native_ui_type, - &jalv->ui_type)) { - /* TODO: Multiple UI support */ - jalv->ui = this_ui; - break; - } - } -#endif - } else if (!jalv->opts.generic_ui && jalv->opts.show_ui) { - jalv->ui = lilv_uis_get(jalv->uis, lilv_uis_begin(jalv->uis)); - } - - /* Create ringbuffers for UI if necessary */ - if (jalv->ui) { - fprintf(stderr, "UI: %s\n", - lilv_node_as_uri(lilv_ui_get_uri(jalv->ui))); - } else { - fprintf(stderr, "UI: None\n"); - } - - /* Create port and control structures */ - jalv_create_ports(jalv); - jalv_create_controls(jalv, true); - jalv_create_controls(jalv, false); - - if (!(jalv->backend = jalv_backend_init(jalv))) { - fprintf(stderr, "Failed to connect to audio system\n"); - jalv_close(jalv); - return -6; - } - - printf("Sample rate: %u Hz\n", (uint32_t)jalv->sample_rate); - printf("Block length: %u frames\n", jalv->block_length); - printf("MIDI buffers: %zu bytes\n", jalv->midi_buf_size); - - if (jalv->opts.buffer_size == 0) { - /* The UI ring is fed by plugin output ports (usually one), and the UI - updates roughly once per cycle. The ring size is a few times the - size of the MIDI output to give the UI a chance to keep up. The UI - should be able to keep up with 4 cycles, and tests show this works - for me, but this value might need increasing to avoid overflows. - */ - jalv->opts.buffer_size = jalv->midi_buf_size * N_BUFFER_CYCLES; - } - - if (jalv->opts.update_rate == 0.0) { - /* Calculate a reasonable UI update frequency. */ - jalv->ui_update_hz = jalv_ui_refresh_rate(jalv); - } else { - /* Use user-specified UI update rate. */ - jalv->ui_update_hz = jalv->opts.update_rate; - jalv->ui_update_hz = MAX(1.0f, jalv->ui_update_hz); - } - - /* The UI can only go so fast, clamp to reasonable limits */ - jalv->ui_update_hz = MIN(60, jalv->ui_update_hz); - jalv->opts.buffer_size = MAX(4096, jalv->opts.buffer_size); - fprintf(stderr, "Comm buffers: %d bytes\n", jalv->opts.buffer_size); - fprintf(stderr, "Update rate: %.01f Hz\n", jalv->ui_update_hz); - - /* Build options array to pass to plugin */ - const LV2_Options_Option options[ARRAY_SIZE(jalv->features.options)] = { - { LV2_OPTIONS_INSTANCE, 0, jalv->urids.param_sampleRate, - sizeof(float), jalv->urids.atom_Float, &jalv->sample_rate }, - { LV2_OPTIONS_INSTANCE, 0, jalv->urids.bufsz_minBlockLength, - sizeof(int32_t), jalv->urids.atom_Int, &jalv->block_length }, - { LV2_OPTIONS_INSTANCE, 0, jalv->urids.bufsz_maxBlockLength, - sizeof(int32_t), jalv->urids.atom_Int, &jalv->block_length }, - { LV2_OPTIONS_INSTANCE, 0, jalv->urids.bufsz_sequenceSize, - sizeof(int32_t), jalv->urids.atom_Int, &jalv->midi_buf_size }, - { LV2_OPTIONS_INSTANCE, 0, jalv->urids.ui_updateRate, - sizeof(float), jalv->urids.atom_Float, &jalv->ui_update_hz }, - { LV2_OPTIONS_INSTANCE, 0, 0, 0, 0, NULL } - }; - memcpy(jalv->features.options, options, sizeof(jalv->features.options)); - - init_feature(&jalv->features.options_feature, - LV2_OPTIONS__options, - (void*)jalv->features.options); - - init_feature(&jalv->features.safe_restore_feature, - LV2_STATE__threadSafeRestore, - NULL); - - /* Create Plugin <=> UI communication buffers */ - jalv->ui_events = zix_ring_new(jalv->opts.buffer_size); - jalv->plugin_events = zix_ring_new(jalv->opts.buffer_size); - zix_ring_mlock(jalv->ui_events); - zix_ring_mlock(jalv->plugin_events); - - /* Build feature list for passing to plugins */ - const LV2_Feature* const features[] = { - &jalv->features.map_feature, - &jalv->features.unmap_feature, - &jalv->features.sched_feature, - &jalv->features.log_feature, - &jalv->features.options_feature, - &static_features[0], - &static_features[1], - &static_features[2], - &static_features[3], - NULL - }; - jalv->feature_list = calloc(1, sizeof(features)); - if (!jalv->feature_list) { - fprintf(stderr, "Failed to allocate feature list\n"); - jalv_close(jalv); - return -7; - } - memcpy(jalv->feature_list, features, sizeof(features)); - - /* Check that any required features are supported */ - LilvNodes* req_feats = lilv_plugin_get_required_features(jalv->plugin); - LILV_FOREACH(nodes, f, req_feats) { - const char* uri = lilv_node_as_uri(lilv_nodes_get(req_feats, f)); - if (!feature_is_supported(jalv, uri)) { - fprintf(stderr, "Feature %s is not supported\n", uri); - jalv_close(jalv); - return -8; - } - } - lilv_nodes_free(req_feats); - - /* Instantiate the plugin */ - jalv->instance = lilv_plugin_instantiate( - jalv->plugin, jalv->sample_rate, jalv->feature_list); - if (!jalv->instance) { - fprintf(stderr, "Failed to instantiate plugin.\n"); - jalv_close(jalv); - return -9; - } - - jalv->features.ext_data.data_access = - lilv_instance_get_descriptor(jalv->instance)->extension_data; - - fprintf(stderr, "\n"); - if (!jalv->buf_size_set) { - jalv_allocate_port_buffers(jalv); - } - - /* Create workers if necessary */ - if (lilv_plugin_has_extension_data(jalv->plugin, jalv->nodes.work_interface)) { - const LV2_Worker_Interface* iface = (const LV2_Worker_Interface*) - lilv_instance_get_extension_data(jalv->instance, LV2_WORKER__interface); - - jalv_worker_init(jalv, &jalv->worker, iface, true); - if (jalv->safe_restore) { - jalv_worker_init(jalv, &jalv->state_worker, iface, false); - } - } - - /* Apply loaded state to plugin instance if necessary */ - if (state) { - jalv_apply_state(jalv, state); - } - - if (jalv->opts.controls) { - for (char** c = jalv->opts.controls; *c; ++c) { - jalv_apply_control_arg(jalv, *c); - } - } - - /* Create Jack ports and connect plugin ports to buffers */ - for (uint32_t i = 0; i < jalv->num_ports; ++i) { - jalv_backend_activate_port(jalv, i); - } - - /* Print initial control values */ - for (size_t i = 0; i < jalv->controls.n_controls; ++i) { - ControlID* control = jalv->controls.controls[i]; - if (control->type == PORT && control->is_writable) { - struct Port* port = &jalv->ports[control->index]; - jalv_print_control(jalv, port, port->control); - } - } - - /* Activate plugin */ - lilv_instance_activate(jalv->instance); - - /* Discover UI */ - jalv->has_ui = jalv_discover_ui(jalv); - - /* Activate Jack */ - jalv_backend_activate(jalv); - jalv->play_state = JALV_RUNNING; - - return 0; + jalv_log(JALV_LOG_INFO, + "UI: %s\n", + lilv_node_as_uri(lilv_ui_get_uri(jalv->ui))); + } + } + + // Initialize process thread + const uint32_t update_frames = + (uint32_t)(settings->sample_rate / settings->ui_update_hz); + jalv_process_init(&jalv->process, &jalv->urids, jalv->mapper, update_frames); + + // Create port structures + if (jalv_create_ports(jalv)) { + return -10; + } + + // Create input and output control structures + jalv_create_controls(jalv, true); + jalv_create_controls(jalv, false); + + if (jalv_backend_open(jalv->backend, + &jalv->urids, + &jalv->settings, + &jalv->process, + &jalv->done, + jalv->opts.name, + jalv->opts.name_exact)) { + jalv_log(JALV_LOG_ERR, "Failed to connect to audio system\n"); + return -6; + } + + jalv_log( + JALV_LOG_INFO, "Sample rate: %u Hz\n", (uint32_t)settings->sample_rate); + jalv_log(JALV_LOG_INFO, "Block length: %u frames\n", settings->block_length); + jalv_log(JALV_LOG_INFO, "MIDI buffers: %zu bytes\n", settings->midi_buf_size); + + jalv_init_ui_settings(jalv); + jalv_init_lv2_options(&jalv->features, &jalv->urids, settings); + + // Create Plugin => UI communication buffers + jalv->ui_msg = zix_aligned_alloc(NULL, 8U, jalv->ui_msg_size); + + // Build feature list for passing to plugins + const LV2_Feature* const features[] = {&jalv->features.map_feature, + &jalv->features.unmap_feature, + &jalv->features.sched_feature, + &jalv->features.log_feature, + &jalv->features.options_feature, + &static_features[0], + &static_features[1], + &static_features[2], + &static_features[3], + NULL}; + + jalv->feature_list = (const LV2_Feature**)calloc(1, sizeof(features)); + if (!jalv->feature_list) { + jalv_log(JALV_LOG_ERR, "Failed to allocate feature list\n"); + return -7; + } + memcpy(jalv->feature_list, features, sizeof(features)); + + // Check that any required features are supported + LilvNodes* req_feats = lilv_plugin_get_required_features(jalv->plugin); + LILV_FOREACH (nodes, f, req_feats) { + const char* uri = lilv_node_as_uri(lilv_nodes_get(req_feats, f)); + if (!feature_is_supported(jalv, uri)) { + jalv_log(JALV_LOG_ERR, "Feature %s is not supported\n", uri); + return -8; + } + } + lilv_nodes_free(req_feats); + + // Instantiate the plugin + LilvInstance* const instance = lilv_plugin_instantiate( + jalv->plugin, settings->sample_rate, jalv->feature_list); + if (!instance) { + jalv_log(JALV_LOG_ERR, "Failed to instantiate plugin\n"); + return -9; + } + + // Point things to the instance that require it + + // jalv->process.instance = instance; + jalv->features.ext_data.data_access = + lilv_instance_get_descriptor(instance)->extension_data; + + const LV2_Worker_Interface* worker_iface = + (const LV2_Worker_Interface*)lilv_instance_get_extension_data( + instance, LV2_WORKER__interface); + + jalv_worker_attach(jalv->process.worker, worker_iface, instance->lv2_handle); + jalv_worker_attach( + jalv->process.state_worker, worker_iface, instance->lv2_handle); + jalv_log(JALV_LOG_INFO, "\n"); + + // Allocate port buffers + jalv_process_activate( + &jalv->process, &jalv->urids, instance, &jalv->settings); + + // Apply loaded state to plugin instance if necessary + if (state) { + jalv_apply_state(jalv, state); + lilv_state_free(state); + } + + // Apply initial controls from command-line arguments + if (jalv->opts.controls) { + for (char** c = jalv->opts.controls; *c; ++c) { + jalv_apply_control_arg(jalv, *c); + } + } + + // Create Jack ports and connect plugin ports to buffers + for (uint32_t i = 0; i < jalv->num_ports; ++i) { + jalv_backend_activate_port(jalv->backend, &jalv->process, i); + } + + // Discover UI + jalv->process.has_ui = jalv_frontend_discover(jalv); + return 0; } int -jalv_close(Jalv* const jalv) +jalv_activate(Jalv* const jalv) { - jalv->exit = true; - - fprintf(stderr, "Exiting...\n"); - - /* Terminate the worker */ - jalv_worker_finish(&jalv->worker); - - /* Deactivate audio */ - jalv_backend_deactivate(jalv); - for (uint32_t i = 0; i < jalv->num_ports; ++i) { - if (jalv->ports[i].evbuf) { - lv2_evbuf_free(jalv->ports[i].evbuf); - } - } - jalv_backend_close(jalv); + jalv->process.run_state = JALV_RUNNING; - /* Destroy the worker */ - jalv_worker_destroy(&jalv->worker); + if (jalv->backend) { + if (jalv->process.worker) { + jalv_worker_launch(jalv->process.worker); + } + lilv_instance_activate(jalv->process.instance); + jalv_backend_activate(jalv->backend); + } - /* Deactivate plugin */ -#ifdef HAVE_SUIL - suil_instance_free(jalv->ui_instance); -#endif - if (jalv->instance) { - lilv_instance_deactivate(jalv->instance); - lilv_instance_free(jalv->instance); - } - - /* Clean up */ - free(jalv->ports); - zix_ring_free(jalv->ui_events); - zix_ring_free(jalv->plugin_events); - for (LilvNode** n = (LilvNode**)&jalv->nodes; *n; ++n) { - lilv_node_free(*n); - } - symap_free(jalv->symap); - zix_sem_destroy(&jalv->symap_lock); -#ifdef HAVE_SUIL - suil_host_free(jalv->ui_host); -#endif - - for (unsigned i = 0; i < jalv->controls.n_controls; ++i) { - ControlID* const control = jalv->controls.controls[i]; - lilv_node_free(control->node); - lilv_node_free(control->symbol); - lilv_node_free(control->label); - lilv_node_free(control->group); - lilv_node_free(control->min); - lilv_node_free(control->max); - lilv_node_free(control->def); - free(control); - } - free(jalv->controls.controls); - - if (jalv->sratom) { - sratom_free(jalv->sratom); - } - if (jalv->ui_sratom) { - sratom_free(jalv->ui_sratom); - } - lilv_uis_free(jalv->uis); - lilv_world_free(jalv->world); - - zix_sem_destroy(&jalv->done); - - remove(jalv->temp_dir); - free(jalv->temp_dir); - free(jalv->ui_event_buf); - free(jalv->feature_list); - - free(jalv->opts.name); - free(jalv->opts.uuid); - free(jalv->opts.load); - free(jalv->opts.controls); - - return 0; + return 0; } int -main(int argc, char** argv) +jalv_deactivate(Jalv* const jalv) { - Jalv jalv; - memset(&jalv, '\0', sizeof(Jalv)); - - if (jalv_open(&jalv, &argc, &argv)) { - return EXIT_FAILURE; - } - - /* Set up signal handlers */ - setup_signals(&jalv); - - /* Run UI (or prompt at console) */ - jalv_open_ui(&jalv); + if (jalv->backend) { + jalv_backend_deactivate(jalv->backend); + } + if (jalv->process.instance) { + lilv_instance_deactivate(jalv->process.instance); + } + if (jalv->process.worker) { + jalv_worker_exit(jalv->process.worker); + } + + jalv->process.run_state = JALV_PAUSED; + return 0; +} - /* Wait for finish signal from UI or signal handler */ - zix_sem_wait(&jalv.done); +int +jalv_close(Jalv* const jalv) +{ + // Stop audio processing, free event port buffers, and close backend + jalv_deactivate(jalv); + jalv_process_deactivate(&jalv->process); + if (jalv->backend) { + jalv_backend_close(jalv->backend); + } + + // Free UI and plugin instances +#if USE_SUIL + suil_instance_free(jalv->ui_instance); +#endif + if (jalv->process.instance) { + lilv_instance_free(jalv->process.instance); + } + + // Clean up + lilv_state_free(jalv->preset); + free(jalv->ports); + jalv_process_cleanup(&jalv->process); + zix_aligned_free(NULL, jalv->ui_msg); + free(jalv->process.controls_buf); + jalv_free_nodes(&jalv->nodes); +#if USE_SUIL + suil_host_free(jalv->ui_host); +#endif - return jalv_close(&jalv); + for (unsigned i = 0; i < jalv->controls.n_controls; ++i) { + free_control(jalv->controls.controls[i]); + } + free(jalv->controls.controls); + + jalv_dumper_free(jalv->dumper); + lilv_uis_free(jalv->uis); + jalv_mapper_free(jalv->mapper); + lilv_world_free(jalv->world); + + zix_sem_destroy(&jalv->done); + + if (jalv->temp_dir) { + // Remove temporary state directory + const ZixStatus zst = zix_remove(jalv->temp_dir); + if (zst) { + jalv_log(JALV_LOG_WARNING, + "Failed to remove temporary directory %s (%s)\n", + jalv->temp_dir, + zix_strerror(zst)); + } + } + + zix_free(NULL, jalv->temp_dir); + free(jalv->feature_list); + + free(jalv->opts.name); + free(jalv->opts.load); + free(jalv->opts.controls); + + return 0; } diff --git a/src/jalv.h b/src/jalv.h new file mode 100644 index 0000000..518f94d --- /dev/null +++ b/src/jalv.h @@ -0,0 +1,118 @@ +// Copyright 2007-2022 David Robillard <d@drobilla.net> +// SPDX-License-Identifier: ISC + +#ifndef JALV_JALV_H +#define JALV_JALV_H + +#include "attributes.h" +#include "control.h" +#include "dumper.h" +#include "features.h" +#include "jalv_config.h" +#include "log.h" +#include "mapper.h" +#include "nodes.h" +#include "options.h" +#include "port.h" +#include "process.h" +#include "settings.h" +#include "types.h" +#include "urids.h" + +#if USE_SUIL +# include <suil/suil.h> +#endif + +#include <lilv/lilv.h> +#include <lv2/atom/forge.h> +#include <lv2/core/lv2.h> +#include <lv2/urid/urid.h> +#include <zix/sem.h> + +#include <stdbool.h> +#include <stdint.h> +#include <stdio.h> + +// "Shared" internal application declarations +JALV_BEGIN_DECLS + +/// Internal application state +struct JalvImpl { + JalvOptions opts; ///< Command-line options + LilvWorld* world; ///< Lilv World + JalvMapper* mapper; ///< URI mapper/unmapper + JalvURIDs urids; ///< URIDs + JalvNodes nodes; ///< Nodes + JalvLog log; ///< Log for error/warning/debug messages + LV2_Atom_Forge forge; ///< Atom forge + JalvDumper* dumper; ///< Atom dumper (console debug output) + JalvBackend* backend; ///< Audio system backend + JalvSettings settings; ///< Processing settings + void* ui_msg; ///< Buffer for messages in the UI thread + ZixSem work_lock; ///< Lock for plugin work() method + ZixSem done; ///< Exit semaphore + char* temp_dir; ///< Temporary plugin state directory + char* save_dir; ///< Plugin save directory + const LilvPlugin* plugin; ///< Plugin class (RDF data) + LilvState* preset; ///< Current preset + LilvUIs* uis; ///< All plugin UIs (RDF data) + const LilvUI* ui; ///< Plugin UI (RDF data) + const LilvNode* ui_type; ///< Plugin UI type (unwrapped) + JalvProcess process; ///< Process thread state +#if USE_SUIL + SuilHost* ui_host; ///< Plugin UI host support + SuilInstance* ui_instance; ///< Plugin UI instance (shared library) +#endif + void* window; ///< Window (if applicable) + JalvPort* ports; ///< Port array of size num_ports + Controls controls; ///< Available plugin controls + size_t ui_msg_size; ///< Maximum size of a single message + uint32_t num_ports; ///< Total number of ports on the plugin + bool safe_restore; ///< Plugin restore() is thread-safe + JalvFeatures features; + const LV2_Feature** feature_list; +}; + +/// Load the plugin and set up the application +int +jalv_open(Jalv* jalv, int* argc, char*** argv); + +/// Shut down the application (counterpart to jalv_open) +int +jalv_close(Jalv* jalv); + +/// Activate audio processing +int +jalv_activate(Jalv* jalv); + +/// Deactivate audio processing +int +jalv_deactivate(Jalv* jalv); + +/// Find a port by symbol +JalvPort* +jalv_port_by_symbol(Jalv* jalv, const char* sym); + +/// Set a control to the given value +void +jalv_set_control(Jalv* jalv, + const ControlID* control, + uint32_t size, + LV2_URID type, + const void* body); + +/// Request and/or set initial control values to initialize the UI +void +jalv_init_ui(Jalv* jalv); + +/// Instantiate the UI instance using suil if available +void +jalv_ui_instantiate(Jalv* jalv, const char* native_ui_type, void* parent); + +/// Periodically update user interface +int +jalv_update(Jalv* jalv); + +JALV_END_DECLS + +#endif // JALV_JALV_H diff --git a/src/jalv_config.h b/src/jalv_config.h new file mode 100644 index 0000000..4bcda8c --- /dev/null +++ b/src/jalv_config.h @@ -0,0 +1,166 @@ +// Copyright 2021-2022 David Robillard <d@drobilla.net> +// SPDX-License-Identifier: ISC + +/* + Configuration header that defines reasonable defaults at compile time. + + This allows compile-time configuration from the command line, while still + allowing the source to be built "as-is" without any configuration. The idea + is to support an advanced build system with configuration checks, while still + allowing the code to be simply "thrown at a compiler" with features + determined from the compiler or system headers. Everything can be + overridden, so it should never be necessary to edit this file to build + successfully. + + To ensure that all configure checks are performed, the build system can + define JALV_NO_DEFAULT_CONFIG to disable defaults. In this case, it must + define all HAVE_FEATURE symbols below to 1 or 0 to enable or disable + features. Any missing definitions will generate a compiler warning. + + To ensure that this header is always included properly, all code that uses + configuration variables includes this header and checks their value with #if + (not #ifdef). Variables like USE_FEATURE are internal and should never be + defined on the command line. +*/ + +#ifndef JALV_CONFIG_H +#define JALV_CONFIG_H + +// Define version unconditionally so a warning will catch a mismatch +#define JALV_VERSION "1.6.9" + +#if !defined(JALV_NO_DEFAULT_CONFIG) + +// We need unistd.h to check _POSIX_VERSION +# ifndef JALV_NO_POSIX +# ifdef __has_include +# if __has_include(<unistd.h>) +# include <unistd.h> +# endif +# elif defined(__unix__) +# include <unistd.h> +# endif +# endif + +// POSIX.1-2001: fileno() +# ifndef HAVE_FILENO +# if defined(_POSIX_VERSION) && _POSIX_VERSION >= 200112L +# define HAVE_FILENO 1 +# else +# define HAVE_FILENO 0 +# endif +# endif + +// POSIX.1-2001: isatty() +# ifndef HAVE_ISATTY +# if defined(_POSIX_VERSION) && _POSIX_VERSION >= 200112L +# define HAVE_ISATTY 1 +# else +# define HAVE_ISATTY 0 +# endif +# endif + +// POSIX.1-2001: posix_memalign() +# ifndef HAVE_POSIX_MEMALIGN +# if defined(_POSIX_VERSION) && _POSIX_VERSION >= 200112L +# define HAVE_POSIX_MEMALIGN 1 +# else +# define HAVE_POSIX_MEMALIGN 0 +# endif +# endif + +// POSIX.1-2001: sigaction() +# ifndef HAVE_SIGACTION +# if defined(_POSIX_VERSION) && _POSIX_VERSION >= 200112L +# define HAVE_SIGACTION 1 +# else +# define HAVE_SIGACTION 0 +# endif +# endif + +// Suil +# ifndef HAVE_SUIL +# ifdef __has_include +# if __has_include("suil/suil.h") +# define HAVE_SUIL 1 +# else +# define HAVE_SUIL 0 +# endif +# endif +# endif + +// JACK metadata API +# ifndef HAVE_JACK_METADATA +# ifdef __has_include +# if __has_include("jack/metadata.h") +# define HAVE_JACK_METADATA 1 +# else +# define HAVE_JACK_METADATA 0 +# endif +# endif +# endif + +// JACK jack_port_type_get_buffer_size() function +# ifndef HAVE_JACK_PORT_TYPE_GET_BUFFER_SIZE +# ifdef __has_include +# if __has_include("jack/midiport.h") +# define HAVE_JACK_PORT_TYPE_GET_BUFFER_SIZE 1 +# else +# define HAVE_JACK_PORT_TYPE_GET_BUFFER_SIZE 0 +# endif +# endif +# endif + +#endif // !defined(JALV_NO_DEFAULT_CONFIG) + +/* + Make corresponding USE_FEATURE defines based on the HAVE_FEATURE defines from + above or the command line. The code checks for these using #if (not #ifdef), + so there will be an undefined warning if it checks for an unknown feature, + and this header is always required by any code that checks for features, even + if the build system defines them all. +*/ + +#if HAVE_FILENO +# define USE_FILENO 1 +#else +# define USE_FILENO 0 +#endif + +#if HAVE_ISATTY +# define USE_ISATTY 1 +#else +# define USE_ISATTY 0 +#endif + +#if HAVE_POSIX_MEMALIGN +# define USE_POSIX_MEMALIGN 1 +#else +# define USE_POSIX_MEMALIGN 0 +#endif + +#if HAVE_SIGACTION +# define USE_SIGACTION 1 +#else +# define USE_SIGACTION 0 +#endif + +#if HAVE_SUIL +# define USE_SUIL 1 +#else +# define USE_SUIL 0 +#endif + +#if HAVE_JACK_METADATA +# define USE_JACK_METADATA 1 +#else +# define USE_JACK_METADATA 0 +#endif + +#if HAVE_JACK_PORT_TYPE_GET_BUFFER_SIZE +# define USE_JACK_PORT_TYPE_GET_BUFFER_SIZE 1 +#else +# define USE_JACK_PORT_TYPE_GET_BUFFER_SIZE 0 +#endif + +#endif // JALV_CONFIG_H diff --git a/src/jalv_console.c b/src/jalv_console.c index 7d11714..fe92cd7 100644 --- a/src/jalv_console.c +++ b/src/jalv_console.c @@ -1,288 +1,378 @@ -/* - Copyright 2007-2016 David Robillard <http://drobilla.net> - - Permission to use, copy, modify, and/or distribute this software for any - purpose with or without fee is hereby granted, provided that the above - copyright notice and this permission notice appear in all copies. - - THIS SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES - WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF - MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR - ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES - WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN - ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF - OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. -*/ - -#define _POSIX_C_SOURCE 200809L -#define _XOPEN_SOURCE 600 -#define _BSD_SOURCE 1 -#define _DEFAULT_SOURCE 1 +// Copyright 2007-2024 David Robillard <d@drobilla.net> +// SPDX-License-Identifier: ISC +#include "comm.h" +#include "control.h" +#include "frontend.h" +#include "jalv.h" #include "jalv_config.h" -#include "jalv_internal.h" +#include "log.h" +#include "options.h" +#include "port.h" +#include "state.h" +#include "string_utils.h" +#include "types.h" -#include "lv2/ui/ui.h" +#include <lilv/lilv.h> +#include <lv2/ui/ui.h> +#include <zix/attributes.h> +#include <zix/sem.h> +#if USE_SUIL +# include <suil/suil.h> +#endif + +#ifdef _WIN32 +# include <synchapi.h> +#else +# include <time.h> +#endif + +#include <assert.h> #include <stdbool.h> +#include <stdint.h> #include <stdio.h> +#include <stdlib.h> #include <string.h> -#include <unistd.h> static int print_usage(const char* name, bool error) { - FILE* const os = error ? stderr : stdout; - fprintf(os, "Usage: %s [OPTION...] PLUGIN_URI\n", name); - fprintf(os, "Run an LV2 plugin as a Jack application.\n"); - fprintf(os, " -b SIZE Buffer size for plugin <=> UI communication\n"); - fprintf(os, " -c SYM=VAL Set control value (e.g. \"vol=1.4\")\n"); - fprintf(os, " -d Dump plugin <=> UI communication\n"); - fprintf(os, " -h Display this help and exit\n"); - fprintf(os, " -l DIR Load state from save directory\n"); - fprintf(os, " -n NAME JACK client name\n"); - fprintf(os, " -p Print control output changes to stdout\n"); - fprintf(os, " -s Show plugin UI if possible\n"); - fprintf(os, " -t Print trace messages from plugin\n"); - fprintf(os, " -u UUID UUID for Jack session restoration\n"); - fprintf(os, " -x Exact JACK client name (exit if taken)\n"); - return error ? 1 : 0; + FILE* const os = error ? stderr : stdout; + fprintf(os, "Usage: %s [OPTION...] PLUGIN_URI\n", name); + fprintf(os, + "Run an LV2 plugin as a Jack application.\n" + " -b SIZE Buffer size for plugin <=> UI communication\n" + " -c SYM=VAL Set control value (like \"vol=1.4\")\n" + " -d Dump plugin <=> UI communication\n" + " -h Display this help and exit\n" + " -i Ignore keyboard input, run non-interactively\n" + " -l DIR Load state from save directory\n" + " -n NAME JACK client name\n" + " -p Print control output changes to stdout\n" + " -s Show plugin UI if possible\n" + " -t Print trace messages from plugin\n" + " -U URI Load the UI with the given URI\n" + " -V Display version information and exit\n" + " -x Exit if the requested JACK client name is taken\n"); + return error ? 1 : JALV_EARLY_EXIT_STATUS; +} + +static int +print_version(void) +{ + printf("jalv " JALV_VERSION " <http://drobilla.net/software/jalv>\n"); + printf("Copyright 2011-2024 David Robillard <d@drobilla.net>\n" + "License ISC: <https://spdx.org/licenses/ISC>.\n" + "This is free software; you are free to change and redistribute it." + "\nThere is NO WARRANTY, to the extent permitted by law.\n"); + return JALV_EARLY_EXIT_STATUS; +} + +static int +print_arg_error(const char* const command, const char* const msg) +{ + fprintf(stderr, "%s: %s\n", command, msg); + return 1; +} + +static void +print_control_port(const Jalv* const jalv, + const JalvPort* const port, + const float value) +{ + const LilvNode* sym = lilv_port_get_symbol(jalv->plugin, port->lilv_port); + jalv_log(JALV_LOG_INFO, "%s = %f\n", lilv_node_as_string(sym), value); } void -jalv_ui_port_event(ZIX_UNUSED Jalv* jalv, - ZIX_UNUSED uint32_t port_index, - ZIX_UNUSED uint32_t buffer_size, - ZIX_UNUSED uint32_t protocol, - ZIX_UNUSED const void* buffer) +jalv_frontend_port_event(Jalv* jalv, + uint32_t port_index, + uint32_t buffer_size, + uint32_t protocol, + const void* buffer) { +#if USE_SUIL + if (jalv->ui_instance) { + suil_instance_port_event( + jalv->ui_instance, port_index, buffer_size, protocol, buffer); + } +#else + (void)buffer_size; +#endif + + if (!protocol && jalv->opts.print_controls) { + assert(buffer_size == sizeof(float)); + print_control_port(jalv, &jalv->ports[port_index], *(float*)buffer); + } } int -jalv_init(int* argc, char*** argv, JalvOptions* opts) +jalv_frontend_init(JalvFrontendArgs* const args, JalvOptions* const opts) { - int n_controls = 0; - int a = 1; - for (; a < *argc && (*argv)[a][0] == '-'; ++a) { - if ((*argv)[a][1] == 'h') { - return print_usage((*argv)[0], true); - } else if ((*argv)[a][1] == 's') { - opts->show_ui = true; - } else if ((*argv)[a][1] == 'p') { - opts->print_controls = true; - } else if ((*argv)[a][1] == 'u') { - if (++a == *argc) { - fprintf(stderr, "Missing argument for -u\n"); - return 1; - } - opts->uuid = jalv_strdup((*argv)[a]); - } else if ((*argv)[a][1] == 'l') { - if (++a == *argc) { - fprintf(stderr, "Missing argument for -l\n"); - return 1; - } - opts->load = jalv_strdup((*argv)[a]); - } else if ((*argv)[a][1] == 'b') { - if (++a == *argc) { - fprintf(stderr, "Missing argument for -b\n"); - return 1; - } - opts->buffer_size = atoi((*argv)[a]); - } else if ((*argv)[a][1] == 'c') { - if (++a == *argc) { - fprintf(stderr, "Missing argument for -c\n"); - return 1; - } - opts->controls = (char**)realloc( - opts->controls, (++n_controls + 1) * sizeof(char*)); - opts->controls[n_controls - 1] = (*argv)[a]; - opts->controls[n_controls] = NULL; - } else if ((*argv)[a][1] == 'i') { - opts->non_interactive = true; - } else if ((*argv)[a][1] == 'd') { - opts->dump = true; - } else if ((*argv)[a][1] == 't') { - opts->trace = true; - } else if ((*argv)[a][1] == 'n') { - if (++a == *argc) { - fprintf(stderr, "Missing argument for -n\n"); - return 1; - } - free(opts->name); - opts->name = jalv_strdup((*argv)[a]); - } else if ((*argv)[a][1] == 'x') { - opts->name_exact = 1; - } else { - fprintf(stderr, "Unknown option %s\n", (*argv)[a]); - return print_usage((*argv)[0], true); - } - } - - return 0; + const int argc = *args->argc; + char** argv = *args->argv; + + const char* const cmd = argv[0]; + + int n_controls = 0; + int a = 1; + for (; a < argc && argv[a][0] == '-'; ++a) { + if (argv[a][1] == 'h' || !strcmp(argv[a], "--help")) { + return print_usage(cmd, false); + } + + if (argv[a][1] == 'V' || !strcmp(argv[a], "--version")) { + return print_version(); + } + + if (argv[a][1] == 's') { + opts->show_ui = true; + } else if (argv[a][1] == 'p') { + opts->print_controls = true; + } else if (argv[a][1] == 'U') { + if (++a == argc) { + return print_arg_error(cmd, "option requires an argument -- 'U'"); + } + opts->ui_uri = jalv_strdup(argv[a]); + } else if (argv[a][1] == 'l') { + if (++a == argc) { + return print_arg_error(cmd, "option requires an argument -- 'l'"); + } + opts->load = jalv_strdup(argv[a]); + } else if (argv[a][1] == 'b') { + if (++a == argc) { + return print_arg_error(cmd, "option requires an argument -- 'b'"); + } + opts->ring_size = atoi(argv[a]); + } else if (argv[a][1] == 'c') { + if (++a == argc) { + return print_arg_error(cmd, "option requires an argument -- 'c'"); + } + + char** new_controls = + (char**)realloc(opts->controls, (n_controls + 2) * sizeof(char*)); + if (!new_controls) { + fprintf(stderr, "Out of memory\n"); + return 12; + } + + opts->controls = new_controls; + opts->controls[n_controls++] = argv[a]; + opts->controls[n_controls] = NULL; + } else if (argv[a][1] == 'i') { + opts->non_interactive = true; + } else if (argv[a][1] == 'd') { + opts->dump = true; + } else if (argv[a][1] == 't') { + opts->trace = true; + } else if (argv[a][1] == 'n') { + if (++a == argc) { + return print_arg_error(cmd, "option requires an argument -- 'n'"); + } + free(opts->name); + opts->name = jalv_strdup(argv[a]); + } else if (argv[a][1] == 'x') { + opts->name_exact = 1; + } else { + fprintf(stderr, "%s: unknown option -- '%c'\n", cmd, argv[a][1]); + return print_usage(argv[0], true); + } + } + + *args->argc = *args->argc - a; + *args->argv = *args->argv + a; + return 0; } const char* -jalv_native_ui_type(void) +jalv_frontend_ui_type(void) { - return NULL; + return NULL; } static void -jalv_print_controls(Jalv* jalv, bool writable, bool readable) +print_controls(const Jalv* const jalv, const bool writable, const bool readable) { - for (size_t i = 0; i < jalv->controls.n_controls; ++i) { - ControlID* const control = jalv->controls.controls[i]; - if ((control->is_writable && writable) || - (control->is_readable && readable)) { - struct Port* const port = &jalv->ports[control->index]; - printf("%s = %f\n", - lilv_node_as_string(control->symbol), - port->control); - } - } + for (size_t i = 0; i < jalv->controls.n_controls; ++i) { + ControlID* const control = jalv->controls.controls[i]; + if (control->type == PORT && ((control->is_writable && writable) || + (control->is_readable && readable))) { + jalv_log(JALV_LOG_INFO, + "%s = %f\n", + lilv_node_as_string(control->symbol), + jalv->process.controls_buf[control->id.index]); + } + } + + fflush(stdout); } static int -jalv_print_preset(Jalv* jalv, +jalv_print_preset(Jalv* ZIX_UNUSED(jalv), const LilvNode* node, const LilvNode* title, - void* data) + void* ZIX_UNUSED(data)) { - printf("%s (%s)\n", lilv_node_as_string(node), lilv_node_as_string(title)); - return 0; + printf("%s (%s)\n", lilv_node_as_string(node), lilv_node_as_string(title)); + return 0; } static void jalv_process_command(Jalv* jalv, const char* cmd) { - char sym[64]; - uint32_t index; - float value; - if (!strncmp(cmd, "help", 4)) { - fprintf(stderr, - "Commands:\n" - " help Display this help message\n" - " controls Print settable control values\n" - " monitors Print output control values\n" - " presets Print available presets\n" - " preset URI Set preset\n" - " set INDEX VALUE Set control value by port index\n" - " set SYMBOL VALUE Set control value by symbol\n" - " SYMBOL = VALUE Set control value by symbol\n"); - } else if (strcmp(cmd, "presets\n") == 0) { - jalv_unload_presets(jalv); - jalv_load_presets(jalv, jalv_print_preset, NULL); - } else if (sscanf(cmd, "preset %[a-zA-Z0-9_:/-.#]\n", sym) == 1) { - LilvNode* preset = lilv_new_uri(jalv->world, sym); - jalv_apply_preset(jalv, preset); - lilv_node_free(preset); - jalv_print_controls(jalv, true, false); - } else if (strcmp(cmd, "controls\n") == 0) { - jalv_print_controls(jalv, true, false); - } else if (strcmp(cmd, "monitors\n") == 0) { - jalv_print_controls(jalv, false, true); - } else if (sscanf(cmd, "set %u %f", &index, &value) == 2) { - if (index < jalv->num_ports) { - jalv->ports[index].control = value; - jalv_print_control(jalv, &jalv->ports[index], value); - } else { - fprintf(stderr, "error: port index out of range\n"); - } - } else if (sscanf(cmd, "set %[a-zA-Z0-9_] %f", sym, &value) == 2 || - sscanf(cmd, "%[a-zA-Z0-9_] = %f", sym, &value) == 2) { - struct Port* port = NULL; - for (uint32_t i = 0; i < jalv->num_ports; ++i) { - struct Port* p = &jalv->ports[i]; - const LilvNode* s = lilv_port_get_symbol(jalv->plugin, p->lilv_port); - if (!strcmp(lilv_node_as_string(s), sym)) { - port = p; - break; - } - } - if (port) { - port->control = value; - jalv_print_control(jalv, port, value); - } else { - fprintf(stderr, "error: no control named `%s'\n", sym); - } - } else { - fprintf(stderr, "error: invalid command (try `help')\n"); - } + char sym[1024]; + uint32_t index = 0; + float value = 0.0f; + if (!strncmp(cmd, "help", 4)) { + fprintf(stderr, + "Commands:\n" + " help Display this help message\n" + " controls Print settable control values\n" + " monitors Print output control values\n" + " presets Print available presets\n" + " preset URI Set preset\n" + " set INDEX VALUE Set control value by port index\n" + " set SYMBOL VALUE Set control value by symbol\n" + " SYMBOL = VALUE Set control value by symbol\n"); + } else if (strcmp(cmd, "presets\n") == 0) { + jalv_unload_presets(jalv); + jalv_load_presets(jalv, jalv_print_preset, NULL); + } else if (sscanf(cmd, "preset %1023[a-zA-Z0-9_:/-.#]\n", sym) == 1) { + LilvNode* preset = lilv_new_uri(jalv->world, sym); + lilv_world_load_resource(jalv->world, preset); + jalv_apply_preset(jalv, preset); + lilv_node_free(preset); + print_controls(jalv, true, false); + } else if (strcmp(cmd, "controls\n") == 0) { + print_controls(jalv, true, false); + } else if (strcmp(cmd, "monitors\n") == 0) { + print_controls(jalv, false, true); + } else if (sscanf(cmd, "set %u %f", &index, &value) == 2) { + if (index < jalv->num_ports) { + jalv_write_control(jalv->process.ui_to_plugin, index, value); + print_control_port(jalv, &jalv->ports[index], value); + } else { + fprintf(stderr, "error: port index out of range\n"); + } + } else if (sscanf(cmd, "set %1023[a-zA-Z0-9_] %f", sym, &value) == 2 || + sscanf(cmd, "%1023[a-zA-Z0-9_] = %f", sym, &value) == 2) { + const JalvPort* const port = jalv_port_by_symbol(jalv, sym); + if (port) { + jalv->process.controls_buf[port->index] = value; + print_control_port(jalv, port, value); + } else { + fprintf(stderr, "error: no control named `%s'\n", sym); + } + } else { + fprintf(stderr, "error: invalid command (try `help')\n"); + } } bool -jalv_discover_ui(Jalv* jalv) +jalv_frontend_discover(const Jalv* jalv) { - return jalv->opts.show_ui; + return jalv->opts.show_ui; } static bool jalv_run_custom_ui(Jalv* jalv) { -#ifdef HAVE_SUIL - const LV2UI_Idle_Interface* idle_iface = NULL; - const LV2UI_Show_Interface* show_iface = NULL; - if (jalv->ui && jalv->opts.show_ui) { - jalv_ui_instantiate(jalv, jalv_native_ui_type(), NULL); - idle_iface = (const LV2UI_Idle_Interface*) - suil_instance_extension_data(jalv->ui_instance, LV2_UI__idleInterface); - show_iface = (const LV2UI_Show_Interface*) - suil_instance_extension_data(jalv->ui_instance, LV2_UI__showInterface); - } - - if (show_iface && idle_iface) { - show_iface->show(suil_instance_get_handle(jalv->ui_instance)); - - // Drive idle interface until interrupted - while (!zix_sem_try_wait(&jalv->done)) { - jalv_update(jalv); - if (idle_iface->idle(suil_instance_get_handle(jalv->ui_instance))) { - break; - } - usleep(33333); - } - - show_iface->hide(suil_instance_get_handle(jalv->ui_instance)); - return true; - } +#if USE_SUIL + const LV2UI_Idle_Interface* idle_iface = NULL; + const LV2UI_Show_Interface* show_iface = NULL; + if (jalv->ui && jalv->opts.show_ui) { + jalv_ui_instantiate(jalv, jalv_frontend_ui_type(), NULL); + idle_iface = (const LV2UI_Idle_Interface*)suil_instance_extension_data( + jalv->ui_instance, LV2_UI__idleInterface); + show_iface = (const LV2UI_Show_Interface*)suil_instance_extension_data( + jalv->ui_instance, LV2_UI__showInterface); + } + + if (show_iface && idle_iface) { + show_iface->show(suil_instance_get_handle(jalv->ui_instance)); + + // Drive idle interface until interrupted + while (zix_sem_try_wait(&jalv->done)) { + jalv_update(jalv); + if (idle_iface->idle(suil_instance_get_handle(jalv->ui_instance))) { + break; + } + +# ifdef _WIN32 + Sleep(33); +# else + const struct timespec delay = {0, 33333000}; + nanosleep(&delay, NULL); +# endif + } + + show_iface->hide(suil_instance_get_handle(jalv->ui_instance)); + return true; + } +#else + (void)jalv; #endif - return false; + return false; } float -jalv_ui_refresh_rate(Jalv* jalv) +jalv_frontend_refresh_rate(const Jalv* ZIX_UNUSED(jalv)) { - return 30.0f; + return 30.0f; +} + +float +jalv_frontend_scale_factor(const Jalv* ZIX_UNUSED(jalv)) +{ + return 1.0f; +} + +LilvNode* +jalv_frontend_select_plugin(Jalv* jalv) +{ + (void)jalv; + return NULL; } int -jalv_open_ui(Jalv* jalv) +jalv_frontend_open(Jalv* jalv) { - if (!jalv_run_custom_ui(jalv) && !jalv->opts.non_interactive) { - // Primitive command prompt for setting control values - while (!zix_sem_try_wait(&jalv->done)) { - char line[128]; - printf("> "); - if (fgets(line, sizeof(line), stdin)) { - jalv_process_command(jalv, line); - } else { - break; - } - } - } else { - zix_sem_wait(&jalv->done); - } - - // Caller waits on the done sem, so increment it again to exit - zix_sem_post(&jalv->done); - - return 0; + // Print initial control values + for (size_t i = 0; i < jalv->controls.n_controls; ++i) { + ControlID* control = jalv->controls.controls[i]; + if (control->type == PORT && control->is_writable) { + const JalvPort* const port = &jalv->ports[control->id.index]; + print_control_port( + jalv, port, jalv->process.controls_buf[control->id.index]); + } + } + + if (!jalv_run_custom_ui(jalv) && !jalv->opts.non_interactive) { + // Primitive command prompt for setting control values + while (zix_sem_try_wait(&jalv->done)) { + char line[1024]; + printf("> "); + if (fgets(line, sizeof(line), stdin)) { + jalv_process_command(jalv, line); + } else { + break; + } + } + } else { + zix_sem_wait(&jalv->done); + } + + // Caller waits on the done sem, so increment it again to exit + zix_sem_post(&jalv->done); + + return 0; } int -jalv_close_ui(Jalv* jalv) +jalv_frontend_close(Jalv* jalv) { - zix_sem_post(&jalv->done); - return 0; + zix_sem_post(&jalv->done); + return 0; } diff --git a/src/jalv_gtk.c b/src/jalv_gtk.c index 71259bd..16cff34 100644 --- a/src/jalv_gtk.c +++ b/src/jalv_gtk.c @@ -1,296 +1,377 @@ -/* - Copyright 2007-2017 David Robillard <http://drobilla.net> - - Permission to use, copy, modify, and/or distribute this software for any - purpose with or without fee is hereby granted, provided that the above - copyright notice and this permission notice appear in all copies. - - THIS SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES - WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF - MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR - ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES - WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN - ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF - OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. -*/ - -#include "jalv_internal.h" - -#include "lv2/core/attributes.h" -#include "lv2/patch/patch.h" -#include "lv2/port-props/port-props.h" - -LV2_DISABLE_DEPRECATION_WARNINGS - +// Copyright 2007-2022 David Robillard <d@drobilla.net> +// SPDX-License-Identifier: ISC + +#include "control.h" +#include "frontend.h" +#include "jalv.h" +#include "log.h" +#include "options.h" +#include "query.h" +#include "state.h" +#include "types.h" + +#include <lilv/lilv.h> +#include <lv2/atom/atom.h> +#include <lv2/atom/forge.h> +#include <lv2/atom/util.h> +#include <lv2/core/lv2.h> +#include <lv2/ui/ui.h> +#include <lv2/urid/urid.h> +#include <suil/suil.h> +#include <zix/attributes.h> +#include <zix/sem.h> + +#include <gdk/gdk.h> +#include <glib-object.h> +#include <glib.h> +#include <gobject/gclosure.h> #include <gtk/gtk.h> +#include <float.h> #include <math.h> +#include <stdbool.h> +#include <stdint.h> +#include <stdio.h> +#include <stdlib.h> +#include <string.h> + +/* TODO: Gtk only provides one pointer for value changed callbacks, which we + use for the ControlID. So, there is no easy way to pass both a ControlID + and Jalv which is needed to actually do anything with a control. Work + around this by statically storing the Jalv instance. Since this UI isn't a + module, this isn't the end of the world, but a global "god pointer" is a + pretty bad smell. Refactoring things to be more modular or changing how Gtk + signals are connected would be a good idea. +*/ +static Jalv* s_jalv = NULL; static GtkCheckMenuItem* active_preset_item = NULL; static bool updating = false; -/** Widget for a control. */ +/// Widget(s) for a control port or parameter typedef struct { - GtkSpinButton* spin; - GtkWidget* control; + GtkSpinButton* spin; ///< Spinner for numbers, or null + GtkWidget* control; ///< Primary value control } Controller; static float get_float(const LilvNode* node, float fallback) { - if (lilv_node_is_float(node) || lilv_node_is_int(node)) { - return lilv_node_as_float(node); - } - - return fallback; -} - -static GtkWidget* -new_box(gboolean horizontal, gint spacing) -{ - #if GTK_MAJOR_VERSION == 3 - return gtk_box_new( - horizontal ? GTK_ORIENTATION_HORIZONTAL : GTK_ORIENTATION_VERTICAL, - spacing); - #else - return (horizontal - ? gtk_hbox_new(FALSE, spacing) - : gtk_vbox_new(FALSE, spacing)); - #endif -} - -static GtkWidget* -new_hscale(gdouble min, gdouble max, gdouble step) -{ - #if GTK_MAJOR_VERSION == 3 - return gtk_scale_new_with_range(GTK_ORIENTATION_HORIZONTAL, min, max, step); - #else - return gtk_hscale_new_with_range(min, max, step); - #endif + return (lilv_node_is_float(node) || lilv_node_is_int(node)) + ? lilv_node_as_float(node) + : fallback; } static void -size_request(GtkWidget* widget, GtkRequisition* req) +on_window_destroy(GtkWidget* widget, gpointer data) { - #if GTK_MAJOR_VERSION == 3 - gtk_widget_get_preferred_size(widget, NULL, req); - #else - gtk_widget_size_request(widget, req); - #endif -} - -static void -on_window_destroy(ZIX_UNUSED GtkWidget* widget, ZIX_UNUSED gpointer data) -{ - gtk_main_quit(); + (void)widget; + (void)data; + gtk_main_quit(); } int -jalv_init(int* argc, char*** argv, JalvOptions* opts) +jalv_frontend_init(JalvFrontendArgs* const args, JalvOptions* const opts) { - GOptionEntry entries[] = { - { "uuid", 'u', 0, G_OPTION_ARG_STRING, &opts->uuid, - "UUID for Jack session restoration", "UUID" }, - { "load", 'l', 0, G_OPTION_ARG_STRING, &opts->load, - "Load state from save directory", "DIR" }, - { "preset", 'p', 0, G_OPTION_ARG_STRING, &opts->preset, - "Load state from preset", "URI" }, - { "dump", 'd', 0, G_OPTION_ARG_NONE, &opts->dump, - "Dump plugin <=> UI communication", NULL }, - { "trace", 't', 0, G_OPTION_ARG_NONE, &opts->trace, - "Print trace messages from plugin", NULL }, - { "show-hidden", 's', 0, G_OPTION_ARG_NONE, &opts->show_hidden, - "Show controls for ports with notOnGUI property on generic UI", NULL }, - { "no-menu", 'n', 0, G_OPTION_ARG_NONE, &opts->no_menu, - "Do not show Jalv menu on window", NULL }, - { "generic-ui", 'g', 0, G_OPTION_ARG_NONE, &opts->generic_ui, - "Use Jalv generic UI and not the plugin UI", NULL}, - { "buffer-size", 'b', 0, G_OPTION_ARG_INT, &opts->buffer_size, - "Buffer size for plugin <=> UI communication", "SIZE"}, - { "update-frequency", 'r', 0, G_OPTION_ARG_DOUBLE, &opts->update_rate, - "UI update frequency", NULL}, - { "control", 'c', 0, G_OPTION_ARG_STRING_ARRAY, &opts->controls, - "Set control value (e.g. \"vol=1.4\")", NULL}, - { "print-controls", 'p', 0, G_OPTION_ARG_NONE, &opts->print_controls, - "Print control output changes to stdout", NULL}, - { "jack-name", 'n', 0, G_OPTION_ARG_STRING, &opts->name, - "JACK client name", NULL}, - { "exact-jack-name", 'x', 0, G_OPTION_ARG_NONE, &opts->name_exact, - "Exact JACK client name (exit if taken)", NULL }, - { 0, 0, 0, G_OPTION_ARG_NONE, 0, 0, 0 } }; - GError* error = NULL; - const int err = gtk_init_with_args( - argc, argv, - "PLUGIN_URI - Run an LV2 plugin as a Jack application", - entries, NULL, &error); - - if (!err) { - fprintf(stderr, "%s\n", error->message); - } - - return !err; + const GOptionEntry entries[] = { + {"preset", + 'P', + 0, + G_OPTION_ARG_STRING, + &opts->preset, + "Load state from preset", + "URI"}, + {"scale-factor", + 'S', + 0, + G_OPTION_ARG_DOUBLE, + &opts->scale_factor, + "UI scale factor", + "SCALE"}, + {"ui-uri", + 'U', + 0, + G_OPTION_ARG_STRING, + &opts->ui_uri, + "Load the UI with the given URI", + "URI"}, + {"buffer-size", + 'b', + 0, + G_OPTION_ARG_INT, + &opts->ring_size, + "Buffer size for plugin <=> UI communication", + "SIZE"}, + {"control", + 'c', + 0, + G_OPTION_ARG_STRING_ARRAY, + &opts->controls, + "Set control value (e.g. \"vol=1.4\")", + "SETTING"}, + {"dump", + 'd', + 0, + G_OPTION_ARG_NONE, + &opts->dump, + "Dump plugin <=> UI communication", + NULL}, + {"generic-ui", + 'g', + 0, + G_OPTION_ARG_NONE, + &opts->generic_ui, + "Use Jalv generic UI and not the plugin UI", + NULL}, + {"load", + 'l', + 0, + G_OPTION_ARG_STRING, + &opts->load, + "Load state from save directory", + "DIR"}, + {"no-menu", + 'm', + 0, + G_OPTION_ARG_NONE, + &opts->no_menu, + "Do not show Jalv menu on window", + NULL}, + {"jack-name", + 'n', + 0, + G_OPTION_ARG_STRING, + &opts->name, + "JACK client name", + "NAME"}, + {"print-controls", + 'p', + 0, + G_OPTION_ARG_NONE, + &opts->print_controls, + "Print control output changes to stdout", + NULL}, + {"update-frequency", + 'r', + 0, + G_OPTION_ARG_DOUBLE, + &opts->update_rate, + "UI update frequency", + "HZ"}, + {"show-hidden", + 's', + 0, + G_OPTION_ARG_NONE, + &opts->show_hidden, + "Show controls for ports with notOnGUI property on generic UI", + NULL}, + {"trace", + 't', + 0, + G_OPTION_ARG_NONE, + &opts->trace, + "Print trace messages from plugin", + NULL}, + {"exact-jack-name", + 'x', + 0, + G_OPTION_ARG_NONE, + &opts->name_exact, + "Exit if the requested JACK client name is taken", + NULL}, + {0, 0, 0, G_OPTION_ARG_NONE, 0, 0, 0}}; + + GError* error = NULL; + const int err = + gtk_init_with_args(args->argc, + args->argv, + "PLUGIN_URI - Run an LV2 plugin as a Jack application", + entries, + NULL, + &error); + + if (!err) { + fprintf(stderr, "%s\n", error->message); + } + + --*args->argc; + ++*args->argv; + return !err; } const char* -jalv_native_ui_type(void) +jalv_frontend_ui_type(void) { -#if GTK_MAJOR_VERSION == 2 - return "http://lv2plug.in/ns/extensions/ui#GtkUI"; -#elif GTK_MAJOR_VERSION == 3 - return "http://lv2plug.in/ns/extensions/ui#Gtk3UI"; +#if GTK_MAJOR_VERSION == 3 + return "http://lv2plug.in/ns/extensions/ui#Gtk3UI"; #else - return NULL; + return NULL; #endif } static void -on_save_activate(ZIX_UNUSED GtkWidget* widget, void* ptr) +on_save_activate(GtkWidget* ZIX_UNUSED(widget), void* ptr) { - Jalv* jalv = (Jalv*)ptr; - GtkWidget* dialog = gtk_file_chooser_dialog_new( - "Save State", - (GtkWindow*)jalv->window, - GTK_FILE_CHOOSER_ACTION_CREATE_FOLDER, - "_Cancel", GTK_RESPONSE_CANCEL, - "_Save", GTK_RESPONSE_ACCEPT, - NULL); - - if (gtk_dialog_run(GTK_DIALOG(dialog)) == GTK_RESPONSE_ACCEPT) { - char* path = gtk_file_chooser_get_filename(GTK_FILE_CHOOSER(dialog)); - char* base = g_build_filename(path, "/", NULL); - jalv_save(jalv, base); - g_free(path); - g_free(base); - } - - gtk_widget_destroy(dialog); + Jalv* jalv = (Jalv*)ptr; + GtkWidget* dialog = + gtk_file_chooser_dialog_new("Save State", + (GtkWindow*)jalv->window, + GTK_FILE_CHOOSER_ACTION_CREATE_FOLDER, + "_Cancel", + GTK_RESPONSE_CANCEL, + "_Save", + GTK_RESPONSE_ACCEPT, + NULL); + + if (gtk_dialog_run(GTK_DIALOG(dialog)) == GTK_RESPONSE_ACCEPT) { + char* path = gtk_file_chooser_get_filename(GTK_FILE_CHOOSER(dialog)); + char* base = g_build_filename(path, "/", NULL); + jalv_save(jalv, base); + g_free(path); + g_free(base); + } + + gtk_widget_destroy(dialog); } static void -on_quit_activate(ZIX_UNUSED GtkWidget* widget, gpointer data) +on_quit_activate(GtkWidget* ZIX_UNUSED(widget), gpointer data) { - GtkWidget* window = (GtkWidget*)data; - gtk_widget_destroy(window); + GtkWidget* window = (GtkWidget*)data; + gtk_widget_destroy(window); } typedef struct { - Jalv* jalv; - LilvNode* preset; + Jalv* jalv; + LilvNode* preset; } PresetRecord; static char* symbolify(const char* in) { - const size_t len = strlen(in); - char* out = (char*)calloc(len + 1, 1); - for (size_t i = 0; i < len; ++i) { - if (g_ascii_isalnum(in[i])) { - out[i] = in[i]; - } else { - out[i] = '_'; - } - } - return out; + const size_t len = strlen(in); + char* out = (char*)calloc(len + 1, 1); + for (size_t i = 0; i < len; ++i) { + if (g_ascii_isalnum(in[i])) { + out[i] = in[i]; + } else { + out[i] = '_'; + } + } + return out; } static void set_window_title(Jalv* jalv) { - LilvNode* name = lilv_plugin_get_name(jalv->plugin); - const char* plugin = lilv_node_as_string(name); - if (jalv->preset) { - const char* preset_label = lilv_state_get_label(jalv->preset); - char* title = g_strdup_printf("%s - %s", plugin, preset_label); - gtk_window_set_title(GTK_WINDOW(jalv->window), title); - free(title); - } else { - gtk_window_set_title(GTK_WINDOW(jalv->window), plugin); - } - lilv_node_free(name); + LilvNode* name = lilv_plugin_get_name(jalv->plugin); + const char* plugin = lilv_node_as_string(name); + if (jalv->preset) { + const char* preset_label = lilv_state_get_label(jalv->preset); + char* title = g_strdup_printf("%s - %s", plugin, preset_label); + gtk_window_set_title(GTK_WINDOW(jalv->window), title); + free(title); + } else { + gtk_window_set_title(GTK_WINDOW(jalv->window), plugin); + } + lilv_node_free(name); } static void on_preset_activate(GtkWidget* widget, gpointer data) { - if (GTK_CHECK_MENU_ITEM(widget) != active_preset_item) { - PresetRecord* record = (PresetRecord*)data; - jalv_apply_preset(record->jalv, record->preset); - if (active_preset_item) { - gtk_check_menu_item_set_active(active_preset_item, FALSE); - } - - active_preset_item = GTK_CHECK_MENU_ITEM(widget); - gtk_check_menu_item_set_active(active_preset_item, TRUE); - set_window_title(record->jalv); - } + if (GTK_CHECK_MENU_ITEM(widget) != active_preset_item) { + PresetRecord* record = (PresetRecord*)data; + jalv_apply_preset(record->jalv, record->preset); + if (active_preset_item) { + gtk_check_menu_item_set_active(active_preset_item, FALSE); + } + + active_preset_item = GTK_CHECK_MENU_ITEM(widget); + gtk_check_menu_item_set_active(active_preset_item, TRUE); + set_window_title(record->jalv); + } } static void -on_preset_destroy(gpointer data, ZIX_UNUSED GClosure* closure) +on_preset_destroy(gpointer data, GClosure* ZIX_UNUSED(closure)) { - PresetRecord* record = (PresetRecord*)data; - lilv_node_free(record->preset); - free(record); + PresetRecord* record = (PresetRecord*)data; + lilv_node_free(record->preset); + free(record); } typedef struct { - GtkMenuItem* item; - char* label; - GtkMenu* menu; - GSequence* banks; + GtkMenuItem* item; + char* label; + GtkMenu* menu; + GSequence* banks; } PresetMenu; static PresetMenu* -pset_menu_new(const char* label) +pset_menu_new(char* const label) { - PresetMenu* menu = (PresetMenu*)malloc(sizeof(PresetMenu)); - menu->label = g_strdup(label); - menu->item = GTK_MENU_ITEM(gtk_menu_item_new_with_label(menu->label)); - menu->menu = GTK_MENU(gtk_menu_new()); - menu->banks = NULL; - return menu; + PresetMenu* menu = (PresetMenu*)malloc(sizeof(PresetMenu)); + menu->label = label; + menu->item = GTK_MENU_ITEM(gtk_menu_item_new_with_label(menu->label)); + menu->menu = GTK_MENU(gtk_menu_new()); + menu->banks = NULL; + return menu; } static void pset_menu_free(PresetMenu* menu) { - if (menu->banks) { - for (GSequenceIter* i = g_sequence_get_begin_iter(menu->banks); - !g_sequence_iter_is_end(i); - i = g_sequence_iter_next(i)) { - PresetMenu* bank_menu = (PresetMenu*)g_sequence_get(i); - pset_menu_free(bank_menu); - } - g_sequence_free(menu->banks); - } - - free(menu->label); - free(menu); + if (menu->banks) { + for (GSequenceIter* i = g_sequence_get_begin_iter(menu->banks); + !g_sequence_iter_is_end(i); + i = g_sequence_iter_next(i)) { + PresetMenu* bank_menu = (PresetMenu*)g_sequence_get(i); + pset_menu_free(bank_menu); + } + g_sequence_free(menu->banks); + } + + free(menu->label); + free(menu); } static gint -menu_cmp(gconstpointer a, gconstpointer b, ZIX_UNUSED gpointer data) +menu_cmp(gconstpointer a, gconstpointer b, gpointer ZIX_UNUSED(data)) +{ + return strcmp(((const PresetMenu*)a)->label, ((const PresetMenu*)b)->label); +} + +static char* +get_label_string(Jalv* const jalv, const LilvNode* const node) { - return strcmp(((const PresetMenu*)a)->label, ((const PresetMenu*)b)->label); + LilvNode* const label_node = + lilv_world_get(jalv->world, node, jalv->nodes.rdfs_label, NULL); + + if (!label_node) { + return g_strdup(lilv_node_as_string(node)); + } + + char* const label = g_strdup(lilv_node_as_string(label_node)); + lilv_node_free(label_node); + return label; } static PresetMenu* get_bank_menu(Jalv* jalv, PresetMenu* menu, const LilvNode* bank) { - LilvNode* label = lilv_world_get( - jalv->world, bank, jalv->nodes.rdfs_label, NULL); - - const char* uri = lilv_node_as_string(bank); - const char* str = label ? lilv_node_as_string(label) : uri; - PresetMenu key = { NULL, (char*)str, NULL, NULL }; - GSequenceIter* i = g_sequence_lookup(menu->banks, &key, menu_cmp, NULL); - if (!i) { - PresetMenu* bank_menu = pset_menu_new(str); - gtk_menu_item_set_submenu(bank_menu->item, GTK_WIDGET(bank_menu->menu)); - g_sequence_insert_sorted(menu->banks, bank_menu, menu_cmp, NULL); - return bank_menu; - } - return (PresetMenu*)g_sequence_get(i); + char* const label = get_label_string(jalv, bank); + PresetMenu key = {NULL, label, NULL, NULL}; + GSequenceIter* i = g_sequence_lookup(menu->banks, &key, menu_cmp, NULL); + if (!i) { + PresetMenu* const bank_menu = pset_menu_new(label); + gtk_menu_item_set_submenu(bank_menu->item, GTK_WIDGET(bank_menu->menu)); + g_sequence_insert_sorted(menu->banks, bank_menu, menu_cmp, NULL); + return bank_menu; + } + + g_free(label); + return (PresetMenu*)g_sequence_get(i); } static int @@ -299,185 +380,190 @@ add_preset_to_menu(Jalv* jalv, const LilvNode* title, void* data) { - PresetMenu* menu = (PresetMenu*)data; - const char* label = lilv_node_as_string(title); - GtkWidget* item = gtk_check_menu_item_new_with_label(label); - gtk_check_menu_item_set_draw_as_radio(GTK_CHECK_MENU_ITEM(item), TRUE); - if (jalv->preset && - lilv_node_equals(lilv_state_get_uri(jalv->preset), node)) { - gtk_check_menu_item_set_active(GTK_CHECK_MENU_ITEM(item), TRUE); - active_preset_item = GTK_CHECK_MENU_ITEM(item); - } - - LilvNode* bank = lilv_world_get( - jalv->world, node, jalv->nodes.pset_bank, NULL); - - if (bank) { - PresetMenu* bank_menu = get_bank_menu(jalv, menu, bank); - gtk_menu_shell_append(GTK_MENU_SHELL(bank_menu->menu), item); - } else { - gtk_menu_shell_append(GTK_MENU_SHELL(menu->menu), item); - } - - PresetRecord* record = (PresetRecord*)malloc(sizeof(PresetRecord)); - record->jalv = jalv; - record->preset = lilv_node_duplicate(node); - - g_signal_connect_data(G_OBJECT(item), "activate", - G_CALLBACK(on_preset_activate), - record, on_preset_destroy, - (GConnectFlags)0); - - return 0; + PresetMenu* menu = (PresetMenu*)data; + const char* label = lilv_node_as_string(title); + GtkWidget* item = gtk_check_menu_item_new_with_label(label); + gtk_check_menu_item_set_draw_as_radio(GTK_CHECK_MENU_ITEM(item), TRUE); + if (jalv->preset && + lilv_node_equals(lilv_state_get_uri(jalv->preset), node)) { + gtk_check_menu_item_set_active(GTK_CHECK_MENU_ITEM(item), TRUE); + active_preset_item = GTK_CHECK_MENU_ITEM(item); + } + + const LilvNode* bank = + lilv_world_get(jalv->world, node, jalv->nodes.pset_bank, NULL); + + if (bank) { + PresetMenu* bank_menu = get_bank_menu(jalv, menu, bank); + gtk_menu_shell_append(GTK_MENU_SHELL(bank_menu->menu), item); + } else { + gtk_menu_shell_append(GTK_MENU_SHELL(menu->menu), item); + } + + PresetRecord* record = (PresetRecord*)malloc(sizeof(PresetRecord)); + record->jalv = jalv; + record->preset = lilv_node_duplicate(node); + + g_signal_connect_data(G_OBJECT(item), + "activate", + G_CALLBACK(on_preset_activate), + record, + on_preset_destroy, + (GConnectFlags)0); + + return 0; } static void finish_menu(PresetMenu* menu) { - for (GSequenceIter* i = g_sequence_get_begin_iter(menu->banks); - !g_sequence_iter_is_end(i); - i = g_sequence_iter_next(i)) { - PresetMenu* bank_menu = (PresetMenu*)g_sequence_get(i); - gtk_menu_shell_append(GTK_MENU_SHELL(menu->menu), - GTK_WIDGET(bank_menu->item)); - } - g_sequence_free(menu->banks); + for (GSequenceIter* i = g_sequence_get_begin_iter(menu->banks); + !g_sequence_iter_is_end(i); + i = g_sequence_iter_next(i)) { + PresetMenu* bank_menu = (PresetMenu*)g_sequence_get(i); + gtk_menu_shell_append(GTK_MENU_SHELL(menu->menu), + GTK_WIDGET(bank_menu->item)); + } + g_sequence_free(menu->banks); } static void rebuild_preset_menu(Jalv* jalv, GtkContainer* pset_menu) { - // Clear current menu - active_preset_item = NULL; - for (GList* items = g_list_nth(gtk_container_get_children(pset_menu), 3); - items; - items = items->next) { - gtk_container_remove(pset_menu, GTK_WIDGET(items->data)); - } - - // Load presets and build new menu - PresetMenu menu = { - NULL, NULL, GTK_MENU(pset_menu), - g_sequence_new((GDestroyNotify)pset_menu_free) - }; - jalv_load_presets(jalv, add_preset_to_menu, &menu); - finish_menu(&menu); - gtk_widget_show_all(GTK_WIDGET(pset_menu)); + // Clear current menu + active_preset_item = NULL; + for (GList* items = g_list_nth(gtk_container_get_children(pset_menu), 3); + items; + items = items->next) { + gtk_container_remove(pset_menu, GTK_WIDGET(items->data)); + } + + // Load presets and build new menu + PresetMenu menu = {NULL, + NULL, + GTK_MENU(pset_menu), + g_sequence_new((GDestroyNotify)pset_menu_free)}; + jalv_load_presets(jalv, add_preset_to_menu, &menu); + finish_menu(&menu); + gtk_widget_show_all(GTK_WIDGET(pset_menu)); } static void on_save_preset_activate(GtkWidget* widget, void* ptr) { - Jalv* jalv = (Jalv*)ptr; - - GtkWidget* dialog = gtk_file_chooser_dialog_new( - "Save Preset", - (GtkWindow*)jalv->window, - GTK_FILE_CHOOSER_ACTION_SAVE, - "_Cancel", GTK_RESPONSE_REJECT, - "_Save", GTK_RESPONSE_ACCEPT, - NULL); - - char* dot_lv2 = g_build_filename(g_get_home_dir(), ".lv2", NULL); - gtk_file_chooser_set_current_folder(GTK_FILE_CHOOSER(dialog), dot_lv2); - free(dot_lv2); - - GtkWidget* content = gtk_dialog_get_content_area(GTK_DIALOG(dialog)); - GtkBox* box = GTK_BOX(new_box(true, 8)); - GtkWidget* uri_label = gtk_label_new("URI (Optional):"); - GtkWidget* uri_entry = gtk_entry_new(); - GtkWidget* add_prefix = gtk_check_button_new_with_mnemonic( - "_Prefix plugin name"); - - gtk_toggle_button_set_active(GTK_TOGGLE_BUTTON(add_prefix), TRUE); - gtk_box_pack_start(box, uri_label, FALSE, TRUE, 2); - gtk_box_pack_start(box, uri_entry, TRUE, TRUE, 2); - gtk_box_pack_start(GTK_BOX(content), GTK_WIDGET(box), FALSE, FALSE, 6); - gtk_box_pack_start(GTK_BOX(content), add_prefix, FALSE, FALSE, 6); - - gtk_widget_show_all(GTK_WIDGET(dialog)); - gtk_entry_set_activates_default(GTK_ENTRY(uri_entry), TRUE); - gtk_dialog_set_default_response(GTK_DIALOG(dialog), GTK_RESPONSE_ACCEPT); - if (gtk_dialog_run(GTK_DIALOG(dialog)) == GTK_RESPONSE_ACCEPT) { - LilvNode* plug_name = lilv_plugin_get_name(jalv->plugin); - const char* path = gtk_file_chooser_get_filename(GTK_FILE_CHOOSER(dialog)); - const char* uri = gtk_entry_get_text(GTK_ENTRY(uri_entry)); - const char* prefix = ""; - const char* sep = ""; - if (gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON(add_prefix))) { - prefix = lilv_node_as_string(plug_name); - sep = "_"; - } - - char* dirname = g_path_get_dirname(path); - char* basename = g_path_get_basename(path); - char* sym = symbolify(basename); - char* sprefix = symbolify(prefix); - char* bundle = g_strjoin(NULL, sprefix, sep, sym, ".preset.lv2/", NULL); - char* file = g_strjoin(NULL, sym, ".ttl", NULL); - char* dir = g_build_filename(dirname, bundle, NULL); - - jalv_save_preset(jalv, dir, (strlen(uri) ? uri : NULL), basename, file); - - // Reload bundle into the world - LilvNode* ldir = lilv_new_file_uri(jalv->world, NULL, dir); - lilv_world_unload_bundle(jalv->world, ldir); - lilv_world_load_bundle(jalv->world, ldir); - lilv_node_free(ldir); - - // Rebuild preset menu and update window title - rebuild_preset_menu(jalv, GTK_CONTAINER(gtk_widget_get_parent(widget))); - set_window_title(jalv); - - g_free(dir); - g_free(file); - g_free(bundle); - free(sprefix); - free(sym); - g_free(basename); - g_free(dirname); - lilv_node_free(plug_name); - } - - gtk_widget_destroy(GTK_WIDGET(dialog)); + Jalv* jalv = (Jalv*)ptr; + + GtkWidget* dialog = gtk_file_chooser_dialog_new("Save Preset", + (GtkWindow*)jalv->window, + GTK_FILE_CHOOSER_ACTION_SAVE, + "_Cancel", + GTK_RESPONSE_REJECT, + "_Save", + GTK_RESPONSE_ACCEPT, + NULL); + + char* dot_lv2 = g_build_filename(g_get_home_dir(), ".lv2", NULL); + gtk_file_chooser_set_current_folder(GTK_FILE_CHOOSER(dialog), dot_lv2); + free(dot_lv2); + + GtkWidget* content = gtk_dialog_get_content_area(GTK_DIALOG(dialog)); + GtkBox* box = GTK_BOX(gtk_box_new(GTK_ORIENTATION_HORIZONTAL, 8)); + GtkWidget* uri_label = gtk_label_new("URI (Optional):"); + GtkWidget* uri_entry = gtk_entry_new(); + GtkWidget* add_prefix = + gtk_check_button_new_with_mnemonic("_Prefix plugin name"); + + gtk_toggle_button_set_active(GTK_TOGGLE_BUTTON(add_prefix), TRUE); + gtk_box_pack_start(box, uri_label, FALSE, TRUE, 2); + gtk_box_pack_start(box, uri_entry, TRUE, TRUE, 2); + gtk_box_pack_start(GTK_BOX(content), GTK_WIDGET(box), FALSE, FALSE, 6); + gtk_box_pack_start(GTK_BOX(content), add_prefix, FALSE, FALSE, 6); + + gtk_widget_show_all(GTK_WIDGET(dialog)); + gtk_entry_set_activates_default(GTK_ENTRY(uri_entry), TRUE); + gtk_dialog_set_default_response(GTK_DIALOG(dialog), GTK_RESPONSE_ACCEPT); + if (gtk_dialog_run(GTK_DIALOG(dialog)) == GTK_RESPONSE_ACCEPT) { + LilvNode* plug_name = lilv_plugin_get_name(jalv->plugin); + const char* path = gtk_file_chooser_get_filename(GTK_FILE_CHOOSER(dialog)); + const char* uri = gtk_entry_get_text(GTK_ENTRY(uri_entry)); + const char* prefix = ""; + const char* sep = ""; + if (gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON(add_prefix))) { + prefix = lilv_node_as_string(plug_name); + sep = "_"; + } + + char* dirname = g_path_get_dirname(path); + char* basename = g_path_get_basename(path); + char* sym = symbolify(basename); + char* sprefix = symbolify(prefix); + char* bundle = g_strjoin(NULL, sprefix, sep, sym, ".preset.lv2/", NULL); + char* file = g_strjoin(NULL, sym, ".ttl", NULL); + char* dir = g_build_filename(dirname, bundle, NULL); + + jalv_save_preset(jalv, dir, (strlen(uri) ? uri : NULL), basename, file); + + // Reload bundle into the world + LilvNode* ldir = lilv_new_file_uri(jalv->world, NULL, dir); + lilv_world_unload_bundle(jalv->world, ldir); + lilv_world_load_bundle(jalv->world, ldir); + lilv_node_free(ldir); + + // Rebuild preset menu and update window title + rebuild_preset_menu(jalv, GTK_CONTAINER(gtk_widget_get_parent(widget))); + set_window_title(jalv); + + g_free(dir); + g_free(file); + g_free(bundle); + free(sprefix); + free(sym); + g_free(basename); + g_free(dirname); + lilv_node_free(plug_name); + } + + gtk_widget_destroy(GTK_WIDGET(dialog)); } static void on_delete_preset_activate(GtkWidget* widget, void* ptr) { - Jalv* jalv = (Jalv*)ptr; - if (!jalv->preset) { - return; - } - - GtkWidget* dialog = gtk_dialog_new_with_buttons( - "Delete Preset?", - (GtkWindow*)jalv->window, - (GtkDialogFlags)(GTK_DIALOG_MODAL | GTK_DIALOG_DESTROY_WITH_PARENT), - "_Cancel", GTK_RESPONSE_REJECT, - "_OK", GTK_RESPONSE_ACCEPT, - NULL); - - char* msg = g_strdup_printf("Delete preset \"%s\" from the file system?", - lilv_state_get_label(jalv->preset)); - - GtkWidget* content = gtk_dialog_get_content_area(GTK_DIALOG(dialog)); - GtkWidget* text = gtk_label_new(msg); - gtk_box_pack_start(GTK_BOX(content), text, TRUE, TRUE, 4); - - gtk_widget_show_all(dialog); - if (gtk_dialog_run(GTK_DIALOG(dialog)) == GTK_RESPONSE_ACCEPT) { - jalv_delete_current_preset(jalv); - rebuild_preset_menu(jalv, GTK_CONTAINER(gtk_widget_get_parent(widget))); - } - - lilv_state_free(jalv->preset); - jalv->preset = NULL; - set_window_title(jalv); - - g_free(msg); - gtk_widget_destroy(text); - gtk_widget_destroy(dialog); + Jalv* jalv = (Jalv*)ptr; + if (!jalv->preset) { + return; + } + + GtkWidget* dialog = gtk_dialog_new_with_buttons( + "Delete Preset?", + (GtkWindow*)jalv->window, + (GtkDialogFlags)(GTK_DIALOG_MODAL | GTK_DIALOG_DESTROY_WITH_PARENT), + "_Cancel", + GTK_RESPONSE_CANCEL, + "_OK", + GTK_RESPONSE_ACCEPT, + NULL); + + char* msg = g_strdup_printf("Delete preset \"%s\" from the file system?", + lilv_state_get_label(jalv->preset)); + + GtkWidget* content = gtk_dialog_get_content_area(GTK_DIALOG(dialog)); + GtkWidget* text = gtk_label_new(msg); + gtk_box_pack_start(GTK_BOX(content), text, TRUE, TRUE, 4); + + gtk_widget_show_all(dialog); + if (gtk_dialog_run(GTK_DIALOG(dialog)) == GTK_RESPONSE_ACCEPT) { + jalv_delete_current_preset(jalv); + rebuild_preset_menu(jalv, GTK_CONTAINER(gtk_widget_get_parent(widget))); + } + + lilv_state_free(jalv->preset); + jalv->preset = NULL; + set_window_title(jalv); + + g_free(msg); + gtk_widget_destroy(text); + gtk_widget_destroy(dialog); } static void @@ -486,108 +572,116 @@ set_control(const ControlID* control, LV2_URID type, const void* body) { - if (!updating) { - jalv_set_control(control, size, type, body); - } + if (!updating) { + jalv_set_control(s_jalv, control, size, type, body); + } } static bool differ_enough(float a, float b) { - return fabsf(a - b) >= FLT_EPSILON; + return fabsf(a - b) >= FLT_EPSILON; } static void set_float_control(const ControlID* control, float value) { - if (control->value_type == control->jalv->forge.Int) { - const int32_t ival = lrint(value); - set_control(control, sizeof(ival), control->jalv->forge.Int, &ival); - } else if (control->value_type == control->jalv->forge.Long) { - const int64_t lval = lrint(value); - set_control(control, sizeof(lval), control->jalv->forge.Long, &lval); - } else if (control->value_type == control->jalv->forge.Float) { - set_control(control, sizeof(value), control->jalv->forge.Float, &value); - } else if (control->value_type == control->jalv->forge.Double) { - const double dval = value; - set_control(control, sizeof(dval), control->jalv->forge.Double, &dval); - } else if (control->value_type == control->jalv->forge.Bool) { - const int32_t ival = value; - set_control(control, sizeof(ival), control->jalv->forge.Bool, &ival); - } - - Controller* controller = (Controller*)control->widget; - if (controller && controller->spin && - differ_enough(gtk_spin_button_get_value(controller->spin), value)) { - gtk_spin_button_set_value(controller->spin, value); - } + const LV2_Atom_Forge* const forge = &s_jalv->forge; + if (control->value_type == forge->Int) { + const int32_t ival = lrintf(value); + set_control(control, sizeof(ival), forge->Int, &ival); + } else if (control->value_type == forge->Long) { + const int64_t lval = lrintf(value); + set_control(control, sizeof(lval), forge->Long, &lval); + } else if (control->value_type == forge->Float) { + set_control(control, sizeof(value), forge->Float, &value); + } else if (control->value_type == forge->Double) { + const double dval = value; + set_control(control, sizeof(dval), forge->Double, &dval); + } else if (control->value_type == forge->Bool) { + const int32_t ival = value; + set_control(control, sizeof(ival), forge->Bool, &ival); + } + + Controller* controller = (Controller*)control->widget; + if (controller && controller->spin && + differ_enough(gtk_spin_button_get_value(controller->spin), value)) { + gtk_spin_button_set_value(controller->spin, value); + } } static double -get_atom_double(Jalv* jalv, - ZIX_UNUSED uint32_t size, - LV2_URID type, - const void* body) +get_atom_double(const Jalv* jalv, + uint32_t ZIX_UNUSED(size), + LV2_URID type, + const void* body) { - if (type == jalv->forge.Int || type == jalv->forge.Bool) { - return *(const int32_t*)body; - } else if (type == jalv->forge.Long) { - return *(const int64_t*)body; - } else if (type == jalv->forge.Float) { - return *(const float*)body; - } else if (type == jalv->forge.Double) { - return *(const double*)body; - } - return NAN; + if (type == jalv->forge.Int || type == jalv->forge.Bool) { + return *(const int32_t*)body; + } + + if (type == jalv->forge.Long) { + return *(const int64_t*)body; + } + + if (type == jalv->forge.Float) { + return *(const float*)body; + } + + if (type == jalv->forge.Double) { + return *(const double*)body; + } + + return NAN; } static void -control_changed(Jalv* jalv, +control_changed(const Jalv* jalv, Controller* controller, uint32_t size, LV2_URID type, const void* body) { - GtkWidget* widget = controller->control; - const double fvalue = get_atom_double(jalv, size, type, body); - - if (!isnan(fvalue)) { - if (GTK_IS_COMBO_BOX(widget)) { - GtkTreeModel* model = gtk_combo_box_get_model(GTK_COMBO_BOX(widget)); - GValue value = { 0, { { 0 } } }; - GtkTreeIter i; - bool valid = gtk_tree_model_get_iter_first(model, &i); - while (valid) { - gtk_tree_model_get_value(model, &i, 0, &value); - const double v = g_value_get_float(&value); - g_value_unset(&value); - if (fabs(v - fvalue) < FLT_EPSILON) { - gtk_combo_box_set_active_iter(GTK_COMBO_BOX(widget), &i); - return; - } - valid = gtk_tree_model_iter_next(model, &i); - } - } else if (GTK_IS_TOGGLE_BUTTON(widget)) { - gtk_toggle_button_set_active(GTK_TOGGLE_BUTTON(widget), - fvalue > 0.0f); - } else if (GTK_IS_RANGE(widget)) { - gtk_range_set_value(GTK_RANGE(widget), fvalue); - } else { - fprintf(stderr, "Unknown widget type for value\n"); - } - - if (controller->spin) { - // Update spinner for numeric control - gtk_spin_button_set_value(GTK_SPIN_BUTTON(controller->spin), - fvalue); - } - } else if (GTK_IS_ENTRY(widget) && type == jalv->urids.atom_String) { - gtk_entry_set_text(GTK_ENTRY(widget), (const char*)body); - } else if (GTK_IS_FILE_CHOOSER(widget) && type == jalv->urids.atom_Path) { - gtk_file_chooser_set_filename(GTK_FILE_CHOOSER(widget), (const char*)body); - } else { - fprintf(stderr, "Unknown widget type for value\n"); - } + GtkWidget* widget = controller->control; + const double fvalue = get_atom_double(jalv, size, type, body); + + if (!isnan(fvalue)) { + if (GTK_IS_COMBO_BOX(widget)) { + GtkTreeModel* model = gtk_combo_box_get_model(GTK_COMBO_BOX(widget)); + GValue value = G_VALUE_INIT; + GtkTreeIter i; + bool valid = gtk_tree_model_get_iter_first(model, &i); + while (valid) { + gtk_tree_model_get_value(model, &i, 0, &value); + const double v = g_value_get_float(&value); + g_value_unset(&value); + if (fabs(v - fvalue) < FLT_EPSILON) { + gtk_combo_box_set_active_iter(GTK_COMBO_BOX(widget), &i); + return; + } + valid = gtk_tree_model_iter_next(model, &i); + } + } else if (GTK_IS_TOGGLE_BUTTON(widget)) { + gtk_toggle_button_set_active(GTK_TOGGLE_BUTTON(widget), fvalue > 0.0f); + } else if (GTK_IS_SWITCH(widget)) { + gtk_switch_set_active(GTK_SWITCH(widget), fvalue > 0.f); + } else if (GTK_IS_RANGE(widget)) { + gtk_range_set_value(GTK_RANGE(widget), fvalue); + } else { + jalv_log(JALV_LOG_WARNING, "Unknown widget type for value\n"); + } + + if (controller->spin) { + // Update spinner for numeric control + gtk_spin_button_set_value(GTK_SPIN_BUTTON(controller->spin), fvalue); + } + } else if (GTK_IS_ENTRY(widget) && type == jalv->urids.atom_String) { + gtk_entry_set_text(GTK_ENTRY(widget), (const char*)body); + } else if (GTK_IS_FILE_CHOOSER(widget) && type == jalv->urids.atom_Path) { + gtk_file_chooser_set_filename(GTK_FILE_CHOOSER(widget), (const char*)body); + } else { + jalv_log(JALV_LOG_WARNING, "Unknown widget type for value\n"); + } } static int @@ -596,19 +690,23 @@ patch_set_get(Jalv* jalv, const LV2_Atom_URID** property, const LV2_Atom** value) { - lv2_atom_object_get(obj, - jalv->urids.patch_property, (const LV2_Atom*)property, - jalv->urids.patch_value, value, - 0); - if (!*property) { - fprintf(stderr, "patch:Set message with no property\n"); - return 1; - } else if ((*property)->atom.type != jalv->forge.URID) { - fprintf(stderr, "patch:Set property is not a URID\n"); - return 1; - } - - return 0; + lv2_atom_object_get(obj, + jalv->urids.patch_property, + (const LV2_Atom*)property, + jalv->urids.patch_value, + value, + 0); + if (!*property) { + jalv_log(JALV_LOG_WARNING, "patch:Set message with no property\n"); + return 1; + } + + if ((*property)->atom.type != jalv->forge.URID) { + jalv_log(JALV_LOG_WARNING, "patch:Set property is not a URID\n"); + return 1; + } + + return 0; } static int @@ -616,634 +714,832 @@ patch_put_get(Jalv* jalv, const LV2_Atom_Object* obj, const LV2_Atom_Object** body) { - lv2_atom_object_get(obj, - jalv->urids.patch_body, (const LV2_Atom*)body, - 0); - if (!*body) { - fprintf(stderr, "patch:Put message with no body\n"); - return 1; - } else if (!lv2_atom_forge_is_object_type(&jalv->forge, (*body)->atom.type)) { - fprintf(stderr, "patch:Put body is not an object\n"); - return 1; - } - - return 0; + lv2_atom_object_get(obj, jalv->urids.patch_body, (const LV2_Atom*)body, 0); + if (!*body) { + jalv_log(JALV_LOG_WARNING, "patch:Put message with no body\n"); + return 1; + } + + if (!lv2_atom_forge_is_object_type(&jalv->forge, (*body)->atom.type)) { + jalv_log(JALV_LOG_WARNING, "patch:Put body is not an object\n"); + return 1; + } + + return 0; +} + +static LV2UI_Request_Value_Status +on_request_value(LV2UI_Feature_Handle handle, + const LV2_URID key, + const LV2_URID ZIX_UNUSED(type), + const LV2_Feature* const* ZIX_UNUSED(features)) +{ + Jalv* const jalv = (Jalv*)handle; + const ControlID* control = get_property_control(&jalv->controls, key); + + if (!control) { + return LV2UI_REQUEST_VALUE_ERR_UNKNOWN; + } + + if (control->value_type != jalv->forge.Path) { + return LV2UI_REQUEST_VALUE_ERR_UNSUPPORTED; + } + + GtkWidget* dialog = gtk_file_chooser_dialog_new("Choose file", + GTK_WINDOW(jalv->window), + GTK_FILE_CHOOSER_ACTION_OPEN, + "_Cancel", + GTK_RESPONSE_CANCEL, + "_OK", + GTK_RESPONSE_OK, + NULL); + + if (gtk_dialog_run(GTK_DIALOG(dialog)) == GTK_RESPONSE_OK) { + char* path = gtk_file_chooser_get_filename(GTK_FILE_CHOOSER(dialog)); + + set_control(control, strlen(path) + 1, jalv->forge.Path, path); + + g_free(path); + } + + gtk_widget_destroy(dialog); + + return 0; } static void property_changed(Jalv* jalv, LV2_URID key, const LV2_Atom* value) { - ControlID* control = get_property_control(&jalv->controls, key); - if (control) { - control_changed(jalv, - (Controller*)control->widget, - value->size, - value->type, - value + 1); - } + ControlID* control = get_property_control(&jalv->controls, key); + if (control) { + control_changed( + jalv, (Controller*)control->widget, value->size, value->type, value + 1); + } } void -jalv_ui_port_event(Jalv* jalv, - uint32_t port_index, - uint32_t buffer_size, - uint32_t protocol, - const void* buffer) +jalv_frontend_port_event(Jalv* jalv, + uint32_t port_index, + uint32_t buffer_size, + uint32_t protocol, + const void* buffer) { - if (jalv->ui_instance) { - suil_instance_port_event(jalv->ui_instance, port_index, - buffer_size, protocol, buffer); - return; - } else if (protocol == 0 && (Controller*)jalv->ports[port_index].widget) { - control_changed(jalv, - (Controller*)jalv->ports[port_index].widget, - buffer_size, - jalv->forge.Float, - buffer); - return; - } else if (protocol == 0) { - return; // No widget (probably notOnGUI) - } else if (protocol != jalv->urids.atom_eventTransfer) { - fprintf(stderr, "Unknown port event protocol\n"); - return; - } - - const LV2_Atom* atom = (const LV2_Atom*)buffer; - if (lv2_atom_forge_is_object_type(&jalv->forge, atom->type)) { - updating = true; - const LV2_Atom_Object* obj = (const LV2_Atom_Object*)buffer; - if (obj->body.otype == jalv->urids.patch_Set) { - const LV2_Atom_URID* property = NULL; - const LV2_Atom* value = NULL; - if (!patch_set_get(jalv, obj, &property, &value)) { - property_changed(jalv, property->body, value); - } - } else if (obj->body.otype == jalv->urids.patch_Put) { - const LV2_Atom_Object* body = NULL; - if (!patch_put_get(jalv, obj, &body)) { - LV2_ATOM_OBJECT_FOREACH(body, prop) { - property_changed(jalv, prop->key, &prop->value); - } - } - } else { - printf("Unknown object type?\n"); - } - updating = false; - } + if (jalv->ui_instance) { + suil_instance_port_event( + jalv->ui_instance, port_index, buffer_size, protocol, buffer); + return; + } + + if (protocol == 0) { + Controller* const controller = (Controller*)jalv->ports[port_index].widget; + if (controller) { + control_changed(jalv, controller, buffer_size, jalv->forge.Float, buffer); + } + + return; + } + + if (protocol != jalv->urids.atom_eventTransfer) { + jalv_log(JALV_LOG_WARNING, "Unknown port event protocol\n"); + return; + } + + const LV2_Atom* atom = (const LV2_Atom*)buffer; + if (lv2_atom_forge_is_object_type(&jalv->forge, atom->type)) { + updating = true; + const LV2_Atom_Object* obj = (const LV2_Atom_Object*)buffer; + if (obj->body.otype == jalv->urids.patch_Set) { + const LV2_Atom_URID* property = NULL; + const LV2_Atom* value = NULL; + if (!patch_set_get(jalv, obj, &property, &value)) { + property_changed(jalv, property->body, value); + } + } else if (obj->body.otype == jalv->urids.patch_Put) { + const LV2_Atom_Object* body = NULL; + if (!patch_put_get(jalv, obj, &body)) { + LV2_ATOM_OBJECT_FOREACH (body, prop) { + property_changed(jalv, prop->key, &prop->value); + } + } + } else { + jalv_log(JALV_LOG_ERR, "Unknown object type\n"); + } + updating = false; + } } static gboolean scale_changed(GtkRange* range, gpointer data) { - set_float_control((const ControlID*)data, gtk_range_get_value(range)); - return FALSE; + set_float_control((const ControlID*)data, gtk_range_get_value(range)); + return FALSE; } static gboolean spin_changed(GtkSpinButton* spin, gpointer data) { - const ControlID* control = (const ControlID*)data; - Controller* controller = (Controller*)control->widget; - GtkRange* range = GTK_RANGE(controller->control); - const double value = gtk_spin_button_get_value(spin); - if (differ_enough(gtk_range_get_value(range), value)) { - gtk_range_set_value(range, value); - } - return FALSE; + const ControlID* control = (const ControlID*)data; + Controller* controller = (Controller*)control->widget; + GtkRange* range = GTK_RANGE(controller->control); + const double value = gtk_spin_button_get_value(spin); + if (differ_enough(gtk_range_get_value(range), value)) { + gtk_range_set_value(range, value); + } + return FALSE; } static gboolean log_scale_changed(GtkRange* range, gpointer data) { - set_float_control((const ControlID*)data, expf(gtk_range_get_value(range))); - return FALSE; + set_float_control((const ControlID*)data, expf(gtk_range_get_value(range))); + return FALSE; } static gboolean log_spin_changed(GtkSpinButton* spin, gpointer data) { - const ControlID* control = (const ControlID*)data; - Controller* controller = (Controller*)control->widget; - GtkRange* range = GTK_RANGE(controller->control); - const double value = gtk_spin_button_get_value(spin); - if (differ_enough(gtk_range_get_value(range), logf(value))) { - gtk_range_set_value(range, logf(value)); - } - return FALSE; + const ControlID* control = (const ControlID*)data; + Controller* controller = (Controller*)control->widget; + GtkRange* range = GTK_RANGE(controller->control); + const double value = gtk_spin_button_get_value(spin); + if (differ_enough(gtk_range_get_value(range), logf(value))) { + gtk_range_set_value(range, logf(value)); + } + return FALSE; } static void combo_changed(GtkComboBox* box, gpointer data) { - const ControlID* control = (const ControlID*)data; + const ControlID* control = (const ControlID*)data; - GtkTreeIter iter; - if (gtk_combo_box_get_active_iter(box, &iter)) { - GtkTreeModel* model = gtk_combo_box_get_model(box); - GValue value = { 0, { { 0 } } }; + GtkTreeIter iter; + if (gtk_combo_box_get_active_iter(box, &iter)) { + GtkTreeModel* model = gtk_combo_box_get_model(box); + GValue value = G_VALUE_INIT; - gtk_tree_model_get_value(model, &iter, 0, &value); - const double v = g_value_get_float(&value); - g_value_unset(&value); + gtk_tree_model_get_value(model, &iter, 0, &value); + const double v = g_value_get_float(&value); + g_value_unset(&value); - set_float_control(control, v); - } + set_float_control(control, v); + } } static gboolean -toggle_changed(GtkToggleButton* button, gpointer data) +switch_changed(GtkSwitch* toggle_switch, gboolean state, gpointer data) { - set_float_control((const ControlID*)data, - gtk_toggle_button_get_active(button) ? 1.0f : 0.0f); - return FALSE; + (void)toggle_switch; + (void)data; + + set_float_control((const ControlID*)data, state ? 1.0f : 0.0f); + return FALSE; } static void string_changed(GtkEntry* widget, gpointer data) { - ControlID* control = (ControlID*)data; - const char* string = gtk_entry_get_text(widget); + const ControlID* control = (const ControlID*)data; + const char* string = gtk_entry_get_text(widget); - set_control(control, strlen(string) + 1, control->jalv->forge.String, string); + set_control(control, strlen(string) + 1, s_jalv->forge.String, string); } static void -file_changed(GtkFileChooserButton* widget, - gpointer data) +file_changed(GtkFileChooserButton* widget, gpointer data) { - ControlID* control = (ControlID*)data; - Jalv* jalv = control->jalv; - const char* filename = gtk_file_chooser_get_filename( - GTK_FILE_CHOOSER(widget)); + const ControlID* control = (const ControlID*)data; + const char* filename = + gtk_file_chooser_get_filename(GTK_FILE_CHOOSER(widget)); - set_control(control, strlen(filename), jalv->forge.Path, filename); + set_control(control, strlen(filename) + 1, s_jalv->forge.Path, filename); } static Controller* new_controller(GtkSpinButton* spin, GtkWidget* control) { - Controller* controller = (Controller*)malloc(sizeof(Controller)); - controller->spin = spin; - controller->control = control; - return controller; + Controller* controller = (Controller*)malloc(sizeof(Controller)); + controller->spin = spin; + controller->control = control; + return controller; } static Controller* make_combo(ControlID* record, float value) { - GtkListStore* list_store = gtk_list_store_new( - 2, G_TYPE_FLOAT, G_TYPE_STRING); - int active = -1; - for (size_t i = 0; i < record->n_points; ++i) { - const ScalePoint* point = &record->points[i]; - GtkTreeIter iter; - gtk_list_store_append(list_store, &iter); - gtk_list_store_set(list_store, &iter, - 0, point->value, - 1, point->label, - -1); - if (fabs(value - point->value) < FLT_EPSILON) { - active = i; - } - } - - GtkWidget* combo = gtk_combo_box_new_with_model(GTK_TREE_MODEL(list_store)); - gtk_combo_box_set_active(GTK_COMBO_BOX(combo), active); - g_object_unref(list_store); - - gtk_widget_set_sensitive(combo, record->is_writable); - - GtkCellRenderer* cell = gtk_cell_renderer_text_new(); - gtk_cell_layout_pack_start(GTK_CELL_LAYOUT(combo), cell, TRUE); - gtk_cell_layout_set_attributes(GTK_CELL_LAYOUT(combo), cell, "text", 1, NULL); - - if (record->is_writable) { - g_signal_connect(G_OBJECT(combo), "changed", - G_CALLBACK(combo_changed), record); - } - - return new_controller(NULL, combo); + GtkListStore* list_store = gtk_list_store_new(2, G_TYPE_FLOAT, G_TYPE_STRING); + int active = -1; + for (size_t i = 0; i < record->n_points; ++i) { + const ScalePoint* point = &record->points[i]; + GtkTreeIter iter; + gtk_list_store_append(list_store, &iter); + gtk_list_store_set(list_store, &iter, 0, point->value, 1, point->label, -1); + if (fabsf(value - point->value) < FLT_EPSILON) { + active = i; + } + } + + GtkWidget* combo = gtk_combo_box_new_with_model(GTK_TREE_MODEL(list_store)); + gtk_combo_box_set_active(GTK_COMBO_BOX(combo), active); + g_object_unref(list_store); + + gtk_widget_set_sensitive(combo, record->is_writable); + gtk_widget_set_halign(combo, GTK_ALIGN_START); + gtk_widget_set_hexpand(combo, FALSE); + + GtkCellRenderer* cell = gtk_cell_renderer_text_new(); + gtk_cell_layout_pack_start(GTK_CELL_LAYOUT(combo), cell, TRUE); + gtk_cell_layout_set_attributes(GTK_CELL_LAYOUT(combo), cell, "text", 1, NULL); + + if (record->is_writable) { + g_signal_connect( + G_OBJECT(combo), "changed", G_CALLBACK(combo_changed), record); + } + + return new_controller(NULL, combo); } static Controller* make_log_slider(ControlID* record, float value) { - const float min = get_float(record->min, 0.0f); - const float max = get_float(record->max, 1.0f); - const float lmin = logf(min); - const float lmax = logf(max); - const float ldft = logf(value); - GtkWidget* scale = new_hscale(lmin, lmax, 0.001); - GtkWidget* spin = gtk_spin_button_new_with_range(min, max, 0.000001); - - gtk_widget_set_sensitive(scale, record->is_writable); - gtk_widget_set_sensitive(spin, record->is_writable); - - gtk_scale_set_draw_value(GTK_SCALE(scale), FALSE); - gtk_range_set_value(GTK_RANGE(scale), ldft); - gtk_spin_button_set_value(GTK_SPIN_BUTTON(spin), value); - - if (record->is_writable) { - g_signal_connect(G_OBJECT(scale), "value-changed", - G_CALLBACK(log_scale_changed), record); - g_signal_connect(G_OBJECT(spin), "value-changed", - G_CALLBACK(log_spin_changed), record); - } - - return new_controller(GTK_SPIN_BUTTON(spin), scale); + const float min = get_float(record->min, 0.0f); + const float max = get_float(record->max, 1.0f); + const float lmin = logf(min); + const float lmax = logf(max); + const float ldft = logf(value); + + GtkWidget* const scale = + gtk_scale_new_with_range(GTK_ORIENTATION_HORIZONTAL, lmin, lmax, 0.001); + + GtkWidget* const spin = gtk_spin_button_new_with_range(min, max, 0.000001); + + gtk_widget_set_sensitive(scale, record->is_writable); + gtk_widget_set_sensitive(spin, record->is_writable); + + gtk_scale_set_draw_value(GTK_SCALE(scale), FALSE); + gtk_range_set_value(GTK_RANGE(scale), ldft); + gtk_spin_button_set_value(GTK_SPIN_BUTTON(spin), value); + + if (record->is_writable) { + g_signal_connect( + G_OBJECT(scale), "value-changed", G_CALLBACK(log_scale_changed), record); + g_signal_connect( + G_OBJECT(spin), "value-changed", G_CALLBACK(log_spin_changed), record); + } + + return new_controller(GTK_SPIN_BUTTON(spin), scale); } static Controller* make_slider(ControlID* record, float value) { - const float min = get_float(record->min, 0.0f); - const float max = get_float(record->max, 1.0f); - const double step = record->is_integer ? 1.0 : ((max - min) / 100.0); - GtkWidget* scale = new_hscale(min, max, step); - GtkWidget* spin = gtk_spin_button_new_with_range(min, max, step); - - gtk_widget_set_sensitive(scale, record->is_writable); - gtk_widget_set_sensitive(spin, record->is_writable); - - if (record->is_integer) { - gtk_spin_button_set_digits(GTK_SPIN_BUTTON(spin), 0); - } else { - gtk_spin_button_set_digits(GTK_SPIN_BUTTON(spin), 7); - } - - gtk_scale_set_draw_value(GTK_SCALE(scale), FALSE); - gtk_range_set_value(GTK_RANGE(scale), value); - gtk_spin_button_set_value(GTK_SPIN_BUTTON(spin), value); - if (record->points) { - for (size_t i = 0; i < record->n_points; ++i) { - const ScalePoint* point = &record->points[i]; - - gchar* str = g_markup_printf_escaped( - "<span font_size=\"small\">%s</span>", point->label); - gtk_scale_add_mark( - GTK_SCALE(scale), point->value, GTK_POS_TOP, str); - } - } - - if (record->is_writable) { - g_signal_connect(G_OBJECT(scale), "value-changed", - G_CALLBACK(scale_changed), record); - g_signal_connect(G_OBJECT(spin), "value-changed", - G_CALLBACK(spin_changed), record); - } - - return new_controller(GTK_SPIN_BUTTON(spin), scale); + const float min = get_float(record->min, 0.0f); + const float max = get_float(record->max, 1.0f); + const double step = record->is_integer ? 1.0 : ((max - min) / 100.0); + + GtkWidget* const scale = + gtk_scale_new_with_range(GTK_ORIENTATION_HORIZONTAL, min, max, step); + + GtkWidget* const spin = gtk_spin_button_new_with_range(min, max, step); + + gtk_widget_set_sensitive(scale, record->is_writable); + gtk_widget_set_sensitive(spin, record->is_writable); + + if (record->is_integer) { + gtk_spin_button_set_digits(GTK_SPIN_BUTTON(spin), 0); + } else { + gtk_spin_button_set_digits(GTK_SPIN_BUTTON(spin), 7); + } + + gtk_scale_set_draw_value(GTK_SCALE(scale), FALSE); + gtk_range_set_value(GTK_RANGE(scale), value); + gtk_spin_button_set_value(GTK_SPIN_BUTTON(spin), value); + if (record->points) { + for (size_t i = 0; i < record->n_points; ++i) { + const ScalePoint* point = &record->points[i]; + + gchar* str = g_markup_printf_escaped( + "<span font_size=\"small\">%s</span>", point->label); + gtk_scale_add_mark(GTK_SCALE(scale), point->value, GTK_POS_TOP, str); + } + } + + if (record->is_writable) { + g_signal_connect( + G_OBJECT(scale), "value-changed", G_CALLBACK(scale_changed), record); + g_signal_connect( + G_OBJECT(spin), "value-changed", G_CALLBACK(spin_changed), record); + } + + gtk_widget_set_halign(scale, GTK_ALIGN_FILL); + gtk_widget_set_hexpand(scale, TRUE); + return new_controller(GTK_SPIN_BUTTON(spin), scale); } static Controller* -make_toggle(ControlID* record, float value) +make_toggle_switch(ControlID* record, float value) { - GtkWidget* check = gtk_check_button_new(); + GtkWidget* toggle_switch = gtk_switch_new(); + gtk_widget_set_halign(toggle_switch, GTK_ALIGN_START); + gtk_widget_set_hexpand(toggle_switch, FALSE); - gtk_widget_set_sensitive(check, record->is_writable); + gtk_widget_set_sensitive(toggle_switch, record->is_writable); - if (value) { - gtk_toggle_button_set_active(GTK_TOGGLE_BUTTON(check), TRUE); - } + if (value) { + gtk_switch_set_active(GTK_SWITCH(toggle_switch), TRUE); + } - if (record->is_writable) { - g_signal_connect(G_OBJECT(check), "toggled", - G_CALLBACK(toggle_changed), record); - } + if (record->is_writable) { + g_signal_connect( + G_OBJECT(toggle_switch), "state-set", G_CALLBACK(switch_changed), record); + } - return new_controller(NULL, check); + return new_controller(NULL, toggle_switch); } static Controller* make_entry(ControlID* control) { - GtkWidget* entry = gtk_entry_new(); + GtkWidget* entry = gtk_entry_new(); - gtk_widget_set_sensitive(entry, control->is_writable); - if (control->is_writable) { - g_signal_connect(G_OBJECT(entry), "activate", - G_CALLBACK(string_changed), control); - } + gtk_widget_set_sensitive(entry, control->is_writable); + if (control->is_writable) { + g_signal_connect( + G_OBJECT(entry), "activate", G_CALLBACK(string_changed), control); + } - return new_controller(NULL, entry); + return new_controller(NULL, entry); } static Controller* make_file_chooser(ControlID* record) { - GtkWidget* button = gtk_file_chooser_button_new( - "Open File", GTK_FILE_CHOOSER_ACTION_OPEN); + GtkWidget* button = + gtk_file_chooser_button_new("Open File", GTK_FILE_CHOOSER_ACTION_OPEN); - gtk_widget_set_sensitive(button, record->is_writable); + gtk_widget_set_sensitive(button, record->is_writable); - if (record->is_writable) { - g_signal_connect(G_OBJECT(button), "file-set", - G_CALLBACK(file_changed), record); - } + if (record->is_writable) { + g_signal_connect( + G_OBJECT(button), "file-set", G_CALLBACK(file_changed), record); + } - return new_controller(NULL, button); + return new_controller(NULL, button); } static Controller* make_controller(ControlID* control, float value) { - Controller* controller = NULL; - - if (control->is_toggle) { - controller = make_toggle(control, value); - } else if (control->is_enumeration) { - controller = make_combo(control, value); - } else if (control->is_logarithmic) { - controller = make_log_slider(control, value); - } else { - controller = make_slider(control, value); - } - - return controller; + Controller* controller = NULL; + + if (control->is_toggle) { + controller = make_toggle_switch(control, value); + } else if (control->is_enumeration) { + controller = make_combo(control, value); + } else if (control->is_logarithmic) { + controller = make_log_slider(control, value); + } else { + controller = make_slider(control, value); + } + + return controller; } static GtkWidget* -new_label(const char* text, bool title, float xalign, float yalign) +new_label(const char* text, bool title, GtkAlign xalign, GtkAlign yalign) { - GtkWidget* label = gtk_label_new(NULL); - const char* fmt = title ? "<span font_weight=\"bold\">%s</span>" : "%s:"; - gchar* str = g_markup_printf_escaped(fmt, text); - gtk_label_set_markup(GTK_LABEL(label), str); - g_free(str); - gtk_misc_set_alignment(GTK_MISC(label), xalign, yalign); - return label; + GtkWidget* const label = gtk_label_new(NULL); + gchar* const str = + title + ? g_markup_printf_escaped("<span font_weight=\"bold\">%s</span>", text) + : g_markup_printf_escaped("%s:", text); + + gtk_widget_set_halign(label, xalign); + gtk_widget_set_valign(label, yalign); + gtk_label_set_markup(GTK_LABEL(label), str); + + g_free(str); + return label; } static void -add_control_row(GtkWidget* table, +add_control_row(GtkWidget* grid, int row, const char* name, Controller* controller) { - GtkWidget* label = new_label(name, false, 1.0, 0.5); - gtk_table_attach(GTK_TABLE(table), - label, - 0, 1, row, row + 1, - GTK_FILL, (GtkAttachOptions)(GTK_FILL|GTK_EXPAND), 8, 1); - int control_left_attach = 1; - if (controller->spin) { - control_left_attach = 2; - gtk_table_attach(GTK_TABLE(table), GTK_WIDGET(controller->spin), - 1, 2, row, row + 1, - GTK_FILL, GTK_FILL, 2, 1); - } - gtk_table_attach(GTK_TABLE(table), controller->control, - control_left_attach, 3, row, row + 1, - (GtkAttachOptions)(GTK_FILL|GTK_EXPAND), GTK_FILL, 2, 1); + GtkWidget* label = new_label(name, false, GTK_ALIGN_END, GTK_ALIGN_BASELINE); + gtk_widget_set_margin_end(label, 8); + gtk_grid_attach(GTK_GRID(grid), label, 0, row, 1, 1); + + if (controller->spin) { + gtk_grid_attach(GTK_GRID(grid), GTK_WIDGET(controller->spin), 1, row, 1, 1); + gtk_grid_attach(GTK_GRID(grid), controller->control, 2, row, 1, 1); + } else { + gtk_grid_attach(GTK_GRID(grid), controller->control, 1, row, 2, 1); + } } static int -control_group_cmp(const void* p1, const void* p2, ZIX_UNUSED void* data) +control_group_cmp(const void* p1, const void* p2, void* ZIX_UNUSED(data)) { - const ControlID* control1 = *(const ControlID*const*)p1; - const ControlID* control2 = *(const ControlID*const*)p2; + const ControlID* control1 = *(const ControlID* const*)p1; + const ControlID* control2 = *(const ControlID* const*)p2; - const int cmp = (control1->group && control2->group) - ? strcmp(lilv_node_as_string(control1->group), - lilv_node_as_string(control2->group)) - : ((intptr_t)control1->group - (intptr_t)control2->group); + const int cmp = (control1->group && control2->group) + ? strcmp(lilv_node_as_string(control1->group), + lilv_node_as_string(control2->group)) + : ((intptr_t)control1->group - (intptr_t)control2->group); - return cmp; + return cmp; } static GtkWidget* build_control_widget(Jalv* jalv, GtkWidget* window) { - GtkWidget* port_table = gtk_table_new(jalv->num_ports, 3, false); - - /* Make an array of controls sorted by group */ - GArray* controls = g_array_new(FALSE, TRUE, sizeof(ControlID*)); - for (unsigned i = 0; i < jalv->controls.n_controls; ++i) { - g_array_append_vals(controls, &jalv->controls.controls[i], 1); - } - g_array_sort_with_data(controls, control_group_cmp, jalv); - - /* Add controls in group order */ - LilvNode* last_group = NULL; - int n_rows = 0; - for (size_t i = 0; i < controls->len; ++i) { - ControlID* record = g_array_index(controls, ControlID*, i); - Controller* controller = NULL; - LilvNode* group = record->group; - - /* Check group and add new heading if necessary */ - if (group && !lilv_node_equals(group, last_group)) { - LilvNode* group_name = lilv_world_get( - jalv->world, group, jalv->nodes.lv2_name, NULL); - GtkWidget* group_label = new_label( - lilv_node_as_string(group_name), true, 0.0f, 1.0f); - gtk_table_attach(GTK_TABLE(port_table), group_label, - 0, 2, n_rows, n_rows + 1, - GTK_FILL, GTK_FILL, 0, 6); - ++n_rows; - } - last_group = group; - - /* Make control widget */ - if (record->value_type == jalv->forge.String) { - controller = make_entry(record); - } else if (record->value_type == jalv->forge.Path) { - controller = make_file_chooser(record); - } else { - const float val = get_float(record->def, 0.0f); - controller = make_controller(record, val); - } - - record->widget = controller; - if (record->type == PORT) { - jalv->ports[record->index].widget = controller; - } - if (controller) { - /* Add row to table for this controller */ - add_control_row( - port_table, n_rows++, - (record->label - ? lilv_node_as_string(record->label) - : lilv_node_as_uri(record->node)), - controller); - - /* Set tooltip text from comment, if available */ - LilvNode* comment = lilv_world_get( - jalv->world, record->node, jalv->nodes.rdfs_comment, NULL); - if (comment) { - gtk_widget_set_tooltip_text(controller->control, - lilv_node_as_string(comment)); - } - lilv_node_free(comment); - } - } - - if (n_rows > 0) { - gtk_window_set_resizable(GTK_WINDOW(window), TRUE); - GtkWidget* alignment = gtk_alignment_new(0.5, 0.0, 1.0, 0.0); - gtk_alignment_set_padding(GTK_ALIGNMENT(alignment), 0, 0, 8, 8); - gtk_container_add(GTK_CONTAINER(alignment), port_table); - return alignment; - } else { - gtk_widget_destroy(port_table); - GtkWidget* button = gtk_button_new_with_label("Close"); - g_signal_connect_swapped(button, "clicked", - G_CALLBACK(gtk_widget_destroy), window); - gtk_window_set_resizable(GTK_WINDOW(window), FALSE); - return button; - } + GtkWidget* port_grid = gtk_grid_new(); + gtk_grid_set_row_spacing(GTK_GRID(port_grid), 4); + + // Make an array of controls sorted by group + GArray* controls = g_array_new(FALSE, TRUE, sizeof(ControlID*)); + for (unsigned i = 0; i < jalv->controls.n_controls; ++i) { + g_array_append_vals(controls, &jalv->controls.controls[i], 1); + } + g_array_sort_with_data(controls, control_group_cmp, jalv); + + // Add controls in group order + const LilvNode* last_group = NULL; + int n_rows = 0; + for (size_t i = 0; i < controls->len; ++i) { + ControlID* record = g_array_index(controls, ControlID*, i); + Controller* controller = NULL; + LilvNode* group = record->group; + + // Check group and add new heading if necessary + if (group && !lilv_node_equals(group, last_group)) { + LilvNode* group_name = + lilv_world_get(jalv->world, group, jalv->nodes.lv2_name, NULL); + + if (!group_name) { + group_name = + lilv_world_get(jalv->world, group, jalv->nodes.rdfs_label, NULL); + } + + GtkWidget* group_label = new_label(lilv_node_as_string(group_name), + true, + GTK_ALIGN_START, + GTK_ALIGN_BASELINE); + + lilv_node_free(group_name); + gtk_grid_attach(GTK_GRID(port_grid), group_label, 0, n_rows, 3, 1); + ++n_rows; + } + last_group = group; + + // Make control widget + if (record->value_type == jalv->forge.String) { + controller = make_entry(record); + } else if (record->value_type == jalv->forge.Path) { + controller = make_file_chooser(record); + } else { + const float val = get_float(record->def, 0.0f); + controller = make_controller(record, val); + } + + record->widget = controller; + if (record->type == PORT) { + jalv->ports[record->id.index].widget = controller; + } + if (controller) { + // Add row to table for this controller + add_control_row(port_grid, + n_rows++, + (record->label ? lilv_node_as_string(record->label) + : lilv_node_as_uri(record->node)), + controller); + + // Set tooltip text from comment, if available + LilvNode* comment = lilv_world_get( + jalv->world, record->node, jalv->nodes.rdfs_comment, NULL); + if (comment) { + gtk_widget_set_tooltip_text(controller->control, + lilv_node_as_string(comment)); + } + lilv_node_free(comment); + } + } + + if (n_rows > 0) { + gtk_window_set_resizable(GTK_WINDOW(window), TRUE); + gtk_widget_set_margin_start(port_grid, 8); + gtk_widget_set_margin_end(port_grid, 8); + gtk_widget_set_halign(port_grid, GTK_ALIGN_FILL); + gtk_widget_set_hexpand(port_grid, TRUE); + gtk_widget_set_valign(port_grid, GTK_ALIGN_START); + gtk_widget_set_vexpand(port_grid, FALSE); + return port_grid; + } + + gtk_widget_destroy(port_grid); + GtkWidget* button = gtk_button_new_with_label("Close"); + g_signal_connect_swapped( + button, "clicked", G_CALLBACK(gtk_widget_destroy), window); + gtk_window_set_resizable(GTK_WINDOW(window), FALSE); + return button; } static void build_menu(Jalv* jalv, GtkWidget* window, GtkWidget* vbox) { - GtkWidget* menu_bar = gtk_menu_bar_new(); - GtkWidget* file = gtk_menu_item_new_with_mnemonic("_File"); - GtkWidget* file_menu = gtk_menu_new(); - - GtkAccelGroup* ag = gtk_accel_group_new(); - gtk_window_add_accel_group(GTK_WINDOW(window), ag); - - GtkWidget* save = gtk_image_menu_item_new_from_stock(GTK_STOCK_SAVE, ag); - GtkWidget* quit = gtk_image_menu_item_new_from_stock(GTK_STOCK_QUIT, ag); - - gtk_menu_item_set_submenu(GTK_MENU_ITEM(file), file_menu); - gtk_menu_shell_append(GTK_MENU_SHELL(file_menu), save); - gtk_menu_shell_append(GTK_MENU_SHELL(file_menu), quit); - gtk_menu_shell_append(GTK_MENU_SHELL(menu_bar), file); - - GtkWidget* pset_item = gtk_menu_item_new_with_mnemonic("_Presets"); - GtkWidget* pset_menu = gtk_menu_new(); - GtkWidget* save_preset = gtk_menu_item_new_with_mnemonic( - "_Save Preset..."); - GtkWidget* delete_preset = gtk_menu_item_new_with_mnemonic( - "_Delete Current Preset..."); - gtk_menu_item_set_submenu(GTK_MENU_ITEM(pset_item), pset_menu); - gtk_menu_shell_append(GTK_MENU_SHELL(pset_menu), save_preset); - gtk_menu_shell_append(GTK_MENU_SHELL(pset_menu), delete_preset); - gtk_menu_shell_append(GTK_MENU_SHELL(pset_menu), - gtk_separator_menu_item_new()); - gtk_menu_shell_append(GTK_MENU_SHELL(menu_bar), pset_item); - - PresetMenu menu = { - NULL, NULL, GTK_MENU(pset_menu), - g_sequence_new((GDestroyNotify)pset_menu_free) - }; - jalv_load_presets(jalv, add_preset_to_menu, &menu); - finish_menu(&menu); - - g_signal_connect(G_OBJECT(quit), "activate", - G_CALLBACK(on_quit_activate), window); - - g_signal_connect(G_OBJECT(save), "activate", - G_CALLBACK(on_save_activate), jalv); - - g_signal_connect(G_OBJECT(save_preset), "activate", - G_CALLBACK(on_save_preset_activate), jalv); - - g_signal_connect(G_OBJECT(delete_preset), "activate", - G_CALLBACK(on_delete_preset_activate), jalv); - - gtk_box_pack_start(GTK_BOX(vbox), menu_bar, FALSE, FALSE, 0); + GtkWidget* menu_bar = gtk_menu_bar_new(); + GtkWidget* file = gtk_menu_item_new_with_mnemonic("_File"); + GtkWidget* file_menu = gtk_menu_new(); + + GtkAccelGroup* ag = gtk_accel_group_new(); + gtk_window_add_accel_group(GTK_WINDOW(window), ag); + + GtkWidget* save = gtk_menu_item_new_with_mnemonic("_Save"); + GtkWidget* quit = gtk_menu_item_new_with_mnemonic("_Quit"); + + gtk_menu_item_set_submenu(GTK_MENU_ITEM(file), file_menu); + gtk_menu_shell_append(GTK_MENU_SHELL(file_menu), save); + gtk_menu_shell_append(GTK_MENU_SHELL(file_menu), quit); + gtk_menu_shell_append(GTK_MENU_SHELL(menu_bar), file); + + GtkWidget* pset_item = gtk_menu_item_new_with_mnemonic("_Presets"); + GtkWidget* pset_menu = gtk_menu_new(); + GtkWidget* save_preset = gtk_menu_item_new_with_mnemonic("_Save Preset..."); + GtkWidget* delete_preset = + gtk_menu_item_new_with_mnemonic("_Delete Current Preset..."); + gtk_menu_item_set_submenu(GTK_MENU_ITEM(pset_item), pset_menu); + gtk_menu_shell_append(GTK_MENU_SHELL(pset_menu), save_preset); + gtk_menu_shell_append(GTK_MENU_SHELL(pset_menu), delete_preset); + gtk_menu_shell_append(GTK_MENU_SHELL(pset_menu), + gtk_separator_menu_item_new()); + gtk_menu_shell_append(GTK_MENU_SHELL(menu_bar), pset_item); + + PresetMenu menu = {NULL, + NULL, + GTK_MENU(pset_menu), + g_sequence_new((GDestroyNotify)pset_menu_free)}; + jalv_load_presets(jalv, add_preset_to_menu, &menu); + finish_menu(&menu); + + g_signal_connect( + G_OBJECT(quit), "activate", G_CALLBACK(on_quit_activate), window); + + g_signal_connect( + G_OBJECT(save), "activate", G_CALLBACK(on_save_activate), jalv); + + g_signal_connect(G_OBJECT(save_preset), + "activate", + G_CALLBACK(on_save_preset_activate), + jalv); + + g_signal_connect(G_OBJECT(delete_preset), + "activate", + G_CALLBACK(on_delete_preset_activate), + jalv); + + gtk_box_pack_start(GTK_BOX(vbox), menu_bar, FALSE, FALSE, 0); } bool -jalv_discover_ui(ZIX_UNUSED Jalv* jalv) +jalv_frontend_discover(const Jalv* ZIX_UNUSED(jalv)) { - return TRUE; + return TRUE; } float -jalv_ui_refresh_rate(Jalv* jalv) +jalv_frontend_refresh_rate(const Jalv* ZIX_UNUSED(jalv)) { -#if GTK_MAJOR_VERSION == 2 - return 30.0f; -#else - GdkDisplay* const display = gdk_display_get_default(); - GdkMonitor* const monitor = gdk_display_get_primary_monitor(display); + GdkDisplay* const display = gdk_display_get_default(); + GdkMonitor* const monitor = gdk_display_get_primary_monitor(display); - const float rate = (float)gdk_monitor_get_refresh_rate(monitor); + const float rate = (float)gdk_monitor_get_refresh_rate(monitor); - return rate < 30.0f ? 30.0f : rate; -#endif + return rate < 30.0f ? 30.0f : rate; } -int -jalv_open_ui(Jalv* jalv) +float +jalv_frontend_scale_factor(const Jalv* ZIX_UNUSED(jalv)) +{ + GdkDisplay* const display = gdk_display_get_default(); + GdkMonitor* const monitor = gdk_display_get_primary_monitor(display); + + return (float)gdk_monitor_get_scale_factor(monitor); +} + +static void +on_row_activated(GtkTreeView* const tree_view, + GtkTreePath* const path, + GtkTreeViewColumn* const column, + void* const user_data) +{ + (void)tree_view; + (void)path; + (void)column; + + gtk_dialog_response(GTK_DIALOG(user_data), GTK_RESPONSE_ACCEPT); +} + +LilvNode* +jalv_frontend_select_plugin(Jalv* jalv) { - GtkWidget* window = gtk_window_new(GTK_WINDOW_TOPLEVEL); - jalv->window = window; - - g_signal_connect(window, "destroy", - G_CALLBACK(on_window_destroy), jalv); - - set_window_title(jalv); - - GtkWidget* vbox = new_box(false, 0); - gtk_window_set_role(GTK_WINDOW(window), "plugin_ui"); - gtk_container_add(GTK_CONTAINER(window), vbox); - - if (!jalv->opts.no_menu) { - build_menu(jalv, window, vbox); - } - - /* Create/show alignment to contain UI (whether custom or generic) */ - GtkWidget* alignment = gtk_alignment_new(0.5, 0.5, 1.0, 1.0); - gtk_box_pack_start(GTK_BOX(vbox), alignment, TRUE, TRUE, 0); - gtk_widget_show(alignment); - - /* Attempt to instantiate custom UI if necessary */ - if (jalv->ui && !jalv->opts.generic_ui) { - jalv_ui_instantiate(jalv, jalv_native_ui_type(), alignment); - } - - if (jalv->ui_instance) { - GtkWidget* widget = (GtkWidget*)suil_instance_get_widget( - jalv->ui_instance); - - gtk_container_add(GTK_CONTAINER(alignment), widget); - gtk_window_set_resizable(GTK_WINDOW(window), jalv_ui_is_resizable(jalv)); - gtk_widget_show_all(vbox); - gtk_widget_grab_focus(widget); - } else { - GtkWidget* controls = build_control_widget(jalv, window); - GtkWidget* scroll_win = gtk_scrolled_window_new(NULL, NULL); - gtk_scrolled_window_add_with_viewport( - GTK_SCROLLED_WINDOW(scroll_win), controls); - gtk_scrolled_window_set_policy( - GTK_SCROLLED_WINDOW(scroll_win), - GTK_POLICY_AUTOMATIC, GTK_POLICY_AUTOMATIC); - gtk_container_add(GTK_CONTAINER(alignment), scroll_win); - gtk_widget_show_all(vbox); - - GtkRequisition controls_size, box_size; - size_request(GTK_WIDGET(controls), &controls_size); - size_request(GTK_WIDGET(vbox), &box_size); - - gtk_window_set_default_size( - GTK_WINDOW(window), - MAX(MAX(box_size.width, controls_size.width) + 24, 640), - box_size.height + controls_size.height); - } - - jalv_init_ui(jalv); - - g_timeout_add(1000 / jalv->ui_update_hz, (GSourceFunc)jalv_update, jalv); - - gtk_window_present(GTK_WINDOW(window)); - - gtk_main(); - suil_instance_free(jalv->ui_instance); - jalv->ui_instance = NULL; - zix_sem_post(&jalv->done); - return 0; + // Create the dialog + GtkWidget* const dialog = gtk_dialog_new_with_buttons( + "Plugin Selector", + NULL, + (GtkDialogFlags)(GTK_DIALOG_USE_HEADER_BAR | GTK_DIALOG_MODAL | + GTK_DIALOG_DESTROY_WITH_PARENT), + "_Cancel", + GTK_RESPONSE_CANCEL, + "_Load", + GTK_RESPONSE_ACCEPT, + NULL); + + gtk_window_set_role(GTK_WINDOW(dialog), "plugin_selector"); + gtk_window_set_default_size(GTK_WINDOW(dialog), 800, 600); + + // Build the treeview + + GtkTreeView* const tree_view = GTK_TREE_VIEW(gtk_tree_view_new()); + { + // Add treeview to the content area of the dialog + GtkWidget* content = gtk_dialog_get_content_area(GTK_DIALOG(dialog)); + GtkContainer* scroll = GTK_CONTAINER(gtk_scrolled_window_new(NULL, NULL)); + gtk_container_add(scroll, GTK_WIDGET(tree_view)); + gtk_container_add(GTK_CONTAINER(content), GTK_WIDGET(scroll)); + gtk_widget_set_visible(GTK_WIDGET(tree_view), TRUE); + gtk_widget_set_visible(GTK_WIDGET(scroll), TRUE); + gtk_box_set_child_packing( + GTK_BOX(content), GTK_WIDGET(scroll), TRUE, TRUE, 2, GTK_PACK_START); + gtk_scrolled_window_set_policy( + GTK_SCROLLED_WINDOW(scroll), GTK_POLICY_NEVER, GTK_POLICY_AUTOMATIC); + } + + // Set treeview columns (all strings) + static const char* const col_labels[] = {"Name", "Type", "Author", "URI"}; + for (unsigned i = 0; i < 4; ++i) { + GtkTreeViewColumn* const column = gtk_tree_view_column_new_with_attributes( + col_labels[i], gtk_cell_renderer_text_new(), "text", i, NULL); + + gtk_tree_view_column_set_sort_column_id(column, i); + gtk_tree_view_append_column(tree_view, column); + } + + // Build the model + GtkListStore* const store = gtk_list_store_new( + 4, G_TYPE_STRING, G_TYPE_STRING, G_TYPE_STRING, G_TYPE_STRING); + const LilvPlugins* plugins = lilv_world_get_all_plugins(jalv->world); + LILV_FOREACH (plugins, i, plugins) { + const LilvPlugin* const p = lilv_plugins_get(plugins, i); + LilvNode* const name = lilv_plugin_get_name(p); + const LilvPluginClass* const klass = lilv_plugin_get_class(p); + const LilvNode* const type = lilv_plugin_class_get_label(klass); + LilvNode* const author = lilv_plugin_get_author_name(p); + const LilvNode* const uri = lilv_plugin_get_uri(p); + + if (name && type && uri) { + GtkTreeIter iter; + gtk_list_store_insert_with_values(store, + &iter, + -1, + 0, + lilv_node_as_string(name), + 1, + lilv_node_as_string(type), + 2, + lilv_node_as_string(author), + 3, + lilv_node_as_string(uri), + -1); + } + + lilv_node_free(name); + lilv_node_free(author); + } + + gtk_tree_view_set_model(tree_view, GTK_TREE_MODEL(store)); + + g_signal_connect(GTK_WIDGET(tree_view), + "row-activated", + G_CALLBACK(on_row_activated), + dialog); + + // Get URI from selection + LilvNode* selected_uri = NULL; + if (gtk_dialog_run(GTK_DIALOG(dialog)) == GTK_RESPONSE_ACCEPT) { + GtkTreeSelection* selection = gtk_tree_view_get_selection(tree_view); + GtkTreeModel* model = GTK_TREE_MODEL(store); + GtkTreeIter selected; + if (gtk_tree_selection_get_selected(selection, &model, &selected)) { + GValue val = G_VALUE_INIT; + gtk_tree_model_get_value(model, &selected, 3, &val); + + selected_uri = lilv_new_uri(jalv->world, g_value_get_string(&val)); + + g_value_unset(&val); + } + } + gtk_widget_destroy(dialog); + + return selected_uri; } int -jalv_close_ui(ZIX_UNUSED Jalv* jalv) +jalv_frontend_open(Jalv* jalv) { - gtk_main_quit(); - return 0; + GtkWidget* window = gtk_window_new(GTK_WINDOW_TOPLEVEL); + jalv->window = window; + + s_jalv = jalv; + + g_signal_connect(window, "destroy", G_CALLBACK(on_window_destroy), jalv); + + set_window_title(jalv); + + GtkWidget* vbox = gtk_box_new(GTK_ORIENTATION_VERTICAL, 0); + + gtk_window_set_role(GTK_WINDOW(window), "plugin_ui"); + gtk_container_add(GTK_CONTAINER(window), vbox); + + if (!jalv->opts.no_menu) { + build_menu(jalv, window, vbox); + } + + // Create and show a box to contain the plugin UI + GtkWidget* ui_box = gtk_event_box_new(); + gtk_widget_set_halign(ui_box, GTK_ALIGN_FILL); + gtk_widget_set_hexpand(ui_box, TRUE); + gtk_widget_set_valign(ui_box, GTK_ALIGN_FILL); + gtk_widget_set_vexpand(ui_box, TRUE); + gtk_box_pack_start(GTK_BOX(vbox), ui_box, TRUE, TRUE, 0); + gtk_widget_show(ui_box); + gtk_widget_show(vbox); + + // Attempt to instantiate custom UI if necessary + if (jalv->ui && !jalv->opts.generic_ui) { + jalv_ui_instantiate(jalv, jalv_frontend_ui_type(), ui_box); + } + + jalv->features.request_value.request = on_request_value; + + if (jalv->ui_instance) { + GtkWidget* widget = (GtkWidget*)suil_instance_get_widget(jalv->ui_instance); + + gtk_container_add(GTK_CONTAINER(ui_box), widget); + gtk_window_set_resizable(GTK_WINDOW(window), + jalv_ui_is_resizable(jalv->world, jalv->ui)); + gtk_widget_show_all(vbox); + gtk_widget_grab_focus(widget); + } else { + GtkWidget* controls = build_control_widget(jalv, window); + GtkWidget* scroll_win = gtk_scrolled_window_new(NULL, NULL); + gtk_container_add(GTK_CONTAINER(scroll_win), controls); + gtk_scrolled_window_set_policy(GTK_SCROLLED_WINDOW(scroll_win), + GTK_POLICY_AUTOMATIC, + GTK_POLICY_AUTOMATIC); + gtk_container_add(GTK_CONTAINER(ui_box), scroll_win); + gtk_widget_set_margin_top(controls, 8); + gtk_widget_set_margin_bottom(controls, 8); + gtk_widget_show_all(vbox); + + GtkRequisition controls_size = {0, 0}; + GtkRequisition box_size = {0, 0}; + gtk_widget_get_preferred_size(GTK_WIDGET(controls), NULL, &controls_size); + gtk_widget_get_preferred_size(GTK_WIDGET(vbox), NULL, &box_size); + + gtk_window_set_default_size( + GTK_WINDOW(window), + MAX(MAX(box_size.width, controls_size.width) + 24, 640), + box_size.height + controls_size.height); + } + + jalv_init_ui(jalv); + + const float update_interval_ms = 1000.0f / jalv->settings.ui_update_hz; + g_timeout_add((unsigned)update_interval_ms, (GSourceFunc)jalv_update, jalv); + + gtk_window_present(GTK_WINDOW(window)); + + gtk_main(); + suil_instance_free(jalv->ui_instance); + + for (unsigned i = 0U; i < jalv->controls.n_controls; ++i) { + free(jalv->controls.controls[i]->widget); // free Controller + } + + jalv->ui_instance = NULL; + zix_sem_post(&jalv->done); + return 0; } -LV2_RESTORE_WARNINGS +int +jalv_frontend_close(Jalv* jalv) +{ + (void)jalv; + gtk_main_quit(); + s_jalv = NULL; + return 0; +} diff --git a/src/jalv_gtkmm2.cpp b/src/jalv_gtkmm2.cpp deleted file mode 100644 index 3f5a0e9..0000000 --- a/src/jalv_gtkmm2.cpp +++ /dev/null @@ -1,107 +0,0 @@ -/* - Copyright 2007-2016 David Robillard <http://drobilla.net> - - Permission to use, copy, modify, and/or distribute this software for any - purpose with or without fee is hereby granted, provided that the above - copyright notice and this permission notice appear in all copies. - - THIS SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES - WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF - MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR - ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES - WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN - ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF - OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. -*/ - -#include "jalv_internal.h" - -#include "lv2/core/attributes.h" - -LV2_DISABLE_DEPRECATION_WARNINGS -#include <gtkmm/button.h> -#include <gtkmm/main.h> -#include <gtkmm/window.h> -LV2_RESTORE_WARNINGS - -Gtk::Main* jalv_gtk_main = NULL; - -int -jalv_init(int* argc, char*** argv, JalvOptions* opts) -{ - jalv_gtk_main = new Gtk::Main(*argc, *argv); - return 0; -} - -const char* -jalv_native_ui_type(void) -{ - return "http://lv2plug.in/ns/extensions/ui#GtkUI"; -} - -void -jalv_ui_port_event(Jalv* jalv, - uint32_t port_index, - uint32_t buffer_size, - uint32_t protocol, - const void* buffer) -{ - if (jalv->ui_instance) { - suil_instance_port_event(jalv->ui_instance, port_index, - buffer_size, protocol, buffer); - } -} - -bool -jalv_discover_ui(Jalv* jalv) -{ - return true; -} - -float -jalv_ui_refresh_rate(Jalv* jalv) -{ - return 30.0f; -} - -int -jalv_open_ui(Jalv* jalv) -{ - Gtk::Window* window = new Gtk::Window(); - - if (jalv->ui) { - jalv_ui_instantiate(jalv, jalv_native_ui_type(), NULL); - } - - if (jalv->ui_instance) { - GtkWidget* widget = (GtkWidget*)suil_instance_get_widget( - jalv->ui_instance); - Gtk::Widget* widgetmm = Glib::wrap(widget); - window->add(*Gtk::manage(widgetmm)); - widgetmm->show_all(); - - g_timeout_add(1000 / jalv->ui_update_hz, - (GSourceFunc)jalv_update, jalv); - } else { - Gtk::Button* button = Gtk::manage(new Gtk::Button("Close")); - window->add(*Gtk::manage(button)); - } - - window->set_resizable(jalv_ui_is_resizable(jalv)); - window->show_all(); - - Gtk::Main::run(*window); - - delete window; - delete jalv_gtk_main; - zix_sem_post(&jalv->done); - - return 0; -} - -int -jalv_close_ui(Jalv* jalv) -{ - Gtk::Main::quit(); - return 0; -} diff --git a/src/jalv_internal.h b/src/jalv_internal.h deleted file mode 100644 index 4d25109..0000000 --- a/src/jalv_internal.h +++ /dev/null @@ -1,558 +0,0 @@ -/* - Copyright 2007-2016 David Robillard <http://drobilla.net> - - Permission to use, copy, modify, and/or distribute this software for any - purpose with or without fee is hereby granted, provided that the above - copyright notice and this permission notice appear in all copies. - - THIS SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES - WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF - MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR - ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES - WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN - ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF - OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. -*/ - -#ifndef JALV_INTERNAL_H -#define JALV_INTERNAL_H - -#include "lv2_evbuf.h" -#include "symap.h" - -#include "zix/ring.h" -#include "zix/sem.h" -#include "zix/thread.h" - -#include "lilv/lilv.h" -#include "serd/serd.h" -#include "sratom/sratom.h" -#ifdef HAVE_SUIL -#include "suil/suil.h" -#endif - -#include "lv2/atom/atom.h" -#include "lv2/atom/forge.h" -#include "lv2/data-access/data-access.h" -#include "lv2/log/log.h" -#include "lv2/midi/midi.h" -#include "lv2/options/options.h" -#include "lv2/resize-port/resize-port.h" -#include "lv2/state/state.h" -#include "lv2/urid/urid.h" -#include "lv2/worker/worker.h" - -#include <stdio.h> -#include <stdlib.h> -#include <string.h> -#ifdef HAVE_ISATTY -# include <unistd.h> -#endif - -#ifdef __clang__ -# define REALTIME __attribute__((annotate("realtime"))) -#else -# define REALTIME -#endif - -#ifdef __cplusplus -extern "C" { -#endif - -typedef struct JalvBackend JalvBackend; - -typedef struct Jalv Jalv; - -enum PortFlow { - FLOW_UNKNOWN, - FLOW_INPUT, - FLOW_OUTPUT -}; - -enum PortType { - TYPE_UNKNOWN, - TYPE_CONTROL, - TYPE_AUDIO, - TYPE_EVENT, - TYPE_CV -}; - -struct Port { - const LilvPort* lilv_port; ///< LV2 port - enum PortType type; ///< Data type - enum PortFlow flow; ///< Data flow direction - void* sys_port; ///< For audio/MIDI ports, otherwise NULL - LV2_Evbuf* evbuf; ///< For MIDI ports, otherwise NULL - void* widget; ///< Control widget, if applicable - size_t buf_size; ///< Custom buffer size, or 0 - uint32_t index; ///< Port index - float control; ///< For control ports, otherwise 0.0f -}; - -/* Controls */ - -/** Type of plugin control. */ -typedef enum { - PORT, ///< Control port - PROPERTY ///< Property (set via atom message) -} ControlType; - -typedef struct { - float value; - char* label; -} ScalePoint; - -/** Order scale points by value. */ -int scale_point_cmp(const ScalePoint* a, const ScalePoint* b); - -/** Plugin control. */ -typedef struct { - Jalv* jalv; - ControlType type; - LilvNode* node; - LilvNode* symbol; ///< Symbol - LilvNode* label; ///< Human readable label - LV2_URID property; ///< Iff type == PROPERTY - uint32_t index; ///< Iff type == PORT - LilvNode* group; ///< Port/control group, or NULL - void* widget; ///< Control Widget - size_t n_points; ///< Number of scale points - ScalePoint* points; ///< Scale points - LV2_URID value_type; ///< Type of control value - LilvNode* min; ///< Minimum value - LilvNode* max; ///< Maximum value - LilvNode* def; ///< Default value - bool is_toggle; ///< Boolean (0 and 1 only) - bool is_integer; ///< Integer values only - bool is_enumeration; ///< Point values only - bool is_logarithmic; ///< Logarithmic scale - bool is_writable; ///< Writable (input) - bool is_readable; ///< Readable (output) -} ControlID; - -ControlID* -new_port_control(Jalv* jalv, uint32_t index); - -ControlID* -new_property_control(Jalv* jalv, const LilvNode* property); - -typedef struct { - size_t n_controls; - ControlID** controls; -} Controls; - -void -add_control(Controls* controls, ControlID* control); - -ControlID* -get_property_control(const Controls* controls, LV2_URID property); - -/** - Control change event, sent through ring buffers for UI updates. -*/ -typedef struct { - uint32_t index; - uint32_t protocol; - uint32_t size; - uint8_t body[]; -} ControlChange; - -typedef struct { - char* name; ///< Client name - int name_exact; ///< Exit if name is taken - char* uuid; ///< Session UUID - char* load; ///< Path for state to load - char* preset; ///< URI of preset to load - char** controls; ///< Control values - uint32_t buffer_size; ///< Plugin <= >UI communication buffer size - double update_rate; ///< UI update rate in Hz - int dump; ///< Dump communication iff true - int trace; ///< Print trace log iff true - int generic_ui; ///< Use generic UI iff true - int show_hidden; ///< Show controls for notOnGUI ports - int no_menu; ///< Hide menu iff true - int show_ui; ///< Show non-embedded UI - int print_controls; ///< Print control changes to stdout - int non_interactive; ///< Do not listen for commands on stdin -} JalvOptions; - -typedef struct { - LV2_URID atom_Float; - LV2_URID atom_Int; - LV2_URID atom_Object; - LV2_URID atom_Path; - LV2_URID atom_String; - LV2_URID atom_eventTransfer; - LV2_URID bufsz_maxBlockLength; - LV2_URID bufsz_minBlockLength; - LV2_URID bufsz_sequenceSize; - LV2_URID log_Error; - LV2_URID log_Trace; - LV2_URID log_Warning; - LV2_URID midi_MidiEvent; - LV2_URID param_sampleRate; - LV2_URID patch_Get; - LV2_URID patch_Put; - LV2_URID patch_Set; - LV2_URID patch_body; - LV2_URID patch_property; - LV2_URID patch_value; - LV2_URID time_Position; - LV2_URID time_bar; - LV2_URID time_barBeat; - LV2_URID time_beatUnit; - LV2_URID time_beatsPerBar; - LV2_URID time_beatsPerMinute; - LV2_URID time_frame; - LV2_URID time_speed; - LV2_URID ui_updateRate; -} JalvURIDs; - -typedef struct { - LilvNode* atom_AtomPort; - LilvNode* atom_Chunk; - LilvNode* atom_Float; - LilvNode* atom_Path; - LilvNode* atom_Sequence; - LilvNode* lv2_AudioPort; - LilvNode* lv2_CVPort; - LilvNode* lv2_ControlPort; - LilvNode* lv2_InputPort; - LilvNode* lv2_OutputPort; - LilvNode* lv2_connectionOptional; - LilvNode* lv2_control; - LilvNode* lv2_default; - LilvNode* lv2_enumeration; - LilvNode* lv2_integer; - LilvNode* lv2_maximum; - LilvNode* lv2_minimum; - LilvNode* lv2_name; - LilvNode* lv2_reportsLatency; - LilvNode* lv2_sampleRate; - LilvNode* lv2_symbol; - LilvNode* lv2_toggled; - LilvNode* midi_MidiEvent; - LilvNode* pg_group; - LilvNode* pprops_logarithmic; - LilvNode* pprops_notOnGUI; - LilvNode* pprops_rangeSteps; - LilvNode* pset_Preset; - LilvNode* pset_bank; - LilvNode* rdfs_comment; - LilvNode* rdfs_label; - LilvNode* rdfs_range; - LilvNode* rsz_minimumSize; - LilvNode* work_interface; - LilvNode* work_schedule; - LilvNode* end; ///< NULL terminator for easy freeing of entire structure -} JalvNodes; - -typedef enum { - JALV_RUNNING, - JALV_PAUSE_REQUESTED, - JALV_PAUSED -} JalvPlayState; - -typedef struct { - Jalv* jalv; ///< Pointer back to Jalv - ZixRing* requests; ///< Requests to the worker - ZixRing* responses; ///< Responses from the worker - void* response; ///< Worker response buffer - ZixSem sem; ///< Worker semaphore - ZixThread thread; ///< Worker thread - const LV2_Worker_Interface* iface; ///< Plugin worker interface - bool threaded; ///< Run work in another thread -} JalvWorker; - -typedef struct { - LV2_Feature map_feature; - LV2_Feature unmap_feature; - LV2_State_Make_Path make_path; - LV2_Feature make_path_feature; - LV2_Worker_Schedule sched; - LV2_Feature sched_feature; - LV2_Worker_Schedule ssched; - LV2_Feature state_sched_feature; - LV2_Log_Log llog; - LV2_Feature log_feature; - LV2_Options_Option options[6]; - LV2_Feature options_feature; - LV2_Feature safe_restore_feature; - LV2_Extension_Data_Feature ext_data; -} JalvFeatures; - -struct Jalv { - JalvOptions opts; ///< Command-line options - JalvURIDs urids; ///< URIDs - JalvNodes nodes; ///< Nodes - LV2_Atom_Forge forge; ///< Atom forge - const char* prog_name; ///< Program name (argv[0]) - LilvWorld* world; ///< Lilv World - LV2_URID_Map map; ///< URI => Int map - LV2_URID_Unmap unmap; ///< Int => URI map - SerdEnv* env; ///< Environment for RDF printing - Sratom* sratom; ///< Atom serialiser - Sratom* ui_sratom; ///< Atom serialiser for UI thread - Symap* symap; ///< URI map - ZixSem symap_lock; ///< Lock for URI map - JalvBackend* backend; ///< Audio system backend - ZixRing* ui_events; ///< Port events from UI - ZixRing* plugin_events; ///< Port events from plugin - void* ui_event_buf; ///< Buffer for reading UI port events - JalvWorker worker; ///< Worker thread implementation - JalvWorker state_worker; ///< Synchronous worker for state restore - ZixSem work_lock; ///< Lock for plugin work() method - ZixSem done; ///< Exit semaphore - ZixSem paused; ///< Paused signal from process thread - JalvPlayState play_state; ///< Current play state - char* temp_dir; ///< Temporary plugin state directory - char* save_dir; ///< Plugin save directory - const LilvPlugin* plugin; ///< Plugin class (RDF data) - LilvState* preset; ///< Current preset - LilvUIs* uis; ///< All plugin UIs (RDF data) - const LilvUI* ui; ///< Plugin UI (RDF data) - const LilvNode* ui_type; ///< Plugin UI type (unwrapped) - LilvInstance* instance; ///< Plugin instance (shared library) -#ifdef HAVE_SUIL - SuilHost* ui_host; ///< Plugin UI host support - SuilInstance* ui_instance; ///< Plugin UI instance (shared library) -#endif - void* window; ///< Window (if applicable) - struct Port* ports; ///< Port array of size num_ports - Controls controls; ///< Available plugin controls - uint32_t block_length; ///< Audio buffer size (block length) - size_t midi_buf_size; ///< Size of MIDI port buffers - uint32_t control_in; ///< Index of control input port - uint32_t num_ports; ///< Size of the two following arrays: - uint32_t plugin_latency; ///< Latency reported by plugin (if any) - float ui_update_hz; ///< Frequency of UI updates - float sample_rate; ///< Sample rate - uint32_t event_delta_t; ///< Frames since last update sent to UI - uint32_t position; ///< Transport position in frames - float bpm; ///< Transport tempo in beats per minute - bool rolling; ///< Transport speed (0=stop, 1=play) - bool buf_size_set; ///< True iff buffer size callback fired - bool exit; ///< True iff execution is finished - bool has_ui; ///< True iff a control UI is present - bool request_update; ///< True iff a plugin update is needed - bool safe_restore; ///< Plugin restore() is thread-safe - JalvFeatures features; - const LV2_Feature** feature_list; -}; - -int -jalv_open(Jalv* jalv, int* argc, char*** argv); - -int -jalv_init(int* argc, char*** argv, JalvOptions* opts); - -int -jalv_close(Jalv* jalv); - -JalvBackend* -jalv_backend_init(Jalv* jalv); - -void -jalv_backend_activate(Jalv* jalv); - -void -jalv_backend_deactivate(Jalv* jalv); - -void -jalv_backend_close(Jalv* jalv); - -/** Expose a port to the system (if applicable) and connect it to its buffer. */ -void -jalv_backend_activate_port(Jalv* jalv, uint32_t port_index); - -void -jalv_create_ports(Jalv* jalv); - -void -jalv_allocate_port_buffers(Jalv* jalv); - -struct Port* -jalv_port_by_symbol(Jalv* jalv, const char* sym); - -void -jalv_create_controls(Jalv* jalv, bool writable); - -ControlID* -jalv_control_by_symbol(Jalv* jalv, const char* sym); - -void -jalv_set_control(const ControlID* control, - uint32_t size, - LV2_URID type, - const void* body); - -const char* -jalv_native_ui_type(void); - -bool -jalv_discover_ui(Jalv* jalv); - -float -jalv_ui_refresh_rate(Jalv* jalv); - -int -jalv_open_ui(Jalv* jalv); - -void -jalv_init_ui(Jalv* jalv); - -int -jalv_close_ui(Jalv* jalv); - -void -jalv_ui_instantiate(Jalv* jalv, - const char* native_ui_type, - void* parent); - -bool -jalv_ui_is_resizable(Jalv* jalv); - -void -jalv_ui_write(void* const controller, - uint32_t port_index, - uint32_t buffer_size, - uint32_t protocol, - const void* buffer); - -void -jalv_apply_ui_events(Jalv* jalv, uint32_t nframes); - -uint32_t -jalv_ui_port_index(void* const controller, const char* symbol); - -void -jalv_ui_port_event(Jalv* jalv, - uint32_t port_index, - uint32_t buffer_size, - uint32_t protocol, - const void* buffer); - -bool -jalv_send_to_ui(Jalv* jalv, - uint32_t port_index, - uint32_t type, - uint32_t size, - const void* body); -bool -jalv_run(Jalv* jalv, uint32_t nframes); - -int -jalv_update(Jalv* jalv); - -typedef int (*PresetSink)(Jalv* jalv, - const LilvNode* node, - const LilvNode* title, - void* data); - -int -jalv_load_presets(Jalv* jalv, PresetSink sink, void* data); - -int -jalv_unload_presets(Jalv* jalv); - -int -jalv_apply_preset(Jalv* jalv, const LilvNode* preset); - -int -jalv_delete_current_preset(Jalv* jalv); - -int -jalv_save_preset(Jalv* jalv, - const char* dir, - const char* uri, - const char* label, - const char* filename); - -void -jalv_save(Jalv* jalv, const char* dir); - -void -jalv_save_port_values(Jalv* jalv, - SerdWriter* writer, - const SerdNode* subject); -char* -jalv_make_path(LV2_State_Make_Path_Handle handle, - const char* path); - -void -jalv_apply_state(Jalv* jalv, LilvState* state); - -char* -atom_to_turtle(LV2_URID_Unmap* unmap, - const SerdNode* subject, - const SerdNode* predicate, - const LV2_Atom* atom); - -static inline void -jalv_print_control(Jalv* jalv, const struct Port* port, float value) -{ - const LilvNode* sym = lilv_port_get_symbol(jalv->plugin, port->lilv_port); - printf("%s = %f\n", lilv_node_as_string(sym), value); -} - -static inline char* -jalv_strdup(const char* str) -{ - const size_t len = strlen(str); - char* copy = (char*)malloc(len + 1); - memcpy(copy, str, len + 1); - return copy; -} - -static inline char* -jalv_strjoin(const char* a, const char* b) -{ - const size_t a_len = strlen(a); - const size_t b_len = strlen(b); - char* const out = (char*)malloc(a_len + b_len + 1); - - memcpy(out, a, a_len); - memcpy(out + a_len, b, b_len); - out[a_len + b_len] = '\0'; - - return out; -} - -int -jalv_printf(LV2_Log_Handle handle, - LV2_URID type, - const char* fmt, ...); - -int -jalv_vprintf(LV2_Log_Handle handle, - LV2_URID type, - const char* fmt, - va_list ap); - -static inline bool -jalv_ansi_start(FILE* stream, int color) -{ -#if defined(HAVE_ISATTY) && defined(HAVE_FILENO) - if (isatty(fileno(stream))) { - return fprintf(stream, "\033[0;%dm", color); - } -#endif - return 0; -} - -static inline void -jalv_ansi_reset(FILE* stream) -{ -#ifdef HAVE_ISATTY - if (isatty(fileno(stream))) { - fprintf(stream, "\033[0m"); - fflush(stream); - } -#endif -} - -#ifdef __cplusplus -} // extern "C" -#endif - -#endif // JALV_INTERNAL_H diff --git a/src/jalv_qt.cpp b/src/jalv_qt.cpp index f23a005..7d99118 100644 --- a/src/jalv_qt.cpp +++ b/src/jalv_qt.cpp @@ -1,757 +1,730 @@ -/* - Copyright 2007-2016 David Robillard <http://drobilla.net> - - Permission to use, copy, modify, and/or distribute this software for any - purpose with or without fee is hereby granted, provided that the above - copyright notice and this permission notice appear in all copies. - - THIS SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES - WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF - MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR - ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES - WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN - ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF - OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. -*/ - -#include "jalv_internal.h" - -#include "lv2/patch/patch.h" -#include "lv2/port-props/port-props.h" - -#include <qglobal.h> - -#if QT_VERSION >= 0x050000 -# include <QAction> -# include <QApplication> -# include <QDial> -# include <QGroupBox> -# include <QLabel> -# include <QLayout> -# include <QMainWindow> -# include <QMenu> -# include <QMenuBar> -# include <QScreen> -# include <QScrollArea> -# include <QStyle> -# include <QTimer> -# include <QWidget> -# include <QWindow> -#else -# include <QtGui> -#endif +// Copyright 2007-2022 David Robillard <d@drobilla.net> +// SPDX-License-Identifier: ISC + +#include "jalv_qt.hpp" +#include "comm.h" +#include "frontend.h" +#include "jalv.h" +#include "nodes.h" +#include "options.h" +#include "port.h" +#include "query.h" +#include "state.h" +#include "types.h" + +#include <lilv/lilv.h> +#include <suil/suil.h> +#include <zix/sem.h> + +#include <QAction> +#include <QApplication> +#include <QDial> +#include <QFontMetrics> +#include <QGroupBox> +#include <QGuiApplication> +#include <QHBoxLayout> +#include <QKeySequence> +#include <QLabel> +#include <QLayout> +#include <QLayoutItem> +#include <QList> +#include <QMainWindow> +#include <QMargins> +#include <QMenu> +#include <QMenuBar> +#include <QObject> +#include <QPoint> +#include <QRect> +#include <QScreen> +#include <QScrollArea> +#include <QSize> +#include <QSizePolicy> +#include <QString> +#include <QStyle> +#include <QTimer> +#include <QVBoxLayout> +#include <QWidget> +#include <QtCore> +#include <QtGlobal> #include <algorithm> #include <cmath> -#include <cstdio> +#include <cstdint> +#include <cstring> +#include <map> +#include <vector> + +constexpr int CONTROL_WIDTH = 150; +constexpr int DIAL_STEPS = 10000; -#define CONTROL_WIDTH 150 -#define DIAL_STEPS 10000 +namespace { -static QApplication* app = NULL; +QApplication* app = nullptr; -class FlowLayout : public QLayout +class FlowLayout final : public QLayout { public: - FlowLayout(QWidget* parent, - int margin = -1, - int hSpacing = -1, - int vSpacing = -1); - - FlowLayout(int margin = -1, int hSpacing = -1, int vSpacing = -1); - - ~FlowLayout(); - - void addItem(QLayoutItem* item); - int horizontalSpacing() const; - int verticalSpacing() const; - Qt::Orientations expandingDirections() const; - bool hasHeightForWidth() const; - int heightForWidth(int) const; - int count() const; - QLayoutItem* itemAt(int index) const; - QSize minimumSize() const; - void setGeometry(const QRect &rect); - QSize sizeHint() const; - QLayoutItem* takeAt(int index); + explicit FlowLayout(int margin, int hSpacing, int vSpacing); + + FlowLayout(const FlowLayout&) = delete; + FlowLayout& operator=(const FlowLayout&) = delete; + + FlowLayout(FlowLayout&&) = delete; + FlowLayout&& operator=(FlowLayout&&) = delete; + + ~FlowLayout() override; + + void addItem(QLayoutItem* item) override; + int horizontalSpacing() const; + int verticalSpacing() const; + Qt::Orientations expandingDirections() const override; + bool hasHeightForWidth() const override; + int heightForWidth(int) const override; + int count() const override; + QLayoutItem* itemAt(int index) const override; + QSize minimumSize() const override; + void setGeometry(const QRect& rect) override; + QSize sizeHint() const override; + QLayoutItem* takeAt(int index) override; private: - int doLayout(const QRect &rect, bool testOnly) const; - int smartSpacing(QStyle::PixelMetric pm) const; + int doLayout(const QRect& rect, bool testOnly) const; + int smartSpacing(QStyle::PixelMetric pm) const; - QList<QLayoutItem*> itemList; - int m_hSpace; - int m_vSpace; + QList<QLayoutItem*> _itemList; + int _hSpace; + int _vSpace; }; -FlowLayout::FlowLayout(QWidget* parent, int margin, int hSpacing, int vSpacing) - : QLayout(parent), m_hSpace(hSpacing), m_vSpace(vSpacing) -{ - setContentsMargins(margin, margin, margin, margin); -} - FlowLayout::FlowLayout(int margin, int hSpacing, int vSpacing) - : m_hSpace(hSpacing), m_vSpace(vSpacing) + : _hSpace(hSpacing) + , _vSpace(vSpacing) { - setContentsMargins(margin, margin, margin, margin); + setContentsMargins(margin, margin, margin, margin); } FlowLayout::~FlowLayout() { - QLayoutItem* item; - while ((item = takeAt(0))) { - delete item; - } + QLayoutItem* item = nullptr; + while ((item = takeAt(0))) { + delete item; + } } void FlowLayout::addItem(QLayoutItem* item) { - itemList.append(item); + _itemList.append(item); } int FlowLayout::horizontalSpacing() const { - if (m_hSpace >= 0) { - return m_hSpace; - } else { - return smartSpacing(QStyle::PM_LayoutHorizontalSpacing); - } + if (_hSpace >= 0) { + return _hSpace; + } + + return smartSpacing(QStyle::PM_LayoutHorizontalSpacing); } int FlowLayout::verticalSpacing() const { - if (m_vSpace >= 0) { - return m_vSpace; - } else { - return smartSpacing(QStyle::PM_LayoutVerticalSpacing); - } + if (_vSpace >= 0) { + return _vSpace; + } + + return smartSpacing(QStyle::PM_LayoutVerticalSpacing); } int FlowLayout::count() const { - return itemList.size(); + return _itemList.size(); } QLayoutItem* FlowLayout::itemAt(int index) const { - return itemList.value(index); + return _itemList.value(index); } QLayoutItem* FlowLayout::takeAt(int index) { - if (index >= 0 && index < itemList.size()) { - return itemList.takeAt(index); - } else { - return 0; - } + if (index >= 0 && index < _itemList.size()) { + return _itemList.takeAt(index); + } + + return nullptr; } Qt::Orientations FlowLayout::expandingDirections() const { - return 0; + return {}; } bool FlowLayout::hasHeightForWidth() const { - return true; + return true; } int FlowLayout::heightForWidth(int width) const { - return doLayout(QRect(0, 0, width, 0), true); + return doLayout(QRect(0, 0, width, 0), true); } void -FlowLayout::setGeometry(const QRect &rect) +FlowLayout::setGeometry(const QRect& rect) { - QLayout::setGeometry(rect); - doLayout(rect, false); + QLayout::setGeometry(rect); + doLayout(rect, false); } QSize FlowLayout::sizeHint() const { - return minimumSize(); + return minimumSize(); } QSize FlowLayout::minimumSize() const { - QSize size; - QLayoutItem* item; - foreach (item, itemList) { - size = size.expandedTo(item->minimumSize()); - } + QSize size = {}; + for (QLayoutItem* const item : _itemList) { + size = size.expandedTo(item->minimumSize()); + } - return size + QSize(2 * margin(), 2 * margin()); + const auto m = contentsMargins(); + return size + QSize{m.left() + m.right(), m.top() + m.bottom()}; } int -FlowLayout::doLayout(const QRect &rect, bool testOnly) const -{ - int left, top, right, bottom; - getContentsMargins(&left, &top, &right, &bottom); - - QRect effectiveRect = rect.adjusted(+left, +top, -right, -bottom); - int x = effectiveRect.x(); - int y = effectiveRect.y(); - int lineHeight = 0; - - QLayoutItem* item; - foreach (item, itemList) { - QWidget* wid = item->widget(); - - int spaceX = horizontalSpacing(); - if (spaceX == -1) { - spaceX = wid->style()->layoutSpacing(QSizePolicy::PushButton, - QSizePolicy::PushButton, - Qt::Horizontal); - } - int spaceY = verticalSpacing(); - if (spaceY == -1) { - spaceY = wid->style()->layoutSpacing(QSizePolicy::PushButton, - QSizePolicy::PushButton, - Qt::Vertical); - } - - int nextX = x + item->sizeHint().width() + spaceX; - if (nextX - spaceX > effectiveRect.right() && lineHeight > 0) { - x = effectiveRect.x(); - y = y + lineHeight + spaceY; - nextX = x + item->sizeHint().width() + spaceX; - lineHeight = 0; - } - - if (!testOnly) { - item->setGeometry(QRect(QPoint(x, y), item->sizeHint())); - } - - x = nextX; - lineHeight = qMax(lineHeight, item->sizeHint().height()); - } - return y + lineHeight - rect.y() + bottom; +FlowLayout::doLayout(const QRect& rect, bool testOnly) const +{ + int left = 0; + int top = 0; + int right = 0; + int bottom = 0; + getContentsMargins(&left, &top, &right, &bottom); + + const QRect effectiveRect = rect.adjusted(+left, +top, -right, -bottom); + int x = effectiveRect.x(); + int y = effectiveRect.y(); + int lineHeight = 0; + + for (QLayoutItem* const item : _itemList) { + QWidget* wid = item->widget(); + + int spaceX = horizontalSpacing(); + if (spaceX == -1) { + spaceX = wid->style()->layoutSpacing(QSizePolicy::PushButton, + QSizePolicy::PushButton, + Qt::Horizontal, + nullptr, + nullptr); + } + int spaceY = verticalSpacing(); + if (spaceY == -1) { + spaceY = wid->style()->layoutSpacing(QSizePolicy::PushButton, + QSizePolicy::PushButton, + Qt::Vertical, + nullptr, + nullptr); + } + + int nextX = x + item->sizeHint().width() + spaceX; + if (nextX - spaceX > effectiveRect.right() && lineHeight > 0) { + x = effectiveRect.x(); + y = y + lineHeight + spaceY; + nextX = x + item->sizeHint().width() + spaceX; + lineHeight = 0; + } + + if (!testOnly) { + item->setGeometry(QRect(QPoint(x, y), item->sizeHint())); + } + + x = nextX; + lineHeight = qMax(lineHeight, item->sizeHint().height()); + } + return y + lineHeight - rect.y() + bottom; } int FlowLayout::smartSpacing(QStyle::PixelMetric pm) const { - QObject* parent = this->parent(); - if (!parent) { - return -1; - } else if (parent->isWidgetType()) { - QWidget* pw = static_cast<QWidget*>(parent); - return pw->style()->pixelMetric(pm, 0, pw); - } else { - return static_cast<QLayout*>(parent)->spacing(); - } -} - -class PresetAction : public QAction -{ - Q_OBJECT - -public: - PresetAction(QObject* parent, Jalv* jalv, LilvNode* preset) - : QAction(parent) - , _jalv(jalv) - , _preset(preset) - { - connect(this, SIGNAL(triggered()), - this, SLOT(presetChosen())); - } - - Q_SLOT void presetChosen() { - jalv_apply_preset(_jalv, _preset); - } + QObject* const parent = this->parent(); + if (!parent) { + return -1; + } -private: - Jalv* _jalv; - LilvNode* _preset; -}; + auto* const parentWidget = qobject_cast<QWidget*>(parent); + if (parentWidget) { + return parentWidget->style()->pixelMetric(pm, nullptr, parentWidget); + } -typedef struct { - Jalv* jalv; - struct Port* port; -} PortContainer; + auto* const parentLayout = qobject_cast<QLayout*>(parent); + if (parentLayout) { + return parentLayout->spacing(); + } -class Control : public QGroupBox -{ - Q_OBJECT - -public: - Control(PortContainer portContainer, QWidget* parent = 0); - - Q_SLOT void dialChanged(int value); - - void setValue(float value); - - QDial* dial; - -private: - void setRange(float min, float max); - QString getValueLabel(float value); - float getValue(); - int stringWidth(const QString& str); - - const LilvPlugin* plugin; - struct Port* port; - - QLabel* label; - QString name; - int steps; - float max; - float min; - bool isInteger; - bool isEnum; - bool isLogarithmic; - - std::vector<float> scalePoints; - std::map<float, const char*> scaleMap; -}; - -#if QT_VERSION >= 0x050000 -# include "jalv_qt5_meta.hpp" -#else -# include "jalv_qt4_meta.hpp" -#endif - -extern "C" { - -int -jalv_init(int* argc, char*** argv, JalvOptions* opts) -{ - app = new QApplication(*argc, *argv, true); - app->setStyleSheet("QGroupBox::title { subcontrol-position: top center }"); - - return 0; -} - -const char* -jalv_native_ui_type(void) -{ -#if QT_VERSION >= 0x050000 - return "http://lv2plug.in/ns/extensions/ui#Qt5UI"; -#else - return "http://lv2plug.in/ns/extensions/ui#Qt4UI"; -#endif -} - -void -jalv_ui_port_event(Jalv* jalv, - uint32_t port_index, - uint32_t buffer_size, - uint32_t protocol, - const void* buffer) -{ - if (jalv->ui_instance) { - suil_instance_port_event(jalv->ui_instance, port_index, - buffer_size, protocol, buffer); - } else { - Control* control = (Control*)jalv->ports[port_index].widget; - if (control) { - control->setValue(*(const float*)buffer); - } - } + return -1; } class Timer : public QTimer { public: - explicit Timer(Jalv* jalv) : _jalv(jalv) {} + explicit Timer(Jalv* jalv) + : _jalv(jalv) + {} - void timerEvent(QTimerEvent* e) { - jalv_update(_jalv); - } + void timerEvent(QTimerEvent*) override { jalv_update(_jalv); } private: - Jalv* _jalv; + Jalv* _jalv; }; -static int +int add_preset_to_menu(Jalv* jalv, const LilvNode* node, const LilvNode* title, void* data) { - QMenu* menu = (QMenu*)data; - const char* label = lilv_node_as_string(title); + auto* const menu = static_cast<QMenu*>(data); + const char* label = lilv_node_as_string(title); - QAction* action = new PresetAction(menu, jalv, lilv_node_duplicate(node)); - action->setText(label); - menu->addAction(action); - return 0; + QAction* action = new PresetAction(menu, jalv, lilv_node_duplicate(node)); + action->setText(label); + menu->addAction(action); + return 0; } +} // namespace + Control::Control(PortContainer portContainer, QWidget* parent) - : QGroupBox(parent) - , dial(new QDial()) - , plugin(portContainer.jalv->plugin) - , port(portContainer.port) - , label(new QLabel()) -{ - JalvNodes* nodes = &portContainer.jalv->nodes; - const LilvPort* lilvPort = port->lilv_port; - - LilvNode* nmin; - LilvNode* nmax; - LilvNode* ndef; - lilv_port_get_range(plugin, lilvPort, &ndef, &nmin, &nmax); - - LilvNode* stepsNode = lilv_port_get(plugin, lilvPort, nodes->pprops_rangeSteps); - if (lilv_node_is_int(stepsNode)) { - steps = std::max(lilv_node_as_int(stepsNode), 2); - } else { - steps = DIAL_STEPS; - } - lilv_node_free(stepsNode); - - // Fill scalePoints Map - LilvScalePoints* sp = lilv_port_get_scale_points(plugin, lilvPort); - if (sp) { - LILV_FOREACH(scale_points, s, sp) { - const LilvScalePoint* p = lilv_scale_points_get(sp, s); - const LilvNode* val = lilv_scale_point_get_value(p); - if (!lilv_node_is_float(val) && !lilv_node_is_int(val)) { - continue; - } - - const float f = lilv_node_as_float(val); - scalePoints.push_back(f); - scaleMap[f] = lilv_node_as_string(lilv_scale_point_get_label(p)); - } - - lilv_scale_points_free(sp); - } - - // Check port properties - isLogarithmic = lilv_port_has_property(plugin, lilvPort, nodes->pprops_logarithmic); - isInteger = lilv_port_has_property(plugin, lilvPort, nodes->lv2_integer); - isEnum = lilv_port_has_property(plugin, lilvPort, nodes->lv2_enumeration); - - if (lilv_port_has_property(plugin, lilvPort, nodes->lv2_toggled)) { - isInteger = true; - - if (!scaleMap[0]) { - scaleMap[0] = "Off"; - } - if (!scaleMap[1]) { - scaleMap[1] = "On" ; - } - } - - // Find and set min, max and default values for port - float defaultValue = ndef ? lilv_node_as_float(ndef) : port->control; - setRange(lilv_node_as_float(nmin), lilv_node_as_float(nmax)); - setValue(defaultValue); - - // Fill layout - QVBoxLayout* layout = new QVBoxLayout(); - layout->addWidget(label, 0, Qt::AlignHCenter); - layout->addWidget(dial, 0, Qt::AlignHCenter); - setLayout(layout); - - setMinimumWidth(CONTROL_WIDTH); - setMaximumWidth(CONTROL_WIDTH); - - LilvNode* nname = lilv_port_get_name(plugin, lilvPort); - name = QString("%1").arg(lilv_node_as_string(nname)); - - // Handle long names - if (stringWidth(name) > CONTROL_WIDTH) { - setTitle(fontMetrics().elidedText(name, Qt::ElideRight, CONTROL_WIDTH)); - } else { - setTitle(name); - } - - // Set tooltip if comment is available - LilvNode* comment = lilv_port_get(plugin, lilvPort, nodes->rdfs_comment); - if (comment) { - QString* tooltip = new QString(); - tooltip->append(lilv_node_as_string(comment)); - setToolTip(*tooltip); - } - - setFlat(true); - - connect(dial, SIGNAL(valueChanged(int)), this, SLOT(dialChanged(int))); - - lilv_node_free(nmin); - lilv_node_free(nmax); - lilv_node_free(ndef); - lilv_node_free(nname); - lilv_node_free(comment); + : QGroupBox(parent) + , _dial(new QDial()) + , _jalv(portContainer.jalv) + , _port(portContainer.port) + , _label(new QLabel()) +{ + const JalvNodes* nodes = &portContainer.jalv->nodes; + const LilvPlugin* plugin = portContainer.jalv->plugin; + const LilvPort* lilvPort = _port->lilv_port; + + LilvNode* nmin = nullptr; + LilvNode* nmax = nullptr; + LilvNode* ndef = nullptr; + lilv_port_get_range(plugin, lilvPort, &ndef, &nmin, &nmax); + + LilvNode* stepsNode = + lilv_port_get(plugin, lilvPort, nodes->pprops_rangeSteps); + if (lilv_node_is_int(stepsNode)) { + _steps = std::max(lilv_node_as_int(stepsNode), 2); + } else { + _steps = DIAL_STEPS; + } + lilv_node_free(stepsNode); + + // Fill scalePoints Map + LilvScalePoints* sp = lilv_port_get_scale_points(plugin, lilvPort); + if (sp) { + LILV_FOREACH (scale_points, s, sp) { + const LilvScalePoint* p = lilv_scale_points_get(sp, s); + const LilvNode* val = lilv_scale_point_get_value(p); + if (!lilv_node_is_float(val) && !lilv_node_is_int(val)) { + continue; + } + + const float f = lilv_node_as_float(val); + _scalePoints.push_back(f); + _scaleMap[f] = lilv_node_as_string(lilv_scale_point_get_label(p)); + } + + lilv_scale_points_free(sp); + } + + // Check port properties + _isLogarithmic = + lilv_port_has_property(plugin, lilvPort, nodes->pprops_logarithmic); + _isInteger = lilv_port_has_property(plugin, lilvPort, nodes->lv2_integer); + _isEnum = lilv_port_has_property(plugin, lilvPort, nodes->lv2_enumeration); + + if (lilv_port_has_property(plugin, lilvPort, nodes->lv2_toggled)) { + _isInteger = true; + + if (!_scaleMap[0]) { + _scaleMap[0] = "Off"; + } + if (!_scaleMap[1]) { + _scaleMap[1] = "On"; + } + } + + // Find and set min, max and default values for port + const float defaultValue = + ndef ? lilv_node_as_float(ndef) + : portContainer.jalv->process.controls_buf[_port->index]; + setRange(lilv_node_as_float(nmin), lilv_node_as_float(nmax)); + setValue(defaultValue); + + // Fill layout + auto* const layout = new QVBoxLayout(); + layout->addWidget(_label, 0, Qt::AlignHCenter); + layout->addWidget(_dial, 0, Qt::AlignHCenter); + setLayout(layout); + + setMinimumWidth(CONTROL_WIDTH); + setMaximumWidth(CONTROL_WIDTH); + + LilvNode* nname = lilv_port_get_name(plugin, lilvPort); + _name = QString("%1").arg(lilv_node_as_string(nname)); + + // Handle long names + if (stringWidth(_name) > CONTROL_WIDTH) { + setTitle(fontMetrics().elidedText(_name, Qt::ElideRight, CONTROL_WIDTH)); + } else { + setTitle(_name); + } + + // Set tooltip if comment is available + LilvNode* comment = lilv_port_get(plugin, lilvPort, nodes->rdfs_comment); + if (comment) { + auto* const tooltip = new QString(); + tooltip->append(lilv_node_as_string(comment)); + setToolTip(*tooltip); + } + + setFlat(true); + + connect(_dial, SIGNAL(valueChanged(int)), this, SLOT(dialChanged(int))); + + lilv_node_free(nmin); + lilv_node_free(nmax); + lilv_node_free(ndef); + lilv_node_free(nname); + lilv_node_free(comment); } void Control::setValue(float value) { - float step; + float step = 0.0f; - if (isInteger) { - step = value; - } else if (isEnum) { - step = (std::find(scalePoints.begin(), scalePoints.end(), value) - - scalePoints.begin()); - } else if (isLogarithmic) { - step = steps * log(value / min) / log(max / min); - } else { - step = value * steps; - } + if (_isInteger) { + step = value; + } else if (_isEnum) { + step = (std::find(_scalePoints.begin(), _scalePoints.end(), value) - + _scalePoints.begin()); + } else if (_isLogarithmic) { + step = _steps * logf(value / _min) / logf(_max / _min); + } else { + step = value * _steps; + } - dial->setValue(step); - label->setText(getValueLabel(value)); + _dial->setValue(step); + _label->setText(getValueLabel(value)); } QString Control::getValueLabel(float value) { - if (scaleMap[value]) { - if (stringWidth(scaleMap[value]) > CONTROL_WIDTH) { - label->setToolTip(scaleMap[value]); - return fontMetrics().elidedText(QString(scaleMap[value]), - Qt::ElideRight, - CONTROL_WIDTH); - } - return scaleMap[value]; - } + if (_scaleMap[value]) { + if (stringWidth(_scaleMap[value]) > CONTROL_WIDTH) { + _label->setToolTip(_scaleMap[value]); + return fontMetrics().elidedText( + QString(_scaleMap[value]), Qt::ElideRight, CONTROL_WIDTH); + } + return _scaleMap[value]; + } - return QString("%1").arg(value); + return QString("%1").arg(value); } void Control::setRange(float minRange, float maxRange) { - min = minRange; - max = maxRange; + _min = minRange; + _max = maxRange; - if (isLogarithmic) { - minRange = 1; - maxRange = steps; - } else if (isEnum) { - minRange = 0; - maxRange = scalePoints.size() - 1; - } else if (!isInteger) { - minRange *= steps; - maxRange *= steps; - } + if (_isLogarithmic) { + minRange = 1; + maxRange = _steps; + } else if (_isEnum) { + minRange = 0; + maxRange = _scalePoints.size() - 1; + } else if (!_isInteger) { + minRange *= _steps; + maxRange *= _steps; + } - dial->setRange(minRange, maxRange); + _dial->setRange(minRange, maxRange); } float Control::getValue() { - if (isEnum) { - return scalePoints[dial->value()]; - } else if (isInteger) { - return dial->value(); - } else if (isLogarithmic) { - return min * pow(max / min, (float)dial->value() / (steps - 1)); - } else { - return (float)dial->value() / steps; - } + if (_isEnum) { + return _scalePoints[_dial->value()]; + } + + if (_isInteger) { + return _dial->value(); + } + + if (_isLogarithmic) { + return _min * + powf(_max / _min, static_cast<float>(_dial->value()) / (_steps - 1)); + } + + return static_cast<float>(_dial->value()) / _steps; } int Control::stringWidth(const QString& str) { #if QT_VERSION >= 0x050B00 - return fontMetrics().horizontalAdvance(str); + return fontMetrics().horizontalAdvance(str); #else - return fontMetrics().width(str); + return fontMetrics().width(str); #endif } void -Control::dialChanged(int dialValue) +Control::dialChanged(int) { - float value = getValue(); + const float value = getValue(); - label->setText(getValueLabel(value)); - port->control = value; + _label->setText(getValueLabel(value)); + jalv_write_control(_jalv->process.ui_to_plugin, _port->index, value); } -static bool -portGroupLessThan(const PortContainer &p1, const PortContainer &p2) +namespace { + +bool +portGroupLessThan(const PortContainer& p1, const PortContainer& p2) { - Jalv* jalv = p1.jalv; - const LilvPort* port1 = p1.port->lilv_port; - const LilvPort* port2 = p2.port->lilv_port; + const Jalv* jalv = p1.jalv; + const LilvPort* port1 = p1.port->lilv_port; + const LilvPort* port2 = p2.port->lilv_port; - LilvNode* group1 = lilv_port_get( - jalv->plugin, port1, jalv->nodes.pg_group); - LilvNode* group2 = lilv_port_get( - jalv->plugin, port2, jalv->nodes.pg_group); + LilvNode* group1 = lilv_port_get(jalv->plugin, port1, jalv->nodes.pg_group); + LilvNode* group2 = lilv_port_get(jalv->plugin, port2, jalv->nodes.pg_group); - const int cmp = (group1 && group2) - ? strcmp(lilv_node_as_string(group1), lilv_node_as_string(group2)) - : ((intptr_t)group1 - (intptr_t)group2); + const int cmp = (group1 && group2) ? strcmp(lilv_node_as_string(group1), + lilv_node_as_string(group2)) + : (reinterpret_cast<intptr_t>(group1) - + reinterpret_cast<intptr_t>(group2)); - lilv_node_free(group2); - lilv_node_free(group1); + lilv_node_free(group2); + lilv_node_free(group1); - return cmp < 0; + return cmp < 0; } -static QWidget* +QWidget* build_control_widget(Jalv* jalv) { - const LilvPlugin* plugin = jalv->plugin; - LilvWorld* world = jalv->world; - - QList<PortContainer> portContainers; - for (unsigned i = 0; i < jalv->num_ports; ++i) { - if (!jalv->opts.show_hidden && - lilv_port_has_property(plugin, jalv->ports[i].lilv_port, - jalv->nodes.pprops_notOnGUI)) { - continue; - } - - if (jalv->ports[i].type == TYPE_CONTROL) { - PortContainer portContainer; - portContainer.jalv = jalv; - portContainer.port = &jalv->ports[i]; - portContainers.append(portContainer); - } - } - - std::sort(portContainers.begin(), portContainers.end(), portGroupLessThan); - - QWidget* grid = new QWidget(); - FlowLayout* flowLayout = new FlowLayout(); - QLayout* layout = flowLayout; - - LilvNode* lastGroup = NULL; - QHBoxLayout* groupLayout = NULL; - for (int i = 0; i < portContainers.count(); ++i) { - PortContainer portContainer = portContainers[i]; - Port* port = portContainer.port; - - Control* control = new Control(portContainer); - LilvNode* group = lilv_port_get( - plugin, port->lilv_port, jalv->nodes.pg_group); - if (group) { - if (!lilv_node_equals(group, lastGroup)) { - /* Group has changed */ - LilvNode* groupName = lilv_world_get( - world, group, jalv->nodes.lv2_name, NULL); - if (!groupName) { - groupName = lilv_world_get( - world, group, jalv->nodes.rdfs_label, NULL); - } - - QGroupBox* groupBox = new QGroupBox(lilv_node_as_string(groupName)); - - groupLayout = new QHBoxLayout(); - groupBox->setLayout(groupLayout); - layout->addWidget(groupBox); - } - - groupLayout->addWidget(control); - } else { - layout->addWidget(control); - } - lilv_node_free(lastGroup); - lastGroup = group; - - uint32_t index = lilv_port_get_index(plugin, port->lilv_port); - jalv->ports[index].widget = control; - } - lilv_node_free(lastGroup); - - grid->setLayout(layout); - - return grid; + const LilvPlugin* plugin = jalv->plugin; + LilvWorld* world = jalv->world; + + QList<PortContainer> portContainers; + for (unsigned i = 0; i < jalv->num_ports; ++i) { + if (!jalv->opts.show_hidden && + lilv_port_has_property( + plugin, jalv->ports[i].lilv_port, jalv->nodes.pprops_notOnGUI)) { + continue; + } + + if (jalv->ports[i].type == TYPE_CONTROL) { + portContainers.append(PortContainer{jalv, &jalv->ports[i]}); + } + } + + std::sort(portContainers.begin(), portContainers.end(), portGroupLessThan); + + auto* const grid = new QWidget(); + auto* const flowLayout = new FlowLayout(-1, -1, -1); + QLayout* layout = flowLayout; + + LilvNode* lastGroup = nullptr; + QHBoxLayout* groupLayout = nullptr; + for (int i = 0; i < portContainers.count(); ++i) { + const PortContainer portContainer = portContainers[i]; + const JalvPort* const port = portContainer.port; + + auto* const control = new Control(portContainer, nullptr); + LilvNode* group = + lilv_port_get(plugin, port->lilv_port, jalv->nodes.pg_group); + if (group) { + if (!groupLayout || !lilv_node_equals(group, lastGroup)) { + // Group has changed + const LilvNode* groupName = + lilv_world_get(world, group, jalv->nodes.lv2_name, nullptr); + if (!groupName) { + groupName = + lilv_world_get(world, group, jalv->nodes.rdfs_label, nullptr); + } + + auto* const groupBox = new QGroupBox(lilv_node_as_string(groupName)); + + groupLayout = new QHBoxLayout(); + groupBox->setLayout(groupLayout); + layout->addWidget(groupBox); + } + + groupLayout->addWidget(control); + } else { + layout->addWidget(control); + } + lilv_node_free(lastGroup); + lastGroup = group; + + const uint32_t index = lilv_port_get_index(plugin, port->lilv_port); + jalv->ports[index].widget = control; + } + lilv_node_free(lastGroup); + + grid->setLayout(layout); + + return grid; +} + +} // namespace + +extern "C" { + +int +jalv_frontend_init(JalvFrontendArgs* const args, JalvOptions*) +{ + app = new QApplication(*args->argc, *args->argv, true); + app->setStyleSheet("QGroupBox::title { subcontrol-position: top center }"); + --*args->argc; + ++*args->argv; + return 0; +} + +const char* +jalv_frontend_ui_type(void) +{ +#if QT_VERSION < QT_VERSION_CHECK(6, 0, 0) + return "http://lv2plug.in/ns/extensions/ui#Qt5UI"; +#else + return "http://lv2plug.in/ns/extensions/ui#Qt6UI"; +#endif +} + +void +jalv_frontend_port_event(Jalv* jalv, + uint32_t port_index, + uint32_t buffer_size, + uint32_t protocol, + const void* buffer) +{ + if (jalv->ui_instance) { + suil_instance_port_event( + jalv->ui_instance, port_index, buffer_size, protocol, buffer); + } else { + auto* const control = static_cast<Control*>(jalv->ports[port_index].widget); + if (control) { + control->setValue(*static_cast<const float*>(buffer)); + } + } } bool -jalv_discover_ui(Jalv* jalv) +jalv_frontend_discover(const Jalv*) { - return true; + return true; } float -jalv_ui_refresh_rate(Jalv* jalv) +jalv_frontend_refresh_rate(const Jalv*) { -#if QT_VERSION >= 0x050000 - return (float)QGuiApplication::primaryScreen()->refreshRate(); -#else - return 30.0f; -#endif + return static_cast<float>(QGuiApplication::primaryScreen()->refreshRate()); +} + +float +jalv_frontend_scale_factor(const Jalv*) +{ + return static_cast<float>( + QGuiApplication::primaryScreen()->devicePixelRatio()); +} + +LilvNode* +jalv_frontend_select_plugin(Jalv*) +{ + return nullptr; } int -jalv_open_ui(Jalv* jalv) -{ - QMainWindow* win = new QMainWindow(); - QMenu* file_menu = win->menuBar()->addMenu("&File"); - QMenu* presets_menu = win->menuBar()->addMenu("&Presets"); - QAction* quit_action = new QAction("&Quit", win); - - QObject::connect(quit_action, SIGNAL(triggered()), win, SLOT(close())); - quit_action->setShortcuts(QKeySequence::Quit); - quit_action->setStatusTip("Quit Jalv"); - file_menu->addAction(quit_action); - - jalv_load_presets(jalv, add_preset_to_menu, presets_menu); - - if (jalv->ui && !jalv->opts.generic_ui) { - jalv_ui_instantiate(jalv, jalv_native_ui_type(), win); - } - - QWidget* widget; - if (jalv->ui_instance) { - widget = (QWidget*)suil_instance_get_widget(jalv->ui_instance); - } else { - QWidget* controlWidget = build_control_widget(jalv); - - widget = new QScrollArea(); - ((QScrollArea*)widget)->setWidget(controlWidget); - ((QScrollArea*)widget)->setWidgetResizable(true); - widget->setMinimumWidth(800); - widget->setMinimumHeight(600); - } - - LilvNode* name = lilv_plugin_get_name(jalv->plugin); - win->setWindowTitle(lilv_node_as_string(name)); - lilv_node_free(name); - - win->setCentralWidget(widget); - app->connect(app, SIGNAL(lastWindowClosed()), app, SLOT(quit())); - - win->show(); - if (jalv->ui_instance && !jalv_ui_is_resizable(jalv)) { - widget->setMinimumSize(widget->width(), widget->height()); - widget->setMaximumSize(widget->width(), widget->height()); - win->adjustSize(); - win->setFixedSize(win->width(), win->height()); - } else { - win->resize(widget->width(), - widget->height() + win->menuBar()->height()); - } - - Timer* timer = new Timer(jalv); - timer->start(1000 / jalv->ui_update_hz); - - int ret = app->exec(); - zix_sem_post(&jalv->done); - return ret; +jalv_frontend_open(Jalv* jalv) +{ + auto* const win = new QMainWindow(); + QMenu* file_menu = win->menuBar()->addMenu("&File"); + QMenu* presets_menu = win->menuBar()->addMenu("&Presets"); + auto* const quit_action = new QAction("&Quit", win); + + QObject::connect(quit_action, SIGNAL(triggered()), win, SLOT(close())); + quit_action->setShortcuts(QKeySequence::Quit); + quit_action->setStatusTip("Quit Jalv"); + file_menu->addAction(quit_action); + + jalv_load_presets(jalv, add_preset_to_menu, presets_menu); + + if (jalv->ui && !jalv->opts.generic_ui) { + jalv_ui_instantiate(jalv, jalv_frontend_ui_type(), win); + } + + QWidget* widget = nullptr; + if (jalv->ui_instance) { + widget = static_cast<QWidget*>(suil_instance_get_widget(jalv->ui_instance)); + } else { + auto* const controlWidget = build_control_widget(jalv); + auto* const scrollArea = new QScrollArea(); + scrollArea->setWidget(controlWidget); + scrollArea->setWidgetResizable(true); + scrollArea->setMinimumWidth(800); + scrollArea->setMinimumHeight(600); + widget = scrollArea; + } + + LilvNode* name = lilv_plugin_get_name(jalv->plugin); + win->setWindowTitle(lilv_node_as_string(name)); + lilv_node_free(name); + + win->setCentralWidget(widget); + app->connect(app, SIGNAL(lastWindowClosed()), app, SLOT(quit())); + + jalv_init_ui(jalv); + + win->show(); + if (jalv->ui_instance && !jalv_ui_is_resizable(jalv->world, jalv->ui)) { + widget->setMinimumSize(widget->width(), widget->height()); + widget->setMaximumSize(widget->width(), widget->height()); + win->adjustSize(); + win->setFixedSize(win->width(), win->height()); + } else { + win->resize(widget->width(), widget->height() + win->menuBar()->height()); + } + + auto* const timer = new Timer(jalv); + timer->start((int)(1000.0f / jalv->settings.ui_update_hz)); + + const int ret = app->exec(); + zix_sem_post(&jalv->done); + return ret; } int -jalv_close_ui(Jalv* jalv) +jalv_frontend_close(Jalv*) { - app->quit(); - return 0; + app->quit(); + return 0; } -} // extern "C" +} // extern "C" diff --git a/src/jalv_qt.hpp b/src/jalv_qt.hpp new file mode 100644 index 0000000..40f9af7 --- /dev/null +++ b/src/jalv_qt.hpp @@ -0,0 +1,80 @@ +// Copyright 2007-2022 David Robillard <d@drobilla.net> +// SPDX-License-Identifier: ISC + +#include "port.h" +#include "state.h" +#include "types.h" + +#include <lilv/lilv.h> + +#include <QAction> +#include <QGroupBox> +#include <QObject> +#include <QString> +#include <QtCore> + +#include <map> +#include <vector> + +class QDial; +class QLabel; +class QWidget; + +class PresetAction final : public QAction +{ + Q_OBJECT // NOLINT + +public: + PresetAction(QObject* parent, Jalv* jalv, LilvNode* preset) + : QAction(parent) + , _jalv(jalv) + , _preset(preset) + { + connect(this, SIGNAL(triggered()), this, SLOT(presetChosen())); + } + + Q_SLOT void presetChosen() { jalv_apply_preset(_jalv, _preset); } + +private: + Jalv* _jalv; + LilvNode* _preset; +}; + +struct PortContainer { + Jalv* jalv; + JalvPort* port; +}; + +class Control final : public QGroupBox +{ + Q_OBJECT // NOLINT + +public: + explicit Control(PortContainer portContainer, QWidget* parent); + + Q_SLOT void dialChanged(int value); + + void setValue(float value); + +private: + void setRange(float min, float max); + QString getValueLabel(float value); + float getValue(); + int stringWidth(const QString& str); + + QDial* _dial; + Jalv* _jalv; + JalvPort* _port; + + QLabel* _label; + QString _name; + int _steps; + float _max{1.0f}; + float _min{0.0f}; + bool _isInteger{}; + bool _isEnum{}; + bool _isLogarithmic{}; + + std::vector<float> _scalePoints; + std::map<float, const char*> _scaleMap; +}; @@ -1,60 +1,117 @@ -/* - Copyright 2007-2016 David Robillard <http://drobilla.net> +// Copyright 2007-2022 David Robillard <d@drobilla.net> +// SPDX-License-Identifier: ISC - Permission to use, copy, modify, and/or distribute this software for any - purpose with or without fee is hereby granted, provided that the above - copyright notice and this permission notice appear in all copies. +#include "log.h" - THIS SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES - WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF - MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR - ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES - WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN - ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF - OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. -*/ +#include "jalv_config.h" -#include "jalv_internal.h" +#include <lv2/log/log.h> +#include <lv2/urid/urid.h> + +#if USE_ISATTY +# include <unistd.h> +#endif + +#include <stdarg.h> +#include <stdbool.h> +#include <stdio.h> + +JALV_LOG_FUNC(2, 0) +static int +jalv_vlog(const JalvLogLevel level, const char* const fmt, va_list ap) +{ + bool fancy = false; + switch (level) { + case JALV_LOG_ERR: + fancy = jalv_ansi_start(stderr, 31); + fprintf(stderr, "error: "); + break; + case JALV_LOG_WARNING: + fancy = jalv_ansi_start(stderr, 33); + fprintf(stderr, "warning: "); + break; + case JALV_LOG_INFO: + break; + case JALV_LOG_DEBUG: + fancy = jalv_ansi_start(stderr, 32); + fprintf(stderr, "trace: "); + break; + } + + const int st = vfprintf(stderr, fmt, ap); + + if (fancy) { + jalv_ansi_reset(stderr); + } + + return st; +} + +int +jalv_log(const JalvLogLevel level, const char* const fmt, ...) +{ + va_list args; + va_start(args, fmt); + + const int ret = jalv_vlog(level, fmt, args); + + va_end(args); + return ret; +} int -jalv_printf(LV2_Log_Handle handle, - LV2_URID type, - const char* fmt, ...) +jalv_vprintf(LV2_Log_Handle handle, LV2_URID type, const char* fmt, va_list ap) { - va_list args; - va_start(args, fmt); - const int ret = jalv_vprintf(handle, type, fmt, args); - va_end(args); - return ret; + JalvLog* const log = (JalvLog*)handle; + + if (type == log->urids->log_Trace) { + return log->tracing ? jalv_vlog(JALV_LOG_DEBUG, fmt, ap) : 0; + } + + if (type == log->urids->log_Error) { + return jalv_vlog(JALV_LOG_ERR, fmt, ap); + } + + if (type == log->urids->log_Warning) { + return jalv_vlog(JALV_LOG_WARNING, fmt, ap); + } + + return vfprintf(stderr, fmt, ap); } int -jalv_vprintf(LV2_Log_Handle handle, - LV2_URID type, - const char* fmt, - va_list ap) +jalv_printf(LV2_Log_Handle handle, LV2_URID type, const char* fmt, ...) +{ + va_list args; + va_start(args, fmt); + const int ret = jalv_vprintf(handle, type, fmt, args); + va_end(args); + return ret; +} + +bool +jalv_ansi_start(FILE* stream, int color) +{ +#if USE_ISATTY && USE_FILENO + if (isatty(fileno(stream))) { + return fprintf(stream, "\033[0;%dm", color); + } +#else + (void)stream; + (void)color; +#endif + return 0; +} + +void +jalv_ansi_reset(FILE* stream) { - // TODO: Lock - Jalv* jalv = (Jalv*)handle; - bool fancy = true; - if (type == jalv->urids.log_Trace && jalv->opts.trace) { - jalv_ansi_start(stderr, 32); - fprintf(stderr, "trace: "); - } else if (type == jalv->urids.log_Error) { - jalv_ansi_start(stderr, 31); - fprintf(stderr, "error: "); - } else if (type == jalv->urids.log_Warning) { - jalv_ansi_start(stderr, 33); - fprintf(stderr, "warning: "); - } else { - fancy = false; - } - - const int st = vfprintf(stderr, fmt, ap); - - if (fancy) { - jalv_ansi_reset(stderr); - } - - return st; +#if USE_ISATTY + if (isatty(fileno(stream))) { + fprintf(stream, "\033[0m"); + fflush(stream); + } +#else + (void)stream; +#endif } diff --git a/src/log.h b/src/log.h new file mode 100644 index 0000000..b615d34 --- /dev/null +++ b/src/log.h @@ -0,0 +1,63 @@ +// Copyright 2007-2022 David Robillard <d@drobilla.net> +// SPDX-License-Identifier: ISC + +#ifndef JALV_LOG_H +#define JALV_LOG_H + +#include "attributes.h" +#include "urids.h" + +#include <lv2/log/log.h> +#include <lv2/urid/urid.h> + +#include <stdarg.h> +#include <stdbool.h> +#include <stdio.h> + +#ifdef __GNUC__ +# define JALV_LOG_FUNC(fmt, arg1) __attribute__((format(printf, fmt, arg1))) +#else +# define JALV_LOG_FUNC(fmt, arg1) +#endif + +// String and log utilities +JALV_BEGIN_DECLS + +typedef enum { + JALV_LOG_ERR = 3, + JALV_LOG_WARNING = 4, + JALV_LOG_INFO = 6, + JALV_LOG_DEBUG = 7, +} JalvLogLevel; + +typedef struct { + JalvURIDs* urids; + bool tracing; +} JalvLog; + +/// Print a log message to stderr with a GCC-like prefix and color +JALV_LOG_FUNC(2, 3) +int +jalv_log(JalvLogLevel level, const char* fmt, ...); + +/// LV2 log vprintf function +JALV_LOG_FUNC(3, 0) +int +jalv_vprintf(LV2_Log_Handle handle, LV2_URID type, const char* fmt, va_list ap); + +/// LV2 log printf function +JALV_LOG_FUNC(3, 4) +int +jalv_printf(LV2_Log_Handle handle, LV2_URID type, const char* fmt, ...); + +/// Write an ANSI escape sequence to set the foreground color +bool +jalv_ansi_start(FILE* stream, int color); + +/// Write an ANSI escape sequence to reset the foreground color +void +jalv_ansi_reset(FILE* stream); + +JALV_END_DECLS + +#endif // JALV_LOG_H diff --git a/src/lv2_evbuf.c b/src/lv2_evbuf.c index a64d860..cdb5dc2 100644 --- a/src/lv2_evbuf.c +++ b/src/lv2_evbuf.c @@ -1,125 +1,125 @@ -/* - Copyright 2008-2018 David Robillard <http://drobilla.net> - - Permission to use, copy, modify, and/or distribute this software for any - purpose with or without fee is hereby granted, provided that the above - copyright notice and this permission notice appear in all copies. - - THIS SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES - WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF - MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR - ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES - WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN - ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF - OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. -*/ +// Copyright 2008-2022 David Robillard <d@drobilla.net> +// SPDX-License-Identifier: ISC #include "lv2_evbuf.h" +#include "jalv_config.h" -#include "lv2/atom/atom.h" +#include <lv2/atom/atom.h> +#include <lv2/atom/util.h> #include <assert.h> #include <stdlib.h> #include <string.h> struct LV2_Evbuf_Impl { - uint32_t capacity; - uint32_t atom_Chunk; - uint32_t atom_Sequence; - LV2_Atom_Sequence buf; + uint32_t capacity; + uint32_t atom_Chunk; + uint32_t atom_Sequence; + uint32_t pad; // So buf has correct atom alignment + LV2_Atom_Sequence buf; }; -static inline uint32_t -lv2_evbuf_pad_size(uint32_t size) -{ - return (size + 7) & (~7); -} - LV2_Evbuf* lv2_evbuf_new(uint32_t capacity, uint32_t atom_Chunk, uint32_t atom_Sequence) { - // FIXME: memory must be 64-bit aligned - LV2_Evbuf* evbuf = (LV2_Evbuf*)malloc( - sizeof(LV2_Evbuf) + sizeof(LV2_Atom_Sequence) + capacity); - evbuf->capacity = capacity; - evbuf->atom_Chunk = atom_Chunk; - evbuf->atom_Sequence = atom_Sequence; - lv2_evbuf_reset(evbuf, true); - return evbuf; + const size_t buffer_size = + sizeof(LV2_Evbuf) + sizeof(LV2_Atom_Sequence) + capacity; + +#if USE_POSIX_MEMALIGN + LV2_Evbuf* evbuf = NULL; + const int st = posix_memalign((void**)&evbuf, 16, buffer_size); + if (st) { + return NULL; + } + + assert((uintptr_t)evbuf % 8U == 0U); +#else + LV2_Evbuf* evbuf = (LV2_Evbuf*)malloc(buffer_size); +#endif + + if (evbuf) { + memset(evbuf, 0, sizeof(*evbuf)); + evbuf->capacity = capacity; + evbuf->atom_Chunk = atom_Chunk; + evbuf->atom_Sequence = atom_Sequence; + } + + return evbuf; } void lv2_evbuf_free(LV2_Evbuf* evbuf) { - free(evbuf); + if (evbuf) { + free(evbuf); + } } void lv2_evbuf_reset(LV2_Evbuf* evbuf, bool input) { - if (input) { - evbuf->buf.atom.size = sizeof(LV2_Atom_Sequence_Body); - evbuf->buf.atom.type = evbuf->atom_Sequence; - } else { - evbuf->buf.atom.size = evbuf->capacity; - evbuf->buf.atom.type = evbuf->atom_Chunk; - } + if (input) { + evbuf->buf.atom.size = sizeof(LV2_Atom_Sequence_Body); + evbuf->buf.atom.type = evbuf->atom_Sequence; + } else { + evbuf->buf.atom.size = evbuf->capacity; + evbuf->buf.atom.type = evbuf->atom_Chunk; + } } uint32_t lv2_evbuf_get_size(LV2_Evbuf* evbuf) { - assert(evbuf->buf.atom.type != evbuf->atom_Sequence - || evbuf->buf.atom.size >= sizeof(LV2_Atom_Sequence_Body)); - return evbuf->buf.atom.type == evbuf->atom_Sequence - ? evbuf->buf.atom.size - sizeof(LV2_Atom_Sequence_Body) - : 0; + assert(evbuf->buf.atom.type != evbuf->atom_Sequence || + evbuf->buf.atom.size >= sizeof(LV2_Atom_Sequence_Body)); + return evbuf->buf.atom.type == evbuf->atom_Sequence + ? evbuf->buf.atom.size - sizeof(LV2_Atom_Sequence_Body) + : 0; } void* lv2_evbuf_get_buffer(LV2_Evbuf* evbuf) { - return &evbuf->buf; + return &evbuf->buf; } LV2_Evbuf_Iterator lv2_evbuf_begin(LV2_Evbuf* evbuf) { - LV2_Evbuf_Iterator iter = { evbuf, 0 }; - return iter; + LV2_Evbuf_Iterator iter = {evbuf, 0}; + return iter; } LV2_Evbuf_Iterator lv2_evbuf_end(LV2_Evbuf* evbuf) { - const uint32_t size = lv2_evbuf_get_size(evbuf); - const LV2_Evbuf_Iterator iter = { evbuf, lv2_evbuf_pad_size(size) }; - return iter; + const uint32_t size = lv2_evbuf_get_size(evbuf); + const LV2_Evbuf_Iterator iter = {evbuf, lv2_atom_pad_size(size)}; + return iter; } bool lv2_evbuf_is_valid(LV2_Evbuf_Iterator iter) { - return iter.offset < lv2_evbuf_get_size(iter.evbuf); + return iter.offset < lv2_evbuf_get_size(iter.evbuf); } LV2_Evbuf_Iterator -lv2_evbuf_next(LV2_Evbuf_Iterator iter) +lv2_evbuf_next(const LV2_Evbuf_Iterator iter) { - if (!lv2_evbuf_is_valid(iter)) { - return iter; - } - - LV2_Evbuf* evbuf = iter.evbuf; - uint32_t offset = iter.offset; - uint32_t size; - size = ((LV2_Atom_Event*) - ((char*)LV2_ATOM_CONTENTS(LV2_Atom_Sequence, &evbuf->buf.atom) - + offset))->body.size; - offset += lv2_evbuf_pad_size(sizeof(LV2_Atom_Event) + size); - - LV2_Evbuf_Iterator next = { evbuf, offset }; - return next; + if (!lv2_evbuf_is_valid(iter)) { + return iter; + } + + LV2_Atom_Sequence* aseq = &iter.evbuf->buf; + const char* abuf = (const char*)LV2_ATOM_CONTENTS(LV2_Atom_Sequence, aseq); + const LV2_Atom_Event* aev = (const LV2_Atom_Event*)(abuf + iter.offset); + + const uint32_t offset = + iter.offset + lv2_atom_pad_size(sizeof(LV2_Atom_Event) + aev->body.size); + + LV2_Evbuf_Iterator next = {iter.evbuf, offset}; + return next; } bool @@ -128,26 +128,27 @@ lv2_evbuf_get(LV2_Evbuf_Iterator iter, uint32_t* subframes, uint32_t* type, uint32_t* size, - uint8_t** data) + void** data) { - *frames = *subframes = *type = *size = 0; - *data = NULL; + *frames = *subframes = *type = *size = 0; + *data = NULL; - if (!lv2_evbuf_is_valid(iter)) { - return false; - } + if (!lv2_evbuf_is_valid(iter)) { + return false; + } - LV2_Atom_Sequence* aseq = &iter.evbuf->buf; - LV2_Atom_Event* aev = (LV2_Atom_Event*)( - (char*)LV2_ATOM_CONTENTS(LV2_Atom_Sequence, aseq) + iter.offset); + LV2_Atom_Sequence* aseq = &iter.evbuf->buf; + LV2_Atom_Event* aev = + (LV2_Atom_Event*)((char*)LV2_ATOM_CONTENTS(LV2_Atom_Sequence, aseq) + + iter.offset); - *frames = aev->time.frames; - *subframes = 0; - *type = aev->body.type; - *size = aev->body.size; - *data = (uint8_t*)LV2_ATOM_BODY(&aev->body); + *frames = aev->time.frames; + *subframes = 0; + *type = aev->body.type; + *size = aev->body.size; + *data = LV2_ATOM_BODY(&aev->body); - return true; + return true; } bool @@ -156,25 +157,28 @@ lv2_evbuf_write(LV2_Evbuf_Iterator* iter, uint32_t subframes, uint32_t type, uint32_t size, - const uint8_t* data) + const void* data) { - LV2_Atom_Sequence* aseq = &iter->evbuf->buf; - if (iter->evbuf->capacity - sizeof(LV2_Atom) - aseq->atom.size < - sizeof(LV2_Atom_Event) + size) { - return false; - } + (void)subframes; + + LV2_Atom_Sequence* aseq = &iter->evbuf->buf; + if (iter->evbuf->capacity - sizeof(LV2_Atom) - aseq->atom.size < + sizeof(LV2_Atom_Event) + size) { + return false; + } - LV2_Atom_Event* aev = (LV2_Atom_Event*)( - (char*)LV2_ATOM_CONTENTS(LV2_Atom_Sequence, aseq) + iter->offset); + LV2_Atom_Event* aev = + (LV2_Atom_Event*)((char*)LV2_ATOM_CONTENTS(LV2_Atom_Sequence, aseq) + + iter->offset); - aev->time.frames = frames; - aev->body.type = type; - aev->body.size = size; - memcpy(LV2_ATOM_BODY(&aev->body), data, size); + aev->time.frames = frames; + aev->body.type = type; + aev->body.size = size; + memcpy(LV2_ATOM_BODY(&aev->body), data, size); - size = lv2_evbuf_pad_size(sizeof(LV2_Atom_Event) + size); - aseq->atom.size += size; - iter->offset += size; + size = lv2_atom_pad_size(sizeof(LV2_Atom_Event) + size); + aseq->atom.size += size; + iter->offset += size; - return true; + return true; } diff --git a/src/lv2_evbuf.h b/src/lv2_evbuf.h index fad1006..685bef8 100644 --- a/src/lv2_evbuf.h +++ b/src/lv2_evbuf.h @@ -1,18 +1,5 @@ -/* - Copyright 2008-2014 David Robillard <http://drobilla.net> - - Permission to use, copy, modify, and/or distribute this software for any - purpose with or without fee is hereby granted, provided that the above - copyright notice and this permission notice appear in all copies. - - THIS SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES - WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF - MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR - ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES - WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN - ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF - OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. -*/ +// Copyright 2008-2022 David Robillard <d@drobilla.net> +// SPDX-License-Identifier: ISC #ifndef LV2_EVBUF_H #define LV2_EVBUF_H @@ -22,72 +9,64 @@ #ifdef __cplusplus extern "C" { #else -#include <stdbool.h> +# include <stdbool.h> #endif -/** - An abstract/opaque LV2 event buffer. -*/ +/// An abstract/opaque LV2 event buffer typedef struct LV2_Evbuf_Impl LV2_Evbuf; -/** - An iterator over an LV2_Evbuf. -*/ +/// An iterator over an LV2_Evbuf typedef struct { - LV2_Evbuf* evbuf; - uint32_t offset; + LV2_Evbuf* evbuf; + uint32_t offset; } LV2_Evbuf_Iterator; /** Allocate a new, empty event buffer. + URIDs for atom:Chunk and atom:Sequence must be passed for LV2_EVBUF_ATOM. */ LV2_Evbuf* lv2_evbuf_new(uint32_t capacity, uint32_t atom_Chunk, uint32_t atom_Sequence); -/** - Free an event buffer allocated with lv2_evbuf_new. -*/ +/// Free an event buffer allocated with lv2_evbuf_new void lv2_evbuf_free(LV2_Evbuf* evbuf); /** Clear and initialize an existing event buffer. + The contents of buf are ignored entirely and overwritten, except capacity - which is unmodified. - If input is false and this is an atom buffer, the buffer will be prepared - for writing by the plugin. This MUST be called before every run cycle. + which is unmodified. If input is false and this is an atom buffer, the + buffer will be prepared for writing by the plugin. This MUST be called + before every run cycle. */ void lv2_evbuf_reset(LV2_Evbuf* evbuf, bool input); -/** - Return the total padded size of the events stored in the buffer. -*/ +/// Return the total padded size of the events stored in the buffer uint32_t lv2_evbuf_get_size(LV2_Evbuf* evbuf); /** Return the actual buffer implementation. + The format of the buffer returned depends on the buffer type. */ void* lv2_evbuf_get_buffer(LV2_Evbuf* evbuf); -/** - Return an iterator to the start of `evbuf`. -*/ +/// Return an iterator to the start of `evbuf` LV2_Evbuf_Iterator lv2_evbuf_begin(LV2_Evbuf* evbuf); -/** - Return an iterator to the end of `evbuf`. -*/ +/// Return an iterator to the end of `evbuf` LV2_Evbuf_Iterator lv2_evbuf_end(LV2_Evbuf* evbuf); /** Check if `iter` is valid. + @return True if `iter` is valid, otherwise false (past end of buffer) */ bool @@ -95,7 +74,9 @@ lv2_evbuf_is_valid(LV2_Evbuf_Iterator iter); /** Advance `iter` forward one event. + `iter` must be valid. + @return True if `iter` is valid, otherwise false (reached end of buffer) */ LV2_Evbuf_Iterator @@ -103,6 +84,7 @@ lv2_evbuf_next(LV2_Evbuf_Iterator iter); /** Dereference an event iterator (i.e. get the event currently pointed to). + `iter` must be valid. `type` Set to the type of the event. `size` Set to the size of the event. @@ -115,13 +97,15 @@ lv2_evbuf_get(LV2_Evbuf_Iterator iter, uint32_t* subframes, uint32_t* type, uint32_t* size, - uint8_t** data); + void** data); /** Write an event at `iter`. + The event (if any) pointed to by `iter` will be overwritten, and `iter` incremented to point to the following event (i.e. several calls to this function can be done in sequence without twiddling iter in-between). + @return True if event was written, otherwise false (buffer is full). */ bool @@ -130,10 +114,10 @@ lv2_evbuf_write(LV2_Evbuf_Iterator* iter, uint32_t subframes, uint32_t type, uint32_t size, - const uint8_t* data); + const void* data); #ifdef __cplusplus } #endif -#endif /* LV2_EVBUF_H */ +#endif // LV2_EVBUF_H diff --git a/src/macros.h b/src/macros.h new file mode 100644 index 0000000..509a75c --- /dev/null +++ b/src/macros.h @@ -0,0 +1,19 @@ +// Copyright 2012-2024 David Robillard <d@drobilla.net> +// SPDX-License-Identifier: ISC + +#ifndef JALV_MACROS_H +#define JALV_MACROS_H + +#ifndef MIN +# define MIN(a, b) (((a) < (b)) ? (a) : (b)) +#endif + +#ifndef MAX +# define MAX(a, b) (((a) > (b)) ? (a) : (b)) +#endif + +#ifndef ARRAY_SIZE +# define ARRAY_SIZE(arr) (sizeof(arr) / sizeof((arr)[0])) +#endif + +#endif // JALV_MACROS_H diff --git a/src/main.c b/src/main.c new file mode 100644 index 0000000..5c49b10 --- /dev/null +++ b/src/main.c @@ -0,0 +1,77 @@ +// Copyright 2007-2024 David Robillard <d@drobilla.net> +// SPDX-License-Identifier: ISC + +#include "backend.h" +#include "frontend.h" +#include "jalv.h" +#include "jalv_config.h" +#include "types.h" + +#include <zix/attributes.h> +#include <zix/sem.h> + +#if USE_SUIL +#endif + +#include <signal.h> +#include <stdio.h> +#include <stdlib.h> +#include <string.h> + +static ZixSem* exit_sem = NULL; ///< Exit semaphore used by signal handler + +static void +signal_handler(int ZIX_UNUSED(sig)) +{ + zix_sem_post(exit_sem); +} + +static void +setup_signals(Jalv* const jalv) +{ + exit_sem = &jalv->done; + +#if !defined(_WIN32) && USE_SIGACTION + struct sigaction action; + sigemptyset(&action.sa_mask); + action.sa_flags = 0; + action.sa_handler = signal_handler; + sigaction(SIGINT, &action, NULL); + sigaction(SIGTERM, &action, NULL); +#else + // May not work in combination with fgets in the console interface + signal(SIGINT, signal_handler); + signal(SIGTERM, signal_handler); +#endif +} + +int +main(int argc, char** argv) +{ + Jalv jalv; + memset(&jalv, '\0', sizeof(Jalv)); + jalv.backend = jalv_backend_allocate(); + + // Initialize application + const int orc = jalv_open(&jalv, &argc, &argv); + if (orc) { + jalv_close(&jalv); + return orc == JALV_EARLY_EXIT_STATUS ? EXIT_SUCCESS : EXIT_FAILURE; + } + + // Set up signal handlers and activate audio processing + setup_signals(&jalv); + jalv_activate(&jalv); + + // Run UI (or prompt at console) + jalv_frontend_open(&jalv); + + // Wait for finish signal from UI or signal handler + zix_sem_wait(&jalv.done); + + // Deactivate audio processing and tear down application + jalv_deactivate(&jalv); + const int crc = jalv_close(&jalv); + jalv_backend_free(jalv.backend); + return crc; +} diff --git a/src/mapper.c b/src/mapper.c new file mode 100644 index 0000000..3e5c2af --- /dev/null +++ b/src/mapper.c @@ -0,0 +1,92 @@ +// Copyright 2012-2024 David Robillard <d@drobilla.net> +// SPDX-License-Identifier: ISC + +#include "mapper.h" + +#include "symap.h" + +#include <lv2/urid/urid.h> +#include <zix/sem.h> + +#include <stdint.h> +#include <stdlib.h> + +struct JalvMapperImpl { + Symap* symap; + ZixSem lock; + LV2_URID_Map map; + LV2_URID_Unmap unmap; +}; + +static LV2_URID +map_uri(LV2_URID_Map_Handle handle, const char* const uri) +{ + JalvMapper* const mapper = (JalvMapper*)handle; + zix_sem_wait(&mapper->lock); + + const LV2_URID id = symap_map(mapper->symap, uri); + + zix_sem_post(&mapper->lock); + return id; +} + +static const char* +unmap_uri(LV2_URID_Unmap_Handle handle, const LV2_URID urid) +{ + JalvMapper* const mapper = (JalvMapper*)handle; + zix_sem_wait(&mapper->lock); + + const char* const uri = symap_unmap(mapper->symap, urid); + + zix_sem_post(&mapper->lock); + return uri; +} + +JalvMapper* +jalv_mapper_new(void) +{ + JalvMapper* const mapper = (JalvMapper*)calloc(1, sizeof(JalvMapper)); + if (mapper) { + mapper->symap = symap_new(); + mapper->map.handle = mapper; + mapper->map.map = map_uri; + mapper->unmap.handle = mapper; + mapper->unmap.unmap = unmap_uri; + zix_sem_init(&mapper->lock, 1); + } + return mapper; +} + +void +jalv_mapper_free(JalvMapper* const mapper) +{ + if (mapper) { + zix_sem_destroy(&mapper->lock); + symap_free(mapper->symap); + free(mapper); + } +} + +LV2_URID_Map* +jalv_mapper_urid_map(JalvMapper* const mapper) +{ + return mapper ? &mapper->map : NULL; +} + +LV2_URID_Unmap* +jalv_mapper_urid_unmap(JalvMapper* const mapper) +{ + return mapper ? &mapper->unmap : NULL; +} + +LV2_URID +jalv_mapper_map_uri(JalvMapper* const mapper, const char* const sym) +{ + return symap_map(mapper->symap, sym); +} + +const char* +jalv_mapper_unmap_uri(const JalvMapper* mapper, uint32_t id) +{ + return mapper ? symap_unmap(mapper->symap, id) : NULL; +} diff --git a/src/mapper.h b/src/mapper.h new file mode 100644 index 0000000..ac4c53e --- /dev/null +++ b/src/mapper.h @@ -0,0 +1,44 @@ +// Copyright 2012-2024 David Robillard <d@drobilla.net> +// SPDX-License-Identifier: ISC + +#ifndef JALV_MAPPER_H +#define JALV_MAPPER_H + +#include "attributes.h" + +#include <lv2/urid/urid.h> +#include <zix/attributes.h> + +// URI to URID mapping and unmapping +JALV_BEGIN_DECLS + +/// Opaque URI mapper implementation +typedef struct JalvMapperImpl JalvMapper; + +/// Allocate, configure, and return a new URI mapper +JalvMapper* +jalv_mapper_new(void); + +/// Free memory allocated by jalv_mapper_new() +void +jalv_mapper_free(JalvMapper* mapper); + +/// Return a pointer to the mapper's LV2 URID map +LV2_URID_Map* +jalv_mapper_urid_map(JalvMapper* mapper); + +/// Return a pointer to the mapper's LV2 URID unmap +LV2_URID_Unmap* +jalv_mapper_urid_unmap(JalvMapper* mapper); + +/// Map a URI string to a URID +LV2_URID +jalv_mapper_map_uri(JalvMapper* mapper, const char* sym); + +/// Unmap a URID back to a URI string if possible, or return NULL +ZIX_PURE_FUNC const char* +jalv_mapper_unmap_uri(const JalvMapper* mapper, LV2_URID id); + +JALV_END_DECLS + +#endif // JALV_MAPPER_H diff --git a/src/nodes.c b/src/nodes.c new file mode 100644 index 0000000..d448657 --- /dev/null +++ b/src/nodes.c @@ -0,0 +1,76 @@ +// Copyright 2022-2024 David Robillard <d@drobilla.net> +// SPDX-License-Identifier: ISC + +#include "nodes.h" + +#include <lilv/lilv.h> +#include <lv2/atom/atom.h> +#include <lv2/core/lv2.h> +#include <lv2/midi/midi.h> +#include <lv2/port-groups/port-groups.h> +#include <lv2/port-props/port-props.h> +#include <lv2/presets/presets.h> +#include <lv2/resize-port/resize-port.h> +#include <lv2/state/state.h> +#include <lv2/ui/ui.h> +#include <lv2/worker/worker.h> + +#include <stddef.h> + +void +jalv_init_nodes(LilvWorld* const world, JalvNodes* const nodes) +{ +#define MAP_NODE(uri) lilv_new_uri(world, (uri)) + + nodes->atom_AtomPort = MAP_NODE(LV2_ATOM__AtomPort); + nodes->atom_Chunk = MAP_NODE(LV2_ATOM__Chunk); + nodes->atom_Float = MAP_NODE(LV2_ATOM__Float); + nodes->atom_Path = MAP_NODE(LV2_ATOM__Path); + nodes->atom_Sequence = MAP_NODE(LV2_ATOM__Sequence); + nodes->lv2_AudioPort = MAP_NODE(LV2_CORE__AudioPort); + nodes->lv2_CVPort = MAP_NODE(LV2_CORE__CVPort); + nodes->lv2_ControlPort = MAP_NODE(LV2_CORE__ControlPort); + nodes->lv2_InputPort = MAP_NODE(LV2_CORE__InputPort); + nodes->lv2_OutputPort = MAP_NODE(LV2_CORE__OutputPort); + nodes->lv2_connectionOptional = MAP_NODE(LV2_CORE__connectionOptional); + nodes->lv2_control = MAP_NODE(LV2_CORE__control); + nodes->lv2_default = MAP_NODE(LV2_CORE__default); + nodes->lv2_designation = MAP_NODE(LV2_CORE__designation); + nodes->lv2_enumeration = MAP_NODE(LV2_CORE__enumeration); + nodes->lv2_extensionData = MAP_NODE(LV2_CORE__extensionData); + nodes->lv2_integer = MAP_NODE(LV2_CORE__integer); + nodes->lv2_latency = MAP_NODE(LV2_CORE__latency); + nodes->lv2_maximum = MAP_NODE(LV2_CORE__maximum); + nodes->lv2_minimum = MAP_NODE(LV2_CORE__minimum); + nodes->lv2_name = MAP_NODE(LV2_CORE__name); + nodes->lv2_reportsLatency = MAP_NODE(LV2_CORE__reportsLatency); + nodes->lv2_sampleRate = MAP_NODE(LV2_CORE__sampleRate); + nodes->lv2_symbol = MAP_NODE(LV2_CORE__symbol); + nodes->lv2_toggled = MAP_NODE(LV2_CORE__toggled); + nodes->midi_MidiEvent = MAP_NODE(LV2_MIDI__MidiEvent); + nodes->pg_group = MAP_NODE(LV2_PORT_GROUPS__group); + nodes->pprops_logarithmic = MAP_NODE(LV2_PORT_PROPS__logarithmic); + nodes->pprops_notOnGUI = MAP_NODE(LV2_PORT_PROPS__notOnGUI); + nodes->pprops_rangeSteps = MAP_NODE(LV2_PORT_PROPS__rangeSteps); + nodes->pset_Preset = MAP_NODE(LV2_PRESETS__Preset); + nodes->pset_bank = MAP_NODE(LV2_PRESETS__bank); + nodes->rdfs_comment = MAP_NODE(LILV_NS_RDFS "comment"); + nodes->rdfs_label = MAP_NODE(LILV_NS_RDFS "label"); + nodes->rdfs_range = MAP_NODE(LILV_NS_RDFS "range"); + nodes->rsz_minimumSize = MAP_NODE(LV2_RESIZE_PORT__minimumSize); + nodes->state_threadSafeRestore = MAP_NODE(LV2_STATE__threadSafeRestore); + nodes->ui_showInterface = MAP_NODE(LV2_UI__showInterface); + nodes->work_interface = MAP_NODE(LV2_WORKER__interface); + nodes->work_schedule = MAP_NODE(LV2_WORKER__schedule); + nodes->end = NULL; + +#undef MAP_NODE +} + +void +jalv_free_nodes(JalvNodes* const nodes) +{ + for (LilvNode** n = (LilvNode**)nodes; *n; ++n) { + lilv_node_free(*n); + } +} diff --git a/src/nodes.h b/src/nodes.h new file mode 100644 index 0000000..8e93426 --- /dev/null +++ b/src/nodes.h @@ -0,0 +1,66 @@ +// Copyright 2007-2022 David Robillard <d@drobilla.net> +// SPDX-License-Identifier: ISC + +#ifndef JALV_NODES_H +#define JALV_NODES_H + +#include "attributes.h" + +#include <lilv/lilv.h> + +// Cached lilv nodes +JALV_BEGIN_DECLS + +typedef struct { + LilvNode* atom_AtomPort; + LilvNode* atom_Chunk; + LilvNode* atom_Float; + LilvNode* atom_Path; + LilvNode* atom_Sequence; + LilvNode* lv2_AudioPort; + LilvNode* lv2_CVPort; + LilvNode* lv2_ControlPort; + LilvNode* lv2_InputPort; + LilvNode* lv2_OutputPort; + LilvNode* lv2_connectionOptional; + LilvNode* lv2_control; + LilvNode* lv2_default; + LilvNode* lv2_designation; + LilvNode* lv2_enumeration; + LilvNode* lv2_extensionData; + LilvNode* lv2_integer; + LilvNode* lv2_latency; + LilvNode* lv2_maximum; + LilvNode* lv2_minimum; + LilvNode* lv2_name; + LilvNode* lv2_reportsLatency; + LilvNode* lv2_sampleRate; + LilvNode* lv2_symbol; + LilvNode* lv2_toggled; + LilvNode* midi_MidiEvent; + LilvNode* pg_group; + LilvNode* pprops_logarithmic; + LilvNode* pprops_notOnGUI; + LilvNode* pprops_rangeSteps; + LilvNode* pset_Preset; + LilvNode* pset_bank; + LilvNode* rdfs_comment; + LilvNode* rdfs_label; + LilvNode* rdfs_range; + LilvNode* rsz_minimumSize; + LilvNode* state_threadSafeRestore; + LilvNode* ui_showInterface; + LilvNode* work_interface; + LilvNode* work_schedule; + LilvNode* end; ///< NULL terminator for easy freeing of entire structure +} JalvNodes; + +void +jalv_init_nodes(LilvWorld* world, JalvNodes* nodes); + +void +jalv_free_nodes(JalvNodes* nodes); + +JALV_END_DECLS + +#endif // JALV_NODES_H diff --git a/src/options.h b/src/options.h new file mode 100644 index 0000000..1373e95 --- /dev/null +++ b/src/options.h @@ -0,0 +1,36 @@ +// Copyright 2007-2022 David Robillard <d@drobilla.net> +// SPDX-License-Identifier: ISC + +#ifndef JALV_OPTIONS_H +#define JALV_OPTIONS_H + +#include "attributes.h" + +#include <stdint.h> + +// Program options +JALV_BEGIN_DECLS + +typedef struct { + char* name; ///< Client name + int name_exact; ///< Exit if name is taken + char* load; ///< Path for state to load + char* preset; ///< URI of preset to load + char** controls; ///< Control values + uint32_t ring_size; ///< Plugin <=> UI communication buffer size + double update_rate; ///< UI update rate in Hz + double scale_factor; ///< UI scale factor + int dump; ///< Dump communication iff true + int trace; ///< Print trace log iff true + int generic_ui; ///< Use generic UI iff true + int show_hidden; ///< Show controls for notOnGUI ports + int no_menu; ///< Hide menu iff true + int show_ui; ///< Show non-embedded UI + int print_controls; ///< Print control changes to stdout + int non_interactive; ///< Do not listen for commands on stdin + char* ui_uri; ///< URI of UI to load +} JalvOptions; + +JALV_END_DECLS + +#endif // JALV_OPTIONS_H diff --git a/src/port.h b/src/port.h new file mode 100644 index 0000000..3737001 --- /dev/null +++ b/src/port.h @@ -0,0 +1,27 @@ +// Copyright 2007-2022 David Robillard <d@drobilla.net> +// SPDX-License-Identifier: ISC + +#ifndef JALV_PORT_H +#define JALV_PORT_H + +#include "attributes.h" +#include "types.h" + +#include <lilv/lilv.h> + +#include <stdint.h> + +// Application port state +JALV_BEGIN_DECLS + +typedef struct { + const LilvPort* lilv_port; ///< LV2 port + PortType type; ///< Data type + PortFlow flow; ///< Data flow direction + void* widget; ///< Control widget, if applicable + uint32_t index; ///< Port index +} JalvPort; + +JALV_END_DECLS + +#endif // JALV_PORT_H diff --git a/src/portaudio.c b/src/portaudio.c index bbcf008..8ce1945 100644 --- a/src/portaudio.c +++ b/src/portaudio.c @@ -1,223 +1,252 @@ -/* - Copyright 2007-2016 David Robillard <http://drobilla.net> +// Copyright 2007-2024 David Robillard <d@drobilla.net> +// SPDX-License-Identifier: ISC + +#include "backend.h" +#include "comm.h" +#include "log.h" +#include "lv2_evbuf.h" +#include "process.h" +#include "settings.h" +#include "types.h" +#include "urids.h" + +#include <lilv/lilv.h> +#include <zix/attributes.h> +#include <zix/sem.h> - Permission to use, copy, modify, and/or distribute this software for any - purpose with or without fee is hereby granted, provided that the above - copyright notice and this permission notice appear in all copies. - - THIS SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES - WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF - MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR - ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES - WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN - ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF - OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. - */ - -#include "jalv_internal.h" -#include "worker.h" - -#include <stdio.h> -#include <math.h> #include <portaudio.h> +#include <stdbool.h> +#include <stdint.h> +#include <stdio.h> +#include <stdlib.h> +#include <string.h> -struct JalvBackend { - PaStream* stream; +struct JalvBackendImpl { + PaStream* stream; }; static int -pa_process_cb(const void* inputs, - void* outputs, - unsigned long nframes, - const PaStreamCallbackTimeInfo* time, - PaStreamCallbackFlags flags, - void* handle) +process_silent(JalvProcess* const proc, + void* const outputs, + const unsigned long nframes) { - Jalv* jalv = (Jalv*)handle; - - /* Prepare port buffers */ - uint32_t in_index = 0; - uint32_t out_index = 0; - for (uint32_t i = 0; i < jalv->num_ports; ++i) { - struct Port* port = &jalv->ports[i]; - if (port->type == TYPE_AUDIO) { - if (port->flow == FLOW_INPUT) { - lilv_instance_connect_port(jalv->instance, i, ((float**)inputs)[in_index++]); - } else if (port->flow == FLOW_OUTPUT) { - lilv_instance_connect_port(jalv->instance, i, ((float**)outputs)[out_index++]); - } - } else if (port->type == TYPE_EVENT && port->flow == FLOW_INPUT) { - lv2_evbuf_reset(port->evbuf, true); - - if (jalv->request_update) { - /* Plugin state has changed, request an update */ - const LV2_Atom_Object get = { - { sizeof(LV2_Atom_Object_Body), jalv->urids.atom_Object }, - { 0, jalv->urids.patch_Get } }; - LV2_Evbuf_Iterator iter = lv2_evbuf_begin(port->evbuf); - lv2_evbuf_write(&iter, 0, 0, - get.atom.type, get.atom.size, - (const uint8_t*)LV2_ATOM_BODY(&get)); - } - } else if (port->type == TYPE_EVENT) { - /* Clear event output for plugin to write to */ - lv2_evbuf_reset(port->evbuf, false); - } - } - jalv->request_update = false; - - /* Run plugin for this cycle */ - const bool send_ui_updates = jalv_run(jalv, nframes); - - /* Deliver UI events */ - for (uint32_t p = 0; p < jalv->num_ports; ++p) { - struct Port* const port = &jalv->ports[p]; - if (port->flow == FLOW_OUTPUT && port->type == TYPE_EVENT) { - for (LV2_Evbuf_Iterator i = lv2_evbuf_begin(port->evbuf); - lv2_evbuf_is_valid(i); - i = lv2_evbuf_next(i)) { - // Get event from LV2 buffer - uint32_t frames, subframes, type, size; - uint8_t* body; - lv2_evbuf_get(i, &frames, &subframes, &type, &size, &body); - - if (jalv->has_ui) { - // Forward event to UI - jalv_send_to_ui(jalv, p, type, size, body); - } - } - } else if (send_ui_updates && - port->flow == FLOW_OUTPUT && port->type == TYPE_CONTROL) { - char buf[sizeof(ControlChange) + sizeof(float)]; - ControlChange* ev = (ControlChange*)buf; - ev->index = p; - ev->protocol = 0; - ev->size = sizeof(float); - *(float*)ev->body = port->control; - if (zix_ring_write(jalv->plugin_events, buf, sizeof(buf)) - < sizeof(buf)) { - fprintf(stderr, "Plugin => UI buffer overflow!\n"); - } - } - } - - return paContinue; + for (uint32_t i = 0; i < proc->num_ports; ++i) { + memset(((float**)outputs)[i], '\0', nframes * sizeof(float)); + } + + return jalv_bypass(proc, nframes); } -static JalvBackend* -pa_error(const char* msg, PaError err) +static int +process_cb(const void* inputs, + void* outputs, + unsigned long nframes, + const PaStreamCallbackTimeInfo* time, + PaStreamCallbackFlags flags, + void* handle) +{ + (void)time; + (void)flags; + + JalvProcess* const proc = (JalvProcess*)handle; + + // If execution is paused, emit silence and return + if (proc->run_state == JALV_PAUSED) { + return process_silent(proc, outputs, nframes); + } + + // Prepare port buffers + uint32_t in_index = 0; + uint32_t out_index = 0; + for (uint32_t i = 0; i < proc->num_ports; ++i) { + JalvProcessPort* const port = &proc->ports[i]; + if (port->type == TYPE_AUDIO) { + if (port->flow == FLOW_INPUT) { + lilv_instance_connect_port( + proc->instance, i, ((float**)inputs)[in_index++]); + } else if (port->flow == FLOW_OUTPUT) { + lilv_instance_connect_port( + proc->instance, i, ((float**)outputs)[out_index++]); + } + } else if (port->type == TYPE_EVENT) { + lv2_evbuf_reset(port->evbuf, port->flow == FLOW_INPUT); + } + } + + // Run plugin for this cycle + const bool send_ui_updates = jalv_run(proc, nframes); + + // Deliver UI events + for (uint32_t p = 0; p < proc->num_ports; ++p) { + JalvProcessPort* const port = &proc->ports[p]; + if (port->flow == FLOW_OUTPUT && port->type == TYPE_EVENT) { + for (LV2_Evbuf_Iterator i = lv2_evbuf_begin(port->evbuf); + lv2_evbuf_is_valid(i); + i = lv2_evbuf_next(i)) { + // Get event from LV2 buffer + uint32_t frames = 0U; + uint32_t subframes = 0U; + uint32_t type = 0U; + uint32_t size = 0U; + void* body = NULL; + lv2_evbuf_get(i, &frames, &subframes, &type, &size, &body); + + if (proc->has_ui) { + // Forward event to UI + jalv_write_event(proc->plugin_to_ui, p, size, type, body); + } + } + } else if (send_ui_updates && port->flow == FLOW_OUTPUT && + port->type == TYPE_CONTROL) { + jalv_write_control(proc->plugin_to_ui, p, proc->controls_buf[p]); + } + } + + return paContinue; +} + +static int +setup_error(const char* msg, PaError err) { - fprintf(stderr, "error: %s (%s)\n", msg, Pa_GetErrorText(err)); - Pa_Terminate(); - return NULL; + jalv_log(JALV_LOG_ERR, "%s (%s)\n", msg, Pa_GetErrorText(err)); + Pa_Terminate(); + return 1; } JalvBackend* -jalv_backend_init(Jalv* jalv) +jalv_backend_allocate(void) { - PaStreamParameters inputParameters; - PaStreamParameters outputParameters; - PaStream* stream = NULL; - PaError st = paNoError; - - if ((st = Pa_Initialize())) { - return pa_error("Failed to initialize audio system", st); - } - - // Get default input and output devices - inputParameters.device = Pa_GetDefaultInputDevice(); - outputParameters.device = Pa_GetDefaultOutputDevice(); - if (inputParameters.device == paNoDevice) { - return pa_error("No default input device", paDeviceUnavailable); - } else if (outputParameters.device == paNoDevice) { - return pa_error("No default output device", paDeviceUnavailable); - } - - const PaDeviceInfo* in_dev = Pa_GetDeviceInfo(inputParameters.device); - const PaDeviceInfo* out_dev = Pa_GetDeviceInfo(outputParameters.device); - - // Count number of input and output audio ports/channels - inputParameters.channelCount = 0; - outputParameters.channelCount = 0; - for (uint32_t i = 0; i < jalv->num_ports; ++i) { - if (jalv->ports[i].type == TYPE_AUDIO) { - if (jalv->ports[i].flow == FLOW_INPUT) { - ++inputParameters.channelCount; - } else if (jalv->ports[i].flow == FLOW_OUTPUT) { - ++outputParameters.channelCount; - } - } - } - - // Configure audio format - inputParameters.sampleFormat = paFloat32|paNonInterleaved; - inputParameters.suggestedLatency = in_dev->defaultLowInputLatency; - inputParameters.hostApiSpecificStreamInfo = NULL; - outputParameters.sampleFormat = paFloat32|paNonInterleaved; - outputParameters.suggestedLatency = out_dev->defaultLowOutputLatency; - outputParameters.hostApiSpecificStreamInfo = NULL; - - // Open stream - if ((st = Pa_OpenStream( - &stream, - inputParameters.channelCount ? &inputParameters : NULL, - outputParameters.channelCount ? &outputParameters : NULL, - in_dev->defaultSampleRate, - paFramesPerBufferUnspecified, - 0, - pa_process_cb, - jalv))) { - return pa_error("Failed to open audio stream", st); - } - - // Set audio parameters - jalv->sample_rate = in_dev->defaultSampleRate; - // jalv->block_length = FIXME - jalv->midi_buf_size = 4096; - - // Allocate and return opaque backend - JalvBackend* backend = (JalvBackend*)calloc(1, sizeof(JalvBackend)); - backend->stream = stream; - return backend; + return (JalvBackend*)calloc(1, sizeof(JalvBackend)); } void -jalv_backend_close(Jalv* jalv) +jalv_backend_free(JalvBackend* const backend) { - Pa_Terminate(); - free(jalv->backend); - jalv->backend = NULL; + free(backend); +} + +int +jalv_backend_open(JalvBackend* const backend, + const JalvURIDs* const ZIX_UNUSED(urids), + JalvSettings* const settings, + JalvProcess* const proc, + ZixSem* const ZIX_UNUSED(done), + const char* const ZIX_UNUSED(name), + const bool ZIX_UNUSED(exact_name)) +{ + PaStreamParameters inputParameters; + PaStreamParameters outputParameters; + PaStream* stream = NULL; + PaError st = paNoError; + + if ((st = Pa_Initialize())) { + return setup_error("Failed to initialize audio system", st); + } + + // Get default input and output devices + inputParameters.device = Pa_GetDefaultInputDevice(); + outputParameters.device = Pa_GetDefaultOutputDevice(); + if (inputParameters.device == paNoDevice) { + return setup_error("No default input device", paDeviceUnavailable); + } + + if (outputParameters.device == paNoDevice) { + return setup_error("No default output device", paDeviceUnavailable); + } + + const PaDeviceInfo* in_dev = Pa_GetDeviceInfo(inputParameters.device); + const PaDeviceInfo* out_dev = Pa_GetDeviceInfo(outputParameters.device); + + // Count number of input and output audio ports/channels + inputParameters.channelCount = 0; + outputParameters.channelCount = 0; + for (uint32_t i = 0; i < proc->num_ports; ++i) { + if (proc->ports[i].type == TYPE_AUDIO) { + if (proc->ports[i].flow == FLOW_INPUT) { + ++inputParameters.channelCount; + } else if (proc->ports[i].flow == FLOW_OUTPUT) { + ++outputParameters.channelCount; + } + } + } + + // Configure audio format + inputParameters.sampleFormat = paFloat32 | paNonInterleaved; + inputParameters.suggestedLatency = in_dev->defaultLowInputLatency; + inputParameters.hostApiSpecificStreamInfo = NULL; + outputParameters.sampleFormat = paFloat32 | paNonInterleaved; + outputParameters.suggestedLatency = out_dev->defaultLowOutputLatency; + outputParameters.hostApiSpecificStreamInfo = NULL; + + // Open stream + if ((st = + Pa_OpenStream(&stream, + inputParameters.channelCount ? &inputParameters : NULL, + outputParameters.channelCount ? &outputParameters : NULL, + in_dev->defaultSampleRate, + paFramesPerBufferUnspecified, + 0, + process_cb, + proc))) { + return setup_error("Failed to open audio stream", st); + } + + // Set audio parameters + settings->sample_rate = in_dev->defaultSampleRate; + // settings->block_length = FIXME + settings->midi_buf_size = 4096; + + backend->stream = stream; + return 0; +} + +void +jalv_backend_close(JalvBackend* const backend) +{ + if (backend) { + PaError st = paNoError; + if (backend->stream && (st = Pa_CloseStream(backend->stream))) { + jalv_log(JALV_LOG_ERR, "Error closing audio (%s)\n", Pa_GetErrorText(st)); + } + + if ((st = Pa_Terminate())) { + jalv_log( + JALV_LOG_ERR, "Error terminating audio (%s)\n", Pa_GetErrorText(st)); + } + } } void -jalv_backend_activate(Jalv* jalv) +jalv_backend_activate(JalvBackend* const backend) { - const int st = Pa_StartStream(jalv->backend->stream); - if (st != paNoError) { - fprintf(stderr, "error: Error starting audio stream (%s)\n", - Pa_GetErrorText(st)); - } + const PaError st = Pa_StartStream(backend->stream); + if (st != paNoError) { + jalv_log(JALV_LOG_ERR, "Error starting audio (%s)\n", Pa_GetErrorText(st)); + } } void -jalv_backend_deactivate(Jalv* jalv) +jalv_backend_deactivate(JalvBackend* const backend) { - const int st = Pa_CloseStream(jalv->backend->stream); - if (st != paNoError) { - fprintf(stderr, "error: Error closing audio stream (%s)\n", - Pa_GetErrorText(st)); - } + const PaError st = Pa_StopStream(backend->stream); + if (st != paNoError) { + jalv_log(JALV_LOG_ERR, "Error stopping audio (%s)\n", Pa_GetErrorText(st)); + } } void -jalv_backend_activate_port(Jalv* jalv, uint32_t port_index) +jalv_backend_activate_port(JalvBackend* const ZIX_UNUSED(backend), + JalvProcess* const proc, + const uint32_t port_index) { - struct Port* const port = &jalv->ports[port_index]; - switch (port->type) { - case TYPE_CONTROL: - lilv_instance_connect_port(jalv->instance, port_index, &port->control); - break; - default: - break; - } + JalvProcessPort* const port = &proc->ports[port_index]; + + if (port->type == TYPE_CONTROL) { + lilv_instance_connect_port( + proc->instance, port_index, &proc->controls_buf[port_index]); + } } + +void +jalv_backend_recompute_latencies(JalvBackend* const ZIX_UNUSED(backend)) +{} diff --git a/src/process.c b/src/process.c new file mode 100644 index 0000000..efb2602 --- /dev/null +++ b/src/process.c @@ -0,0 +1,130 @@ +// Copyright 2016-2024 David Robillard <d@drobilla.net> +// SPDX-License-Identifier: ISC + +#include "process.h" + +#include "comm.h" +#include "log.h" +#include "lv2_evbuf.h" +#include "types.h" +#include "worker.h" + +#include <lilv/lilv.h> +#include <lv2/atom/atom.h> +#include <lv2/core/lv2.h> +#include <zix/ring.h> +#include <zix/sem.h> + +#include <assert.h> +#include <stddef.h> + +static int +ring_error(const char* const message) +{ + jalv_log(JALV_LOG_ERR, "%s", message); + return 1; +} + +static int +apply_ui_events(JalvProcess* const proc, const uint32_t nframes) +{ + ZixRing* const ring = proc->ui_to_plugin; + JalvMessageHeader header = {NO_MESSAGE, 0U}; + const size_t space = zix_ring_read_space(ring); + for (size_t i = 0; i < space; i += sizeof(header) + header.size) { + // Read message header (which includes the body size) + if (zix_ring_read(ring, &header, sizeof(header)) != sizeof(header)) { + return ring_error("Failed to read header from UI ring\n"); + } + + if (header.type == CONTROL_PORT_CHANGE) { + assert(header.size == sizeof(JalvControlChange)); + JalvControlChange msg = {0U, 0.0f}; + if (zix_ring_read(ring, &msg, sizeof(msg)) != sizeof(msg)) { + return ring_error("Failed to read control value from UI ring\n"); + } + + assert(msg.port_index < proc->num_ports); + proc->controls_buf[msg.port_index] = msg.value; + + } else if (header.type == EVENT_TRANSFER) { + assert(header.size <= proc->process_msg_size); + void* const body = proc->process_msg; + if (zix_ring_read(ring, body, header.size) != header.size) { + return ring_error("Failed to read event from UI ring\n"); + } + + const JalvEventTransfer* const msg = (const JalvEventTransfer*)body; + assert(msg->port_index < proc->num_ports); + JalvProcessPort* const port = &proc->ports[msg->port_index]; + LV2_Evbuf_Iterator e = lv2_evbuf_end(port->evbuf); + const LV2_Atom* const atom = &msg->atom; + lv2_evbuf_write( + &e, nframes, 0U, atom->type, atom->size, LV2_ATOM_BODY_CONST(atom)); + + } else if (header.type == STATE_REQUEST) { + JalvProcessPort* const port = &proc->ports[proc->control_in]; + assert(port->type == TYPE_EVENT); + assert(port->flow == FLOW_INPUT); + assert(port->evbuf); + + LV2_Evbuf_Iterator e = lv2_evbuf_end(port->evbuf); + lv2_evbuf_write(&e, + nframes, + 0U, + proc->get_msg.atom.type, + proc->get_msg.atom.size, + &proc->get_msg.body); + + } else if (header.type == RUN_STATE_CHANGE) { + assert(header.size == sizeof(JalvRunStateChange)); + JalvRunStateChange msg = {JALV_RUNNING}; + if (zix_ring_read(ring, &msg, sizeof(msg)) != sizeof(msg)) { + return ring_error("Failed to read run state change from UI ring\n"); + } + + proc->run_state = msg.state; + if (msg.state == JALV_PAUSED) { + zix_sem_post(&proc->paused); + } + + } else { + return ring_error("Unknown message type received from UI ring\n"); + } + } + + return 0; +} + +bool +jalv_run(JalvProcess* const proc, const uint32_t nframes) +{ + // Read and apply control change events from UI + apply_ui_events(proc, nframes); + + // Run plugin for this cycle + lilv_instance_run(proc->instance, nframes); + + // Process any worker replies and end the cycle + LV2_Handle handle = lilv_instance_get_handle(proc->instance); + jalv_worker_emit_responses(proc->state_worker, handle); + jalv_worker_emit_responses(proc->worker, handle); + jalv_worker_end_run(proc->worker); + + // Check if it's time to send updates to the UI + proc->pending_frames += nframes; + if (proc->update_frames && proc->pending_frames > proc->update_frames) { + proc->pending_frames = 0U; + return true; + } + + return false; +} + +int +jalv_bypass(JalvProcess* const proc, const uint32_t nframes) +{ + // Read and apply control change events from UI + apply_ui_events(proc, nframes); + return 0; +} diff --git a/src/process.h b/src/process.h new file mode 100644 index 0000000..cb6a122 --- /dev/null +++ b/src/process.h @@ -0,0 +1,99 @@ +// Copyright 2016-2024 David Robillard <d@drobilla.net> +// SPDX-License-Identifier: ISC + +#ifndef JALV_PROCESS_H +#define JALV_PROCESS_H + +#include "attributes.h" +#include "lv2_evbuf.h" +#include "types.h" +#include "worker.h" + +#include <lilv/lilv.h> +#include <lv2/atom/atom.h> +#include <lv2/atom/forge.h> +#include <zix/ring.h> +#include <zix/sem.h> + +#include <stdbool.h> +#include <stddef.h> +#include <stdint.h> + +// Code and data used in the realtime process thread +JALV_BEGIN_DECLS + +/// Port state used in the process thread +typedef struct { + PortType type; ///< Data type + PortFlow flow; ///< Data flow direction + void* sys_port; ///< For audio/MIDI ports, otherwise NULL + char* symbol; ///< Port symbol (stable/unique C-like identifier) + char* label; ///< Human-readable label + LV2_Evbuf* evbuf; ///< Sequence port event buffer + uint32_t buf_size; ///< Custom buffer size, or 0 + bool reports_latency; ///< Whether control port reports latency + bool is_primary; ///< True for main control/response channel + bool supports_midi; ///< Whether event port supports MIDI +} JalvProcessPort; + +/** + State accessed in the process thread. + + Everything accessed by the process thread is stored here, to keep it + somewhat insulated from the UI and to make references to it stand out in the + code. +*/ +typedef struct { + LilvInstance* instance; ///< Plugin instance + ZixRing* ui_to_plugin; ///< Messages from UI to plugin/process + ZixRing* plugin_to_ui; ///< Messages from plugin/process to UI + JalvWorker* worker; ///< Worker thread implementation + JalvWorker* state_worker; ///< Synchronous worker for state restore + JalvProcessPort* ports; ///< Port array of size num_ports + LV2_Atom_Forge forge; ///< Atom forge + LV2_Atom_Object get_msg; ///< General patch:Get message + float* controls_buf; ///< Control port buffers array + size_t process_msg_size; ///< Maximum size of a single message + void* process_msg; ///< Buffer for receiving messages + ZixSem paused; ///< Paused signal from process thread + JalvRunState run_state; ///< Current run state + uint32_t control_in; ///< Index of control input port + uint32_t num_ports; ///< Total number of ports on the plugin + uint32_t pending_frames; ///< Frames since last UI update sent + uint32_t update_frames; ///< UI update period in frames, or zero + uint32_t plugin_latency; ///< Latency reported by plugin (if any) + uint32_t position; ///< Transport position in frames + float bpm; ///< Transport tempo in beats per minute + bool rolling; ///< Transport speed (0=stop, 1=play) + bool has_ui; ///< True iff a control UI is present +} JalvProcess; + +/** + Run the plugin for a block of frames. + + Applies any pending messages from the UI, runs the plugin instance, and + processes any worker replies. + + @param proc Process thread state. + @param nframes Number of frames to process. + @return Whether output value updates should be sent to the UI now. +*/ +bool +jalv_run(JalvProcess* proc, uint32_t nframes); + +/** + Bypass the plugin for a block of frames. + + This is like jalv_run(), but doesn't actually run the plugin and only does + the minimum necessary internal work for the cycle. + + @param proc Process thread state. + @param nframes Number of frames to bypass. + @return Zero. +*/ +int +jalv_bypass(JalvProcess* proc, uint32_t nframes); + +JALV_END_DECLS + +#endif // JALV_PROCESS_H diff --git a/src/process_setup.c b/src/process_setup.c new file mode 100644 index 0000000..169ddcd --- /dev/null +++ b/src/process_setup.c @@ -0,0 +1,219 @@ +// Copyright 2016-2024 David Robillard <d@drobilla.net> +// SPDX-License-Identifier: ISC + +#include "process_setup.h" + +#include "jalv_config.h" +#include "log.h" +#include "lv2_evbuf.h" +#include "macros.h" +#include "mapper.h" +#include "nodes.h" +#include "process.h" +#include "query.h" +#include "settings.h" +#include "string_utils.h" +#include "types.h" +#include "urids.h" +#include "worker.h" + +#include <lilv/lilv.h> +#include <lv2/atom/atom.h> +#include <lv2/atom/forge.h> +#include <zix/allocator.h> +#include <zix/ring.h> +#include <zix/sem.h> + +#include <stdbool.h> +#include <stdint.h> +#include <stdlib.h> + +int +jalv_process_init(JalvProcess* const proc, + const JalvURIDs* const urids, + JalvMapper* const mapper, + const uint32_t update_frames) +{ + proc->get_msg.atom.size = sizeof(LV2_Atom_Object_Body); + proc->get_msg.atom.type = urids->atom_Object; + proc->get_msg.body.id = 0U; + proc->get_msg.body.otype = urids->patch_Get; + + proc->instance = NULL; + proc->ui_to_plugin = NULL; + proc->plugin_to_ui = NULL; + proc->worker = NULL; + proc->state_worker = NULL; + proc->ports = NULL; + proc->process_msg_size = 1024U; + proc->process_msg = NULL; + proc->run_state = JALV_PAUSED; + proc->control_in = UINT32_MAX; + proc->num_ports = 0U; + proc->pending_frames = 0U; + proc->update_frames = update_frames; + proc->position = 0U; + proc->bpm = 120.0f; + proc->rolling = false; + proc->has_ui = false; + + zix_sem_init(&proc->paused, 0); + lv2_atom_forge_init(&proc->forge, jalv_mapper_urid_map(mapper)); + + return 0; +} + +void +jalv_process_cleanup(JalvProcess* const proc) +{ + zix_sem_destroy(&proc->paused); + jalv_worker_free(proc->worker); + jalv_worker_free(proc->state_worker); + zix_ring_free(proc->ui_to_plugin); + zix_ring_free(proc->plugin_to_ui); + zix_aligned_free(NULL, proc->process_msg); + + for (uint32_t i = 0U; i < proc->num_ports; ++i) { + jalv_process_port_cleanup(&proc->ports[i]); + } +} + +void +jalv_process_activate(JalvProcess* const proc, + const JalvURIDs* const urids, + LilvInstance* const instance, + const JalvSettings* const settings) +{ + proc->instance = instance; + + for (uint32_t i = 0U; i < proc->num_ports; ++i) { + JalvProcessPort* const port = &proc->ports[i]; + if (port->type == TYPE_EVENT) { + const size_t size = + port->buf_size ? port->buf_size : settings->midi_buf_size; + + lv2_evbuf_free(port->evbuf); + port->evbuf = + lv2_evbuf_new(size, urids->atom_Chunk, urids->atom_Sequence); + + lv2_evbuf_reset(port->evbuf, port->flow == FLOW_INPUT); + lilv_instance_connect_port( + proc->instance, i, lv2_evbuf_get_buffer(port->evbuf)); + + if (port->flow == FLOW_INPUT) { + proc->process_msg_size = MAX(proc->process_msg_size, port->buf_size); + } + } + } + + // Allocate UI<=>process communication rings and process receive buffer + proc->ui_to_plugin = zix_ring_new(NULL, settings->ring_size); + proc->plugin_to_ui = zix_ring_new(NULL, settings->ring_size); + proc->process_msg = zix_aligned_alloc(NULL, 8U, proc->process_msg_size); + zix_ring_mlock(proc->ui_to_plugin); + zix_ring_mlock(proc->plugin_to_ui); + zix_ring_mlock(proc->process_msg); +} + +void +jalv_process_deactivate(JalvProcess* const proc) +{ + zix_aligned_free(NULL, proc->process_msg); + proc->process_msg = NULL; + + for (uint32_t i = 0U; i < proc->num_ports; ++i) { + lv2_evbuf_free(proc->ports[i].evbuf); + lilv_instance_connect_port(proc->instance, i, NULL); + proc->ports[i].evbuf = NULL; + } +} + +int +jalv_process_port_init(JalvProcessPort* const port, + const JalvNodes* const nodes, + const LilvPlugin* const lilv_plugin, + const LilvPort* const lilv_port) +{ + const LilvNode* const symbol = lilv_port_get_symbol(lilv_plugin, lilv_port); + + port->type = TYPE_UNKNOWN; + port->flow = FLOW_UNKNOWN; + port->sys_port = NULL; + port->evbuf = NULL; + port->buf_size = 0U; + port->reports_latency = false; + + const bool optional = lilv_port_has_property( + lilv_plugin, lilv_port, nodes->lv2_connectionOptional); + + // Set port flow (input or output) + if (lilv_port_is_a(lilv_plugin, lilv_port, nodes->lv2_InputPort)) { + port->flow = FLOW_INPUT; + } else if (lilv_port_is_a(lilv_plugin, lilv_port, nodes->lv2_OutputPort)) { + port->flow = FLOW_OUTPUT; + } else if (!optional) { + jalv_log(JALV_LOG_ERR, + "Mandatory port \"%s\" is neither input nor output\n", + lilv_node_as_string(symbol)); + return 1; + } + + // Set port type + if (lilv_port_is_a(lilv_plugin, lilv_port, nodes->lv2_ControlPort)) { + port->type = TYPE_CONTROL; + } else if (lilv_port_is_a(lilv_plugin, lilv_port, nodes->lv2_AudioPort)) { + port->type = TYPE_AUDIO; +#if USE_JACK_METADATA + } else if (lilv_port_is_a(lilv_plugin, lilv_port, nodes->lv2_CVPort)) { + port->type = TYPE_CV; +#endif + } else if (lilv_port_is_a(lilv_plugin, lilv_port, nodes->atom_AtomPort)) { + port->type = TYPE_EVENT; + } else if (!optional) { + jalv_log(JALV_LOG_ERR, + "Mandatory port \"%s\" has unknown data type\n", + lilv_node_as_string(symbol)); + return 1; + } + + // Set symbol and label + LilvNode* const name = lilv_port_get_name(lilv_plugin, lilv_port); + port->symbol = symbol ? jalv_strdup(lilv_node_as_string(symbol)) : NULL; + port->label = name ? jalv_strdup(lilv_node_as_string(name)) : NULL; + lilv_node_free(name); + + // Set buffer size + LilvNode* const min_size = + lilv_port_get(lilv_plugin, lilv_port, nodes->rsz_minimumSize); + if (min_size && lilv_node_is_int(min_size)) { + port->buf_size = (uint32_t)MAX(lilv_node_as_int(min_size), 0); + } + lilv_node_free(min_size); + + // Set reports_latency flag + if (port->flow == FLOW_OUTPUT && port->type == TYPE_CONTROL && + (lilv_port_has_property( + lilv_plugin, lilv_port, nodes->lv2_reportsLatency) || + jalv_port_has_designation( + nodes, lilv_plugin, lilv_port, nodes->lv2_latency))) { + port->reports_latency = true; + } + + // Set supports_midi flag + port->supports_midi = + lilv_port_supports_event(lilv_plugin, lilv_port, nodes->midi_MidiEvent); + + return 0; +} + +void +jalv_process_port_cleanup(JalvProcessPort* const port) +{ + if (port) { + if (port->evbuf) { + lv2_evbuf_free(port->evbuf); + } + free(port->label); + free(port->symbol); + } +} diff --git a/src/process_setup.h b/src/process_setup.h new file mode 100644 index 0000000..8c99312 --- /dev/null +++ b/src/process_setup.h @@ -0,0 +1,83 @@ +// Copyright 2016-2024 David Robillard <d@drobilla.net> +// SPDX-License-Identifier: ISC + +#ifndef JALV_PROCESS_SETUP_H +#define JALV_PROCESS_SETUP_H + +#include "attributes.h" +#include "mapper.h" +#include "nodes.h" +#include "process.h" +#include "settings.h" +#include "urids.h" + +#include <lilv/lilv.h> + +#include <stdint.h> + +// Code for setting up the realtime process thread (but that isn't used in it) +JALV_BEGIN_DECLS + +/** + Initialize process thread and allocate necessary structures. + + This only initializes the state structure, it doesn't create any threads or + start plugin execution. +*/ +int +jalv_process_init(JalvProcess* proc, + const JalvURIDs* urids, + JalvMapper* mapper, + uint32_t update_frames); + +/** + Clean up process thread. + + This frees everything allocated by jalv_process_init() and + jalv_process_activate(). +*/ +void +jalv_process_cleanup(JalvProcess* proc); + +/** + Allocate necessary buffers, connect the plugin to them, and prepare to run. + + @param proc Process thread state. + @param urids Application vocabulary. + @param instance Plugin instance to run. + @param settings Process thread settings. +*/ +void +jalv_process_activate(JalvProcess* proc, + const JalvURIDs* urids, + LilvInstance* instance, + const JalvSettings* settings); + +/** + Clean up after jalv_process_activate() and disconnect plugin. + + @param proc Process thread state. +*/ +void +jalv_process_deactivate(JalvProcess* proc); + +/** + Initialize the process thread state for a port. + + @return Zero on success. +*/ +int +jalv_process_port_init(JalvProcessPort* port, + const JalvNodes* nodes, + const LilvPlugin* lilv_plugin, + const LilvPort* lilv_port); + +/** + Free memory allocated by jalv_setup_init_port(). +*/ +void +jalv_process_port_cleanup(JalvProcessPort* port); + +JALV_END_DECLS + +#endif // JALV_PROCESS_SETUP_H diff --git a/src/query.c b/src/query.c new file mode 100644 index 0000000..bef2fb5 --- /dev/null +++ b/src/query.c @@ -0,0 +1,56 @@ +// Copyright 2012-2024 David Robillard <d@drobilla.net> +// SPDX-License-Identifier: ISC + +#include "query.h" + +#include "nodes.h" + +#include <lilv/lilv.h> +#include <lv2/core/lv2.h> +#include <lv2/ui/ui.h> + +bool +jalv_port_has_designation(const JalvNodes* const nodes, + const LilvPlugin* const plugin, + const LilvPort* const port, + const LilvNode* const designation) +{ + LilvNodes* const designations = + lilv_port_get_value(plugin, port, nodes->lv2_designation); + + bool found = false; + LILV_FOREACH (nodes, n, designations) { + const LilvNode* const node = lilv_nodes_get(designations, n); + if (lilv_node_equals(node, designation)) { + found = true; + break; + } + } + + lilv_nodes_free(designations); + return found; +} + +bool +jalv_ui_is_resizable(LilvWorld* const world, const LilvUI* const ui) +{ + if (!ui) { + return false; + } + + const LilvNode* s = lilv_ui_get_uri(ui); + LilvNode* p = lilv_new_uri(world, LV2_CORE__optionalFeature); + LilvNode* fs = lilv_new_uri(world, LV2_UI__fixedSize); + LilvNode* nrs = lilv_new_uri(world, LV2_UI__noUserResize); + + LilvNodes* fs_matches = lilv_world_find_nodes(world, s, p, fs); + LilvNodes* nrs_matches = lilv_world_find_nodes(world, s, p, nrs); + + lilv_nodes_free(nrs_matches); + lilv_nodes_free(fs_matches); + lilv_node_free(nrs); + lilv_node_free(fs); + lilv_node_free(p); + + return !fs_matches && !nrs_matches; +} diff --git a/src/query.h b/src/query.h new file mode 100644 index 0000000..4a452c6 --- /dev/null +++ b/src/query.h @@ -0,0 +1,30 @@ +// Copyright 2012-2024 David Robillard <d@drobilla.net> +// SPDX-License-Identifier: ISC + +#ifndef JALV_MODEL_H +#define JALV_MODEL_H + +#include "attributes.h" +#include "nodes.h" + +#include <lilv/lilv.h> + +#include <stdbool.h> + +// Lilv query utilities +JALV_BEGIN_DECLS + +/// Return whether a port has a given designation +bool +jalv_port_has_designation(const JalvNodes* nodes, + const LilvPlugin* plugin, + const LilvPort* port, + const LilvNode* designation); + +/// Return whether a UI is described as resizable +bool +jalv_ui_is_resizable(LilvWorld* world, const LilvUI* ui); + +JALV_END_DECLS + +#endif // JALV_MODEL_H diff --git a/src/settings.h b/src/settings.h new file mode 100644 index 0000000..0cb548e --- /dev/null +++ b/src/settings.h @@ -0,0 +1,27 @@ +// Copyright 2018-2024 David Robillard <d@drobilla.net> +// SPDX-License-Identifier: ISC + +#ifndef JALV_SETTINGS_H +#define JALV_SETTINGS_H + +#include "attributes.h" + +#include <stddef.h> +#include <stdint.h> + +// Process thread settings +JALV_BEGIN_DECLS + +/// System and/or configuration settings for the execution process +typedef struct { + float sample_rate; ///< Sample rate + uint32_t block_length; ///< Audio buffer length in frames + size_t midi_buf_size; ///< MIDI buffer size in bytes + uint32_t ring_size; ///< Communication ring size in bytes + float ui_update_hz; ///< Frequency of UI updates + float ui_scale_factor; ///< UI scale factor +} JalvSettings; + +JALV_END_DECLS + +#endif // JALV_SETTINGS_H diff --git a/src/state.c b/src/state.c index dab6c02..472244e 100644 --- a/src/state.c +++ b/src/state.c @@ -1,49 +1,39 @@ -/* - Copyright 2007-2016 David Robillard <http://drobilla.net> - - Permission to use, copy, modify, and/or distribute this software for any - purpose with or without fee is hereby granted, provided that the above - copyright notice and this permission notice appear in all copies. - - THIS SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES - WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF - MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR - ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES - WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN - ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF - OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. -*/ - -#include "jalv_config.h" -#include "jalv_internal.h" - -#ifdef HAVE_LV2_STATE -# include "lv2/lv2plug.in/ns/ext/state/state.h" -#endif - -#include "lilv/lilv.h" - -#include <assert.h> +// Copyright 2007-2024 David Robillard <d@drobilla.net> +// SPDX-License-Identifier: ISC + +#include "state.h" + +#include "comm.h" +#include "jalv.h" +#include "log.h" +#include "mapper.h" +#include "port.h" +#include "process.h" +#include "types.h" + +#include <lilv/lilv.h> +#include <lv2/core/lv2.h> +#include <lv2/state/state.h> +#include <lv2/urid/urid.h> +#include <zix/attributes.h> +#include <zix/path.h> +#include <zix/ring.h> +#include <zix/sem.h> +#include <zix/status.h> + +#include <stdbool.h> +#include <stdint.h> #include <stdio.h> #include <stdlib.h> -#include <string.h> -#include <errno.h> -#include <sys/stat.h> -#include <sys/types.h> - -#define NS_JALV "http://drobilla.net/ns/jalv#" -#define NS_RDF "http://www.w3.org/1999/02/22-rdf-syntax-ns#" -#define NS_RDFS "http://www.w3.org/2000/01/rdf-schema#" -#define NS_XSD "http://www.w3.org/2001/XMLSchema#" - -char* -jalv_make_path(LV2_State_Make_Path_Handle handle, - const char* path) + +ZIX_MALLOC_FUNC char* +jalv_make_path(LV2_State_Make_Path_Handle handle, const char* path) { - Jalv* jalv = (Jalv*)handle; + Jalv* jalv = (Jalv*)handle; - // Create in save directory if saving, otherwise use temp directory - return jalv_strjoin(jalv->save_dir ? jalv->save_dir : jalv->temp_dir, path); + // Create in save directory if saving, otherwise use temp directory + const char* const dir = jalv->save_dir ? jalv->save_dir : jalv->temp_dir; + return zix_path_join(NULL, dir, path); } static const void* @@ -52,166 +42,193 @@ get_port_value(const char* port_symbol, uint32_t* size, uint32_t* type) { - Jalv* jalv = (Jalv*)user_data; - struct Port* port = jalv_port_by_symbol(jalv, port_symbol); - if (port && port->flow == FLOW_INPUT && port->type == TYPE_CONTROL) { - *size = sizeof(float); - *type = jalv->forge.Float; - return &port->control; - } - *size = *type = 0; - return NULL; + Jalv* const jalv = (Jalv*)user_data; + const JalvPort* const port = jalv_port_by_symbol(jalv, port_symbol); + if (port && port->flow == FLOW_INPUT && port->type == TYPE_CONTROL) { + *size = sizeof(float); + *type = jalv->forge.Float; + return &jalv->process.controls_buf[port->index]; + } + *size = *type = 0; + return NULL; } void jalv_save(Jalv* jalv, const char* dir) { - jalv->save_dir = jalv_strjoin(dir, "/"); - - LilvState* const state = lilv_state_new_from_instance( - jalv->plugin, jalv->instance, &jalv->map, - jalv->temp_dir, dir, dir, dir, - get_port_value, jalv, - LV2_STATE_IS_POD|LV2_STATE_IS_PORTABLE, NULL); - - lilv_state_save(jalv->world, &jalv->map, &jalv->unmap, state, NULL, - dir, "state.ttl"); - - lilv_state_free(state); - - free(jalv->save_dir); - jalv->save_dir = NULL; + LV2_URID_Map* const map = jalv_mapper_urid_map(jalv->mapper); + LV2_URID_Unmap* const unmap = jalv_mapper_urid_unmap(jalv->mapper); + + jalv->save_dir = zix_path_join(NULL, dir, NULL); + + LilvState* const state = + lilv_state_new_from_instance(jalv->plugin, + jalv->process.instance, + map, + jalv->temp_dir, + dir, + dir, + dir, + get_port_value, + jalv, + LV2_STATE_IS_POD | LV2_STATE_IS_PORTABLE, + NULL); + + lilv_state_save(jalv->world, map, unmap, state, NULL, dir, "state.ttl"); + lilv_state_free(state); + free(jalv->save_dir); + jalv->save_dir = NULL; } int jalv_load_presets(Jalv* jalv, PresetSink sink, void* data) { - LilvNodes* presets = lilv_plugin_get_related(jalv->plugin, - jalv->nodes.pset_Preset); - LILV_FOREACH(nodes, i, presets) { - const LilvNode* preset = lilv_nodes_get(presets, i); - lilv_world_load_resource(jalv->world, preset); - if (!sink) { - continue; - } - - LilvNodes* labels = lilv_world_find_nodes( - jalv->world, preset, jalv->nodes.rdfs_label, NULL); - if (labels) { - const LilvNode* label = lilv_nodes_get_first(labels); - sink(jalv, preset, label, data); - lilv_nodes_free(labels); - } else { - fprintf(stderr, "Preset <%s> has no rdfs:label\n", - lilv_node_as_string(lilv_nodes_get(presets, i))); - } - } - lilv_nodes_free(presets); - - return 0; + LilvNodes* presets = + lilv_plugin_get_related(jalv->plugin, jalv->nodes.pset_Preset); + LILV_FOREACH (nodes, i, presets) { + const LilvNode* preset = lilv_nodes_get(presets, i); + lilv_world_load_resource(jalv->world, preset); + if (!sink) { + continue; + } + + LilvNodes* labels = + lilv_world_find_nodes(jalv->world, preset, jalv->nodes.rdfs_label, NULL); + if (labels) { + const LilvNode* label = lilv_nodes_get_first(labels); + sink(jalv, preset, label, data); + lilv_nodes_free(labels); + } else { + jalv_log(JALV_LOG_WARNING, + "Preset <%s> has no rdfs:label\n", + lilv_node_as_string(lilv_nodes_get(presets, i))); + } + } + lilv_nodes_free(presets); + + return 0; } int jalv_unload_presets(Jalv* jalv) { - LilvNodes* presets = lilv_plugin_get_related(jalv->plugin, - jalv->nodes.pset_Preset); - LILV_FOREACH(nodes, i, presets) { - const LilvNode* preset = lilv_nodes_get(presets, i); - lilv_world_unload_resource(jalv->world, preset); - } - lilv_nodes_free(presets); - - return 0; + LilvNodes* presets = + lilv_plugin_get_related(jalv->plugin, jalv->nodes.pset_Preset); + LILV_FOREACH (nodes, i, presets) { + const LilvNode* preset = lilv_nodes_get(presets, i); + lilv_world_unload_resource(jalv->world, preset); + } + lilv_nodes_free(presets); + + return 0; } static void -set_port_value(const char* port_symbol, - void* user_data, - const void* value, - ZIX_UNUSED uint32_t size, - uint32_t type) +set_port_value(const char* port_symbol, + void* user_data, + const void* value, + uint32_t ZIX_UNUSED(size), + uint32_t type) { - Jalv* jalv = (Jalv*)user_data; - struct Port* port = jalv_port_by_symbol(jalv, port_symbol); - if (!port) { - fprintf(stderr, "error: Preset port `%s' is missing\n", port_symbol); - return; - } - - float fvalue; - if (type == jalv->forge.Float) { - fvalue = *(const float*)value; - } else if (type == jalv->forge.Double) { - fvalue = *(const double*)value; - } else if (type == jalv->forge.Int) { - fvalue = *(const int32_t*)value; - } else if (type == jalv->forge.Long) { - fvalue = *(const int64_t*)value; - } else { - fprintf(stderr, "error: Preset `%s' value has bad type <%s>\n", - port_symbol, jalv->unmap.unmap(jalv->unmap.handle, type)); - return; - } - - if (jalv->play_state != JALV_RUNNING) { - // Set value on port struct directly - port->control = fvalue; - } else { - // Send value to running plugin - jalv_ui_write(jalv, port->index, sizeof(fvalue), 0, &fvalue); - } - - if (jalv->has_ui) { - // Update UI - char buf[sizeof(ControlChange) + sizeof(fvalue)]; - ControlChange* ev = (ControlChange*)buf; - ev->index = port->index; - ev->protocol = 0; - ev->size = sizeof(fvalue); - *(float*)ev->body = fvalue; - zix_ring_write(jalv->plugin_events, buf, sizeof(buf)); - } + Jalv* const jalv = (Jalv*)user_data; + JalvProcess* const proc = &jalv->process; + const JalvPort* const port = jalv_port_by_symbol(jalv, port_symbol); + if (!port) { + jalv_log(JALV_LOG_ERR, "Preset port `%s' is missing\n", port_symbol); + return; + } + + float fvalue = 0.0f; + if (type == jalv->forge.Float) { + fvalue = *(const float*)value; + } else if (type == jalv->forge.Double) { + fvalue = *(const double*)value; + } else if (type == jalv->forge.Int) { + fvalue = *(const int32_t*)value; + } else if (type == jalv->forge.Long) { + fvalue = *(const int64_t*)value; + } else { + jalv_log(JALV_LOG_ERR, + "Preset `%s' value has bad type <%s>\n", + port_symbol, + jalv_mapper_unmap_uri(jalv->mapper, type)); + return; + } + + ZixStatus st = ZIX_STATUS_SUCCESS; + if (proc->run_state != JALV_RUNNING) { + // Set value on port struct directly + proc->controls_buf[port->index] = fvalue; + } else { + // Send value to plugin (as if from UI) + st = jalv_write_control(proc->ui_to_plugin, port->index, fvalue); + } + + if (proc->has_ui) { + // Update UI (as if from plugin) + st = jalv_write_control(proc->plugin_to_ui, port->index, fvalue); + } + + if (st) { + jalv_log( + JALV_LOG_ERR, "Failed to write control change (%s)\n", zix_strerror(st)); + } } void -jalv_apply_state(Jalv* jalv, LilvState* state) +jalv_apply_state(Jalv* jalv, const LilvState* state) { - bool must_pause = !jalv->safe_restore && jalv->play_state == JALV_RUNNING; - if (state) { - if (must_pause) { - jalv->play_state = JALV_PAUSE_REQUESTED; - zix_sem_wait(&jalv->paused); - } - - const LV2_Feature* state_features[9] = { - &jalv->features.map_feature, - &jalv->features.unmap_feature, - &jalv->features.make_path_feature, - &jalv->features.state_sched_feature, - &jalv->features.safe_restore_feature, - &jalv->features.log_feature, - &jalv->features.options_feature, - NULL - }; - - lilv_state_restore( - state, jalv->instance, set_port_value, jalv, 0, state_features); - - if (must_pause) { - jalv->request_update = true; - jalv->play_state = JALV_RUNNING; - } - } + JalvProcess* const proc = &jalv->process; + + typedef struct { + JalvMessageHeader head; + JalvRunStateChange body; + } PauseMessage; + + const bool must_pause = + !jalv->safe_restore && proc->run_state == JALV_RUNNING; + if (must_pause) { + const PauseMessage pause_msg = { + {RUN_STATE_CHANGE, sizeof(JalvRunStateChange)}, {JALV_PAUSED}}; + zix_ring_write(proc->ui_to_plugin, &pause_msg, sizeof(pause_msg)); + + zix_sem_wait(&proc->paused); + } + + const LV2_Feature* state_features[9] = { + &jalv->features.map_feature, + &jalv->features.unmap_feature, + &jalv->features.make_path_feature, + &jalv->features.state_sched_feature, + &jalv->features.safe_restore_feature, + &jalv->features.log_feature, + &jalv->features.options_feature, + NULL, + }; + + lilv_state_restore( + state, proc->instance, set_port_value, jalv, 0, state_features); + + if (must_pause) { + const JalvMessageHeader state_msg = {STATE_REQUEST, 0U}; + zix_ring_write(proc->ui_to_plugin, &state_msg, sizeof(state_msg)); + + const PauseMessage run_msg = { + {RUN_STATE_CHANGE, sizeof(JalvRunStateChange)}, {JALV_RUNNING}}; + zix_ring_write(proc->ui_to_plugin, &run_msg, sizeof(run_msg)); + } } int jalv_apply_preset(Jalv* jalv, const LilvNode* preset) { - lilv_state_free(jalv->preset); - jalv->preset = lilv_state_new_from_world(jalv->world, &jalv->map, preset); - jalv_apply_state(jalv, jalv->preset); - return 0; + lilv_state_free(jalv->preset); + jalv->preset = lilv_state_new_from_world( + jalv->world, jalv_mapper_urid_map(jalv->mapper), preset); + if (jalv->preset) { + jalv_apply_state(jalv, jalv->preset); + } + return 0; } int @@ -221,35 +238,44 @@ jalv_save_preset(Jalv* jalv, const char* label, const char* filename) { - LilvState* const state = lilv_state_new_from_instance( - jalv->plugin, jalv->instance, &jalv->map, - jalv->temp_dir, dir, dir, dir, - get_port_value, jalv, - LV2_STATE_IS_POD|LV2_STATE_IS_PORTABLE, NULL); - - if (label) { - lilv_state_set_label(state, label); - } - - int ret = lilv_state_save( - jalv->world, &jalv->map, &jalv->unmap, state, uri, dir, filename); - - lilv_state_free(jalv->preset); - jalv->preset = state; - - return ret; + LV2_URID_Map* const map = jalv_mapper_urid_map(jalv->mapper); + LV2_URID_Unmap* const unmap = jalv_mapper_urid_unmap(jalv->mapper); + + LilvState* const state = + lilv_state_new_from_instance(jalv->plugin, + jalv->process.instance, + map, + jalv->temp_dir, + dir, + dir, + dir, + get_port_value, + jalv, + LV2_STATE_IS_POD | LV2_STATE_IS_PORTABLE, + NULL); + + if (label) { + lilv_state_set_label(state, label); + } + + int ret = lilv_state_save(jalv->world, map, unmap, state, uri, dir, filename); + + lilv_state_free(jalv->preset); + jalv->preset = state; + + return ret; } int jalv_delete_current_preset(Jalv* jalv) { - if (!jalv->preset) { - return 1; - } - - lilv_world_unload_resource(jalv->world, lilv_state_get_uri(jalv->preset)); - lilv_state_delete(jalv->world, jalv->preset); - lilv_state_free(jalv->preset); - jalv->preset = NULL; - return 0; + if (!jalv->preset) { + return 1; + } + + lilv_world_unload_resource(jalv->world, lilv_state_get_uri(jalv->preset)); + lilv_state_delete(jalv->world, jalv->preset); + lilv_state_free(jalv->preset); + jalv->preset = NULL; + return 0; } diff --git a/src/state.h b/src/state.h new file mode 100644 index 0000000..c4c1fd3 --- /dev/null +++ b/src/state.h @@ -0,0 +1,51 @@ +// Copyright 2007-2022 David Robillard <d@drobilla.net> +// SPDX-License-Identifier: ISC + +#ifndef JALV_STATE_H +#define JALV_STATE_H + +#include "attributes.h" +#include "types.h" + +#include <lilv/lilv.h> +#include <lv2/state/state.h> + +// State and preset utilities +JALV_BEGIN_DECLS + +typedef int (*PresetSink)(Jalv* jalv, + const LilvNode* node, + const LilvNode* title, + void* data); + +int +jalv_load_presets(Jalv* jalv, PresetSink sink, void* data); + +int +jalv_unload_presets(Jalv* jalv); + +int +jalv_apply_preset(Jalv* jalv, const LilvNode* preset); + +int +jalv_delete_current_preset(Jalv* jalv); + +int +jalv_save_preset(Jalv* jalv, + const char* dir, + const char* uri, + const char* label, + const char* filename); + +void +jalv_save(Jalv* jalv, const char* dir); + +char* +jalv_make_path(LV2_State_Make_Path_Handle handle, const char* path); + +void +jalv_apply_state(Jalv* jalv, const LilvState* state); + +JALV_END_DECLS + +#endif // JALV_STATE_H diff --git a/src/string_utils.c b/src/string_utils.c new file mode 100644 index 0000000..dcabcac --- /dev/null +++ b/src/string_utils.c @@ -0,0 +1,16 @@ +// Copyright 2007-2022 David Robillard <d@drobilla.net> +// SPDX-License-Identifier: ISC + +#include "string_utils.h" + +#include <stdlib.h> +#include <string.h> + +char* +jalv_strdup(const char* const str) +{ + const size_t len = strlen(str); + char* copy = (char*)malloc(len + 1); + memcpy(copy, str, len + 1); + return copy; +} diff --git a/src/string_utils.h b/src/string_utils.h new file mode 100644 index 0000000..74193a0 --- /dev/null +++ b/src/string_utils.h @@ -0,0 +1,18 @@ +// Copyright 2007-2022 David Robillard <d@drobilla.net> +// SPDX-License-Identifier: ISC + +#ifndef JALV_STRING_UTILS_H +#define JALV_STRING_UTILS_H + +#include "attributes.h" + +// String utilities +JALV_BEGIN_DECLS + +/// Return a newly allocated copy of a string +char* +jalv_strdup(const char* str); + +JALV_END_DECLS + +#endif // JALV_STRING_UTILS_H diff --git a/src/symap.c b/src/symap.c index afcdadb..46c147c 100644 --- a/src/symap.c +++ b/src/symap.c @@ -1,18 +1,5 @@ -/* - Copyright 2011-2014 David Robillard <http://drobilla.net> - - Permission to use, copy, modify, and/or distribute this software for any - purpose with or without fee is hereby granted, provided that the above - copyright notice and this permission notice appear in all copies. - - THIS SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES - WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF - MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR - ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES - WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN - ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF - OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. -*/ +// Copyright 2011-2022 David Robillard <d@drobilla.net> +// SPDX-License-Identifier: ISC #include "symap.h" @@ -38,56 +25,47 @@ */ struct SymapImpl { - /** - Unsorted array of strings, such that the symbol for ID i is found - at symbols[i - 1]. - */ - char** symbols; - - /** - Array of IDs, sorted by corresponding string in `symbols`. - */ - uint32_t* index; - - /** - Number of symbols (number of items in `symbols` and `index`). - */ - uint32_t size; + char** symbols; ///< String array where symbols[i] is the symbol for ID i + uint32_t* index; ///< ID array sorted by corresponding string in `symbols` + uint32_t size; ///< Number of symbols (length of both symbols and index) + uint32_t pad; ///< Unused padding }; Symap* symap_new(void) { - Symap* map = (Symap*)malloc(sizeof(Symap)); - map->symbols = NULL; - map->index = NULL; - map->size = 0; - return map; + Symap* const map = (Symap*)calloc(1, sizeof(Symap)); + + if (map) { + map->symbols = NULL; + map->index = NULL; + map->size = 0U; + } + + return map; } void -symap_free(Symap* map) +symap_free(Symap* const map) { - if (!map) { - return; - } - - for (uint32_t i = 0; i < map->size; ++i) { - free(map->symbols[i]); - } - - free(map->symbols); - free(map->index); - free(map); + if (map) { + for (uint32_t i = 0U; i < map->size; ++i) { + free(map->symbols[i]); + } + + free(map->symbols); + free(map->index); + free(map); + } } static char* -symap_strdup(const char* str) +symap_strdup(const char* const str) { - const size_t len = strlen(str); - char* copy = (char*)malloc(len + 1); - memcpy(copy, str, len + 1); - return copy; + const size_t len = strlen(str); + char* const copy = (char*)malloc(len + 1); + memcpy(copy, str, len + 1); + return copy; } /** @@ -95,141 +73,175 @@ symap_strdup(const char* str) or the index where a new entry for `sym` should be inserted. */ static uint32_t -symap_search(const Symap* map, const char* sym, bool* exact) +symap_search(const Symap* const map, const char* const sym, bool* const exact) { - *exact = false; - if (map->size == 0) { - return 0; // Empty map, insert at 0 - } else if (strcmp(map->symbols[map->index[map->size - 1] - 1], sym) < 0) { - return map->size; // Greater than last element, append - } - - uint32_t lower = 0; - uint32_t upper = map->size - 1; - uint32_t i = upper; - int cmp; - - while (upper >= lower) { - i = lower + ((upper - lower) / 2); - cmp = strcmp(map->symbols[map->index[i] - 1], sym); - - if (cmp == 0) { - *exact = true; - return i; - } else if (cmp > 0) { - if (i == 0) { - break; // Avoid underflow - } - upper = i - 1; - } else { - lower = ++i; - } - } - - assert(!*exact || strcmp(map->symbols[map->index[i] - 1], sym) > 0); - return i; + *exact = false; + + if (map->size == 0) { + return 0; // Empty map, insert at 0 + } + + if (strcmp(map->symbols[map->index[map->size - 1] - 1], sym) < 0) { + return map->size; // Greater than last element, append + } + + uint32_t lower = 0; + uint32_t upper = map->size - 1; + uint32_t i = upper; + + while (upper >= lower) { + i = lower + ((upper - lower) / 2); + + const int cmp = strcmp(map->symbols[map->index[i] - 1], sym); + if (cmp == 0) { + *exact = true; + return i; + } + + if (cmp > 0) { + if (i == 0) { + break; // Avoid underflow + } + upper = i - 1; + } else { + lower = ++i; + } + } + + assert(!*exact || strcmp(map->symbols[map->index[i] - 1], sym) > 0); + return i; } uint32_t -symap_try_map(Symap* map, const char* sym) +symap_try_map(const Symap* const map, const char* const sym) { - bool exact; - const uint32_t index = symap_search(map, sym, &exact); - if (exact) { - assert(!strcmp(map->symbols[map->index[index]], sym)); - return map->index[index]; - } - - return 0; + bool exact = false; + const uint32_t index = symap_search(map, sym, &exact); + if (exact) { + return map->index[index]; + } + + return 0; } uint32_t -symap_map(Symap* map, const char* sym) +symap_map(Symap* const map, const char* sym) { - bool exact; - const uint32_t index = symap_search(map, sym, &exact); - if (exact) { - assert(!strcmp(map->symbols[map->index[index] - 1], sym)); - return map->index[index]; - } - - const uint32_t id = ++map->size; - char* const str = symap_strdup(sym); - - /* Append new symbol to symbols array */ - map->symbols = (char**)realloc(map->symbols, map->size * sizeof(str)); - map->symbols[id - 1] = str; - - /* Insert new index element into sorted index */ - map->index = (uint32_t*)realloc(map->index, map->size * sizeof(uint32_t)); - if (index < map->size - 1) { - memmove(map->index + index + 1, - map->index + index, - (map->size - index - 1) * sizeof(uint32_t)); - } - - map->index[index] = id; - - return id; + // Search for existing symbol + bool exact = false; + const uint32_t index = symap_search(map, sym, &exact); + if (exact) { + assert(!strcmp(map->symbols[map->index[index] - 1], sym)); + return map->index[index]; + } + + // Claim a new highest ID + const uint32_t id = map->size + 1; + + // Grow symbol array + char** new_symbols = (char**)realloc(map->symbols, id * sizeof(sym)); + if (!new_symbols) { + return 0; + } + + map->symbols = new_symbols; + + // Grow index array + uint32_t* new_index = (uint32_t*)realloc(map->index, id * sizeof(index)); + if (!new_index) { + return 0; + } + + map->index = new_index; + + // Append new symbol to symbols array + map->size = id; + map->symbols[id - 1] = symap_strdup(sym); + + // Insert new index element into sorted index + map->index = new_index; + if (index < map->size - 1) { + memmove(map->index + index + 1, + map->index + index, + (map->size - index - 1) * sizeof(uint32_t)); + } + + map->index[index] = id; + + return id; } const char* -symap_unmap(Symap* map, uint32_t id) +symap_unmap(const Symap* const map, const uint32_t id) { - if (id == 0) { - return NULL; - } else if (id <= map->size) { - return map->symbols[id - 1]; - } - return NULL; + if (id == 0) { + return NULL; + } + + if (id <= map->size) { + return map->symbols[id - 1]; + } + + return NULL; } -#ifdef STANDALONE +#ifdef SYMAP_STANDALONE -#include <stdio.h> +# include <stdio.h> static void -symap_dump(Symap* map) +symap_dump(const Symap* const map) +{ + fprintf(stderr, "{\n"); + for (uint32_t i = 0; i < map->size; ++i) { + fprintf( + stderr, "\t%u = %s\n", map->index[i], map->symbols[map->index[i] - 1]); + } + fprintf(stderr, "}\n"); +} + +static int +symap_test(Symap* const map) { - fprintf(stderr, "{\n"); - for (uint32_t i = 0; i < map->size; ++i) { - fprintf(stderr, "\t%u = %s\n", - map->index[i], map->symbols[map->index[i] - 1]); - } - fprintf(stderr, "}\n"); +# define N_SYMS 5 + + static const char* const syms[N_SYMS] = { + "hello", "bonjour", "goodbye", "aloha", "salut"}; + + for (int i = 0; i < N_SYMS; ++i) { + if (symap_try_map(map, syms[i])) { + return fprintf(stderr, "error: Symbol already mapped\n"); + } + + const uint32_t id = symap_map(map, syms[i]); + if (!id) { + return fprintf(stderr, "error: Failed to insert ID\n"); + } + + if (!!strcmp(map->symbols[id - 1], syms[i])) { + return fprintf(stderr, "error: Corrupt symbol table\n"); + } + + if (symap_map(map, syms[i]) != id) { + return fprintf(stderr, "error: Remapped symbol to a different ID\n"); + } + + symap_dump(map); + } + + return 0; + +# undef N_SYMS } int -main() +main(void) { - #define N_SYMS 5 - char* syms[N_SYMS] = { - "hello", "bonjour", "goodbye", "aloha", "salut" - }; - - Symap* map = symap_new(); - for (int i = 0; i < N_SYMS; ++i) { - if (symap_try_map(map, syms[i])) { - fprintf(stderr, "error: Symbol already mapped\n"); - return 1; - } - - const uint32_t id = symap_map(map, syms[i]); - if (strcmp(map->symbols[id - 1], syms[i])) { - fprintf(stderr, "error: Corrupt symbol table\n"); - return 1; - } - - if (symap_map(map, syms[i]) != id) { - fprintf(stderr, "error: Remapped symbol to a different ID\n"); - return 1; - } - - symap_dump(map); - } - - symap_free(map); - return 0; + Symap* const map = symap_new(); + const int st = symap_test(map); + + symap_free(map); + return st; } -#endif /* STANDALONE */ +#endif // SYMAP_STANDALONE diff --git a/src/symap.h b/src/symap.h index 918d914..66a1514 100644 --- a/src/symap.h +++ b/src/symap.h @@ -1,18 +1,5 @@ -/* - Copyright 2011-2014 David Robillard <http://drobilla.net> - - Permission to use, copy, modify, and/or distribute this software for any - purpose with or without fee is hereby granted, provided that the above - copyright notice and this permission notice appear in all copies. - - THIS SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES - WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF - MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR - ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES - WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN - ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF - OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. -*/ +// Copyright 2011-2022 David Robillard <d@drobilla.net> +// SPDX-License-Identifier: ISC /** @file symap.h API for Symap, a basic symbol map (string interner). @@ -25,44 +12,30 @@ #ifndef SYMAP_H #define SYMAP_H -#include <stdint.h> +#include <zix/attributes.h> -struct SymapImpl; +#include <stdint.h> typedef struct SymapImpl Symap; -/** - Create a new symbol map. -*/ -Symap* +/// Create a new symbol map +ZIX_MALLOC_FUNC Symap* symap_new(void); -/** - Free a symbol map. -*/ +/// Free a symbol map void symap_free(Symap* map); -/** - Map a string to a symbol ID if it is already mapped, otherwise return 0. -*/ -uint32_t -symap_try_map(Symap* map, const char* sym); - -/** - Map a string to a symbol ID. +/// Map a string to a symbol if it is already mapped, otherwise return 0 +ZIX_PURE_FUNC uint32_t +symap_try_map(const Symap* map, const char* sym); - Note that 0 is never a valid symbol ID. -*/ +/// Map a string to a symbol uint32_t symap_map(Symap* map, const char* sym); -/** - Unmap a symbol ID back to a symbol, or NULL if no such ID exists. - - Note that 0 is never a valid symbol ID. -*/ -const char* -symap_unmap(Symap* map, uint32_t id); +/// Unmap a symbol back to a string if possible, otherwise return NULL +ZIX_PURE_FUNC const char* +symap_unmap(const Symap* map, uint32_t id); -#endif /* SYMAP_H */ +#endif // SYMAP_H diff --git a/src/types.h b/src/types.h new file mode 100644 index 0000000..4f25301 --- /dev/null +++ b/src/types.h @@ -0,0 +1,38 @@ +// Copyright 2007-2024 David Robillard <d@drobilla.net> +// SPDX-License-Identifier: ISC + +#ifndef JALV_TYPES_H +#define JALV_TYPES_H + +#include "attributes.h" + +// Basic internal type declarations +JALV_BEGIN_DECLS + +/// Process thread running state +typedef enum { + JALV_RUNNING, ///< Active and running the plugin + JALV_PAUSED, ///< Active but bypassing the plugin (silent) +} JalvRunState; + +/// "Global" application state +typedef struct JalvImpl Jalv; + +/// Audio/MIDI backend +typedef struct JalvBackendImpl JalvBackend; + +/// Plugin port "direction" +typedef enum { FLOW_UNKNOWN, FLOW_INPUT, FLOW_OUTPUT } PortFlow; + +/// Plugin port type +typedef enum { + TYPE_UNKNOWN, + TYPE_CONTROL, + TYPE_AUDIO, + TYPE_EVENT, + TYPE_CV +} PortType; + +JALV_END_DECLS + +#endif // JALV_TYPES_H diff --git a/src/urids.c b/src/urids.c new file mode 100644 index 0000000..ff74635 --- /dev/null +++ b/src/urids.c @@ -0,0 +1,56 @@ +// Copyright 2022-2024 David Robillard <d@drobilla.net> +// SPDX-License-Identifier: ISC + +#include "urids.h" + +#include "mapper.h" + +#include <lv2/atom/atom.h> +#include <lv2/buf-size/buf-size.h> +#include <lv2/log/log.h> +#include <lv2/midi/midi.h> +#include <lv2/parameters/parameters.h> +#include <lv2/patch/patch.h> +#include <lv2/time/time.h> +#include <lv2/ui/ui.h> + +void +jalv_init_urids(JalvMapper* const mapper, JalvURIDs* const urids) +{ +#define MAP_URI(uri) jalv_mapper_map_uri(mapper, (uri)) + + urids->atom_Chunk = MAP_URI(LV2_ATOM__Chunk); + urids->atom_Float = MAP_URI(LV2_ATOM__Float); + urids->atom_Int = MAP_URI(LV2_ATOM__Int); + urids->atom_Object = MAP_URI(LV2_ATOM__Object); + urids->atom_Path = MAP_URI(LV2_ATOM__Path); + urids->atom_Sequence = MAP_URI(LV2_ATOM__Sequence); + urids->atom_String = MAP_URI(LV2_ATOM__String); + urids->atom_eventTransfer = MAP_URI(LV2_ATOM__eventTransfer); + urids->bufsz_maxBlockLength = MAP_URI(LV2_BUF_SIZE__maxBlockLength); + urids->bufsz_minBlockLength = MAP_URI(LV2_BUF_SIZE__minBlockLength); + urids->bufsz_sequenceSize = MAP_URI(LV2_BUF_SIZE__sequenceSize); + urids->log_Error = MAP_URI(LV2_LOG__Error); + urids->log_Trace = MAP_URI(LV2_LOG__Trace); + urids->log_Warning = MAP_URI(LV2_LOG__Warning); + urids->midi_MidiEvent = MAP_URI(LV2_MIDI__MidiEvent); + urids->param_sampleRate = MAP_URI(LV2_PARAMETERS__sampleRate); + urids->patch_Get = MAP_URI(LV2_PATCH__Get); + urids->patch_Put = MAP_URI(LV2_PATCH__Put); + urids->patch_Set = MAP_URI(LV2_PATCH__Set); + urids->patch_body = MAP_URI(LV2_PATCH__body); + urids->patch_property = MAP_URI(LV2_PATCH__property); + urids->patch_value = MAP_URI(LV2_PATCH__value); + urids->time_Position = MAP_URI(LV2_TIME__Position); + urids->time_bar = MAP_URI(LV2_TIME__bar); + urids->time_barBeat = MAP_URI(LV2_TIME__barBeat); + urids->time_beatUnit = MAP_URI(LV2_TIME__beatUnit); + urids->time_beatsPerBar = MAP_URI(LV2_TIME__beatsPerBar); + urids->time_beatsPerMinute = MAP_URI(LV2_TIME__beatsPerMinute); + urids->time_frame = MAP_URI(LV2_TIME__frame); + urids->time_speed = MAP_URI(LV2_TIME__speed); + urids->ui_scaleFactor = MAP_URI(LV2_UI__scaleFactor); + urids->ui_updateRate = MAP_URI(LV2_UI__updateRate); + +#undef MAP_URI +} diff --git a/src/urids.h b/src/urids.h new file mode 100644 index 0000000..7ac1a45 --- /dev/null +++ b/src/urids.h @@ -0,0 +1,55 @@ +// Copyright 2007-2022 David Robillard <d@drobilla.net> +// SPDX-License-Identifier: ISC + +#ifndef JALV_URIDS_H +#define JALV_URIDS_H + +#include "attributes.h" +#include "mapper.h" + +#include <lv2/urid/urid.h> + +// Cached LV2 URIDs +JALV_BEGIN_DECLS + +typedef struct { + LV2_URID atom_Chunk; + LV2_URID atom_Float; + LV2_URID atom_Int; + LV2_URID atom_Object; + LV2_URID atom_Path; + LV2_URID atom_Sequence; + LV2_URID atom_String; + LV2_URID atom_eventTransfer; + LV2_URID bufsz_maxBlockLength; + LV2_URID bufsz_minBlockLength; + LV2_URID bufsz_sequenceSize; + LV2_URID log_Error; + LV2_URID log_Trace; + LV2_URID log_Warning; + LV2_URID midi_MidiEvent; + LV2_URID param_sampleRate; + LV2_URID patch_Get; + LV2_URID patch_Put; + LV2_URID patch_Set; + LV2_URID patch_body; + LV2_URID patch_property; + LV2_URID patch_value; + LV2_URID time_Position; + LV2_URID time_bar; + LV2_URID time_barBeat; + LV2_URID time_beatUnit; + LV2_URID time_beatsPerBar; + LV2_URID time_beatsPerMinute; + LV2_URID time_frame; + LV2_URID time_speed; + LV2_URID ui_scaleFactor; + LV2_URID ui_updateRate; +} JalvURIDs; + +void +jalv_init_urids(JalvMapper* mapper, JalvURIDs* urids); + +JALV_END_DECLS + +#endif // JALV_URIDS_H diff --git a/src/worker.c b/src/worker.c index 79bb7b7..f03c823 100644 --- a/src/worker.c +++ b/src/worker.c @@ -1,141 +1,229 @@ -/* - Copyright 2007-2016 David Robillard <http://drobilla.net> - - Permission to use, copy, modify, and/or distribute this software for any - purpose with or without fee is hereby granted, provided that the above - copyright notice and this permission notice appear in all copies. - - THIS SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES - WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF - MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR - ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES - WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN - ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF - OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. -*/ +// Copyright 2007-2022 David Robillard <d@drobilla.net> +// SPDX-License-Identifier: ISC #include "worker.h" +#include <lv2/core/lv2.h> +#include <lv2/worker/worker.h> +#include <zix/ring.h> +#include <zix/sem.h> +#include <zix/status.h> +#include <zix/thread.h> + +#include <stdio.h> +#include <stdlib.h> + +#define MAX_PACKET_SIZE 4096U + +typedef enum { + STATE_SINGLE_THREADED, ///< Single-threaded worker (only state) + STATE_STOPPED, ///< Thread is exited + STATE_LAUNCHED, ///< Thread is running + STATE_MUST_EXIT, ///< Thread exit requested +} WorkerState; + +struct JalvWorkerImpl { + ZixRing* requests; ///< Requests to the worker + ZixRing* responses; ///< Responses from the worker + void* response; ///< Worker response buffer + ZixSem* lock; ///< Lock for plugin work() method + ZixSem sem; ///< Worker semaphore + WorkerState state; ///< Worker state + ZixThread thread; ///< Worker thread + LV2_Handle handle; ///< Plugin handle + const LV2_Worker_Interface* iface; ///< Plugin worker interface +}; + +static LV2_Worker_Status +jalv_worker_write_packet(ZixRing* const target, + const uint32_t size, + const void* const data) +{ + ZixRingTransaction tx = zix_ring_begin_write(target); + if (zix_ring_amend_write(target, &tx, &size, sizeof(size)) || + zix_ring_amend_write(target, &tx, data, size)) { + return LV2_WORKER_ERR_NO_SPACE; + } + + zix_ring_commit_write(target, &tx); + return LV2_WORKER_SUCCESS; +} + static LV2_Worker_Status jalv_worker_respond(LV2_Worker_Respond_Handle handle, - uint32_t size, + const uint32_t size, const void* data) { - JalvWorker* worker = (JalvWorker*)handle; - zix_ring_write(worker->responses, (const char*)&size, sizeof(size)); - zix_ring_write(worker->responses, (const char*)data, size); - return LV2_WORKER_SUCCESS; + return jalv_worker_write_packet(((JalvWorker*)handle)->responses, size, data); +} + +static ZixThreadResult ZIX_THREAD_FUNC +worker_func(void* const data) +{ + JalvWorker* const worker = (JalvWorker*)data; + void* buf = NULL; + + while (true) { + // Wait for a request + zix_sem_wait(&worker->sem); + if (worker->state == STATE_MUST_EXIT) { + break; + } + + // Read the size header of the request + uint32_t size = 0; + zix_ring_read(worker->requests, &size, sizeof(size)); + + // Reallocate buffer to accommodate request if necessary + void* const new_buf = realloc(buf, size); + if (new_buf) { + // Read request into buffer + buf = new_buf; + zix_ring_read(worker->requests, buf, size); + + // Lock and dispatch request to plugin's work handler + zix_sem_wait(worker->lock); + worker->iface->work( + worker->handle, jalv_worker_respond, worker, size, buf); + zix_sem_post(worker->lock); + + } else { + // Reallocation failed, skip request to avoid corrupting ring + zix_ring_skip(worker->requests, size); + } + } + + free(buf); + worker->state = STATE_STOPPED; + return ZIX_THREAD_RESULT; } -static void* -worker_func(void* data) +JalvWorker* +jalv_worker_new(ZixSem* const lock, const bool threaded) { - JalvWorker* worker = (JalvWorker*)data; - Jalv* jalv = worker->jalv; - void* buf = NULL; - while (true) { - zix_sem_wait(&worker->sem); - if (jalv->exit) { - break; - } - - uint32_t size = 0; - zix_ring_read(worker->requests, (char*)&size, sizeof(size)); - - if (!(buf = realloc(buf, size))) { - fprintf(stderr, "error: realloc() failed\n"); - free(buf); - return NULL; - } - - zix_ring_read(worker->requests, (char*)buf, size); - - zix_sem_wait(&jalv->work_lock); - worker->iface->work( - jalv->instance->lv2_handle, jalv_worker_respond, worker, size, buf); - zix_sem_post(&jalv->work_lock); - } - - free(buf); - return NULL; + JalvWorker* const worker = (JalvWorker*)calloc(1, sizeof(JalvWorker)); + ZixRing* const requests = zix_ring_new(NULL, MAX_PACKET_SIZE); + ZixRing* const responses = zix_ring_new(NULL, MAX_PACKET_SIZE); + void* const response = calloc(1, MAX_PACKET_SIZE); + + if (worker && responses && response) { + worker->requests = requests; + worker->responses = responses; + worker->response = response; + worker->lock = lock; + worker->state = threaded ? STATE_STOPPED : STATE_SINGLE_THREADED; + + zix_ring_mlock(requests); + zix_ring_mlock(responses); + return worker; + } + + free(response); + zix_ring_free(responses); + zix_ring_free(requests); + free(worker); + return NULL; } void -jalv_worker_init(ZIX_UNUSED Jalv* jalv, - JalvWorker* worker, - const LV2_Worker_Interface* iface, - bool threaded) +jalv_worker_free(JalvWorker* const worker) { - worker->iface = iface; - worker->threaded = threaded; - if (threaded) { - zix_thread_create(&worker->thread, 4096, worker_func, worker); - worker->requests = zix_ring_new(4096); - zix_ring_mlock(worker->requests); - } - worker->responses = zix_ring_new(4096); - worker->response = malloc(4096); - zix_ring_mlock(worker->responses); + if (worker) { + jalv_worker_exit(worker); + zix_ring_free(worker->requests); + zix_ring_free(worker->responses); + free(worker->response); + free(worker); + } +} + +ZixStatus +jalv_worker_launch(JalvWorker* const worker) +{ + ZixStatus st = ZIX_STATUS_SUCCESS; + if (worker->state == STATE_STOPPED) { + if ((st = zix_sem_init(&worker->sem, 0))) { + return st; + } + + if ((st = zix_thread_create(&worker->thread, 4096U, worker_func, worker))) { + zix_sem_destroy(&worker->sem); + return st; + } + + worker->state = STATE_LAUNCHED; + } + return st; } void -jalv_worker_finish(JalvWorker* worker) +jalv_worker_exit(JalvWorker* const worker) { - if (worker->threaded) { - zix_sem_post(&worker->sem); - zix_thread_join(worker->thread, NULL); - } + if (worker && worker->state == STATE_LAUNCHED) { + worker->state = STATE_MUST_EXIT; + zix_sem_post(&worker->sem); + zix_thread_join(worker->thread); + } } void -jalv_worker_destroy(JalvWorker* worker) +jalv_worker_attach(JalvWorker* const worker, + const LV2_Worker_Interface* const iface, + LV2_Handle handle) { - if (worker->requests) { - if (worker->threaded) { - zix_ring_free(worker->requests); - } - zix_ring_free(worker->responses); - free(worker->response); - } + if (worker) { + worker->iface = iface; + worker->handle = handle; + } } LV2_Worker_Status jalv_worker_schedule(LV2_Worker_Schedule_Handle handle, - uint32_t size, - const void* data) + const uint32_t size, + const void* const data) { - JalvWorker* worker = (JalvWorker*)handle; - Jalv* jalv = worker->jalv; - if (worker->threaded) { - // Schedule a request to be executed by the worker thread - zix_ring_write(worker->requests, (const char*)&size, sizeof(size)); - zix_ring_write(worker->requests, (const char*)data, size); - zix_sem_post(&worker->sem); - } else { - // Execute work immediately in this thread - zix_sem_wait(&jalv->work_lock); - worker->iface->work( - jalv->instance->lv2_handle, jalv_worker_respond, worker, size, data); - zix_sem_post(&jalv->work_lock); - } - return LV2_WORKER_SUCCESS; + JalvWorker* const worker = (JalvWorker*)handle; + LV2_Worker_Status st = LV2_WORKER_SUCCESS; + + if (!worker || !size || worker->state == STATE_STOPPED) { + st = LV2_WORKER_ERR_UNKNOWN; + + } else if (worker->state == STATE_LAUNCHED) { + // Schedule a request to be executed by the worker thread + if (!(st = jalv_worker_write_packet(worker->requests, size, data))) { + zix_sem_post(&worker->sem); + } + + } else if (worker->state == STATE_SINGLE_THREADED) { + // Execute work immediately in this thread + zix_sem_wait(worker->lock); + st = worker->iface->work( + worker->handle, jalv_worker_respond, worker, size, data); + zix_sem_post(worker->lock); + } + + return st; } void -jalv_worker_emit_responses(JalvWorker* worker, LilvInstance* instance) +jalv_worker_emit_responses(JalvWorker* const worker, LV2_Handle lv2_handle) { - if (worker->responses) { - uint32_t read_space = zix_ring_read_space(worker->responses); - while (read_space) { - uint32_t size = 0; - zix_ring_read(worker->responses, (char*)&size, sizeof(size)); - - zix_ring_read(worker->responses, (char*)worker->response, size); - - worker->iface->work_response( - instance->lv2_handle, size, worker->response); + static const uint32_t size_size = (uint32_t)sizeof(uint32_t); + + if (worker && worker->responses) { + uint32_t size = 0U; + while (zix_ring_read(worker->responses, &size, size_size) == size_size) { + if (zix_ring_read(worker->responses, worker->response, size) == size) { + worker->iface->work_response(lv2_handle, size, worker->response); + } + } + } +} - read_space -= sizeof(size) + size; - } - } +void +jalv_worker_end_run(JalvWorker* const worker) +{ + if (worker && worker->iface && worker->iface->end_run) { + worker->iface->end_run(worker->handle); + } } diff --git a/src/worker.h b/src/worker.h index 942b993..0e39894 100644 --- a/src/worker.h +++ b/src/worker.h @@ -1,39 +1,113 @@ -/* - Copyright 2007-2016 David Robillard <http://drobilla.net> +// Copyright 2007-2022 David Robillard <d@drobilla.net> +// SPDX-License-Identifier: ISC - Permission to use, copy, modify, and/or distribute this software for any - purpose with or without fee is hereby granted, provided that the above - copyright notice and this permission notice appear in all copies. +#ifndef JALV_WORKER_H +#define JALV_WORKER_H - THIS SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES - WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF - MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR - ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES - WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN - ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF - OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. +#include "attributes.h" + +#include <lv2/core/lv2.h> +#include <lv2/worker/worker.h> +#include <zix/sem.h> +#include <zix/status.h> + +#include <stdbool.h> +#include <stdint.h> + +// Worker implementation +JALV_BEGIN_DECLS + +/** + A worker for running non-realtime tasks for plugins. + + The worker can be used in threaded mode, which allows non-realtime work to be + done with latency when running realtime, or non-threaded mode, which performs + work immediately for state restoration or offline rendering. */ +typedef struct JalvWorkerImpl JalvWorker; + +/** + Allocate a new worker and launch its thread if necessary. -#include "jalv_internal.h" + @param lock Pointer to lock used to guard doing work. + @param threaded If true, launch a thread to perform work in. + @return A newly allocated worker, or null on error. +*/ +JalvWorker* +jalv_worker_new(ZixSem* lock, bool threaded); -#include "lv2/worker/worker.h" +/** + Free a worker allocated with jalv_worker_new(). + Calls jalv_worker_exit() to terminate the running thread if necessary. +*/ void -jalv_worker_init(Jalv* jalv, - JalvWorker* worker, - const LV2_Worker_Interface* iface, - bool threaded); +jalv_worker_free(JalvWorker* worker); + +/** + Launch the worker's thread. + For threaded workers, this launches the thread if it isn't already running. + For non-threaded workers, this does nothing. + + @return Zero on success, or a non-zero error code if launching failed. +*/ +ZixStatus +jalv_worker_launch(JalvWorker* worker); + +/** + Terminate the worker's thread if necessary. + + For threaded workers, this blocks until the thread has exited. For + non-threaded workers, this does nothing. +*/ void -jalv_worker_finish(JalvWorker* worker); +jalv_worker_exit(JalvWorker* worker); +/** + Attach the worker to a plugin instance. + + This must be called before scheduling any work. + + @param worker Worker to activate and attach to a plugin. + @param iface Worker interface from plugin. + @param handle Handle to the LV2 plugin this worker is for. +*/ void -jalv_worker_destroy(JalvWorker* worker); +jalv_worker_attach(JalvWorker* worker, + const LV2_Worker_Interface* iface, + LV2_Handle handle); + +/** + Schedule work to be performed by the worker in the audio thread. + For threaded workers, this enqueues a request that will be handled by the + worker thread asynchronously. For non-threaded workers, the work is + performed immediately before returning. +*/ LV2_Worker_Status jalv_worker_schedule(LV2_Worker_Schedule_Handle handle, uint32_t size, const void* data); +/** + Emit any pending responses to the plugin in the audio thread. + + This dispatches responses from work that has been completed since the last + call, so the plugin knows it is finished and can apply the changes. +*/ void -jalv_worker_emit_responses(JalvWorker* worker, LilvInstance* instance); +jalv_worker_emit_responses(JalvWorker* worker, LV2_Handle lv2_handle); + +/** + Notify the plugin that the run() cycle is finished. + + This must be called near the end of every cycle, after any potential calls + to jalv_worker_emit_responses(). +*/ +void +jalv_worker_end_run(JalvWorker* worker); + +JALV_END_DECLS + +#endif // JALV_WORKER_H diff --git a/src/zix/common.h b/src/zix/common.h deleted file mode 100644 index 9318d0e..0000000 --- a/src/zix/common.h +++ /dev/null @@ -1,116 +0,0 @@ -/* - Copyright 2016 David Robillard <http://drobilla.net> - - Permission to use, copy, modify, and/or distribute this software for any - purpose with or without fee is hereby granted, provided that the above - copyright notice and this permission notice appear in all copies. - - THIS SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES - WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF - MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR - ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES - WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN - ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF - OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. -*/ - -#ifndef ZIX_COMMON_H -#define ZIX_COMMON_H - -/** - @addtogroup zix - @{ -*/ - -/** @cond */ -#ifdef ZIX_SHARED -# ifdef _WIN32 -# define ZIX_LIB_IMPORT __declspec(dllimport) -# define ZIX_LIB_EXPORT __declspec(dllexport) -# else -# define ZIX_LIB_IMPORT __attribute__((visibility("default"))) -# define ZIX_LIB_EXPORT __attribute__((visibility("default"))) -# endif -# ifdef ZIX_INTERNAL -# define ZIX_API ZIX_LIB_EXPORT -# else -# define ZIX_API ZIX_LIB_IMPORT -# endif -# define ZIX_PRIVATE static -#elif defined(ZIX_INLINE) -# define ZIX_API static inline -# define ZIX_PRIVATE static inline -#else -# define ZIX_API -# define ZIX_PRIVATE static -#endif -/** @endcond */ - -#ifdef __cplusplus -extern "C" { -#else -# include <stdbool.h> -#endif - -#ifdef __GNUC__ -#define ZIX_UNUSED __attribute__((__unused__)) -#else -#define ZIX_UNUSED -#endif - -typedef enum { - ZIX_STATUS_SUCCESS, - ZIX_STATUS_ERROR, - ZIX_STATUS_NO_MEM, - ZIX_STATUS_NOT_FOUND, - ZIX_STATUS_EXISTS, - ZIX_STATUS_BAD_ARG, - ZIX_STATUS_BAD_PERMS -} ZixStatus; - -static inline const char* -zix_strerror(const ZixStatus status) -{ - switch (status) { - case ZIX_STATUS_SUCCESS: - return "Success"; - case ZIX_STATUS_ERROR: - return "Unknown error"; - case ZIX_STATUS_NO_MEM: - return "Out of memory"; - case ZIX_STATUS_NOT_FOUND: - return "Not found"; - case ZIX_STATUS_EXISTS: - return "Exists"; - case ZIX_STATUS_BAD_ARG: - return "Bad argument"; - case ZIX_STATUS_BAD_PERMS: - return "Bad permissions"; - } - return "Unknown error"; -} - -/** - Function for comparing two elements. -*/ -typedef int (*ZixComparator)(const void* a, const void* b, void* user_data); - -/** - Function for testing equality of two elements. -*/ -typedef bool (*ZixEqualFunc)(const void* a, const void* b); - -/** - Function to destroy an element. -*/ -typedef void (*ZixDestroyFunc)(void* ptr); - -/** - @} -*/ - -#ifdef __cplusplus -} /* extern "C" */ -#endif - -#endif /* ZIX_COMMON_H */ diff --git a/src/zix/ring.c b/src/zix/ring.c deleted file mode 100644 index 6af9e07..0000000 --- a/src/zix/ring.c +++ /dev/null @@ -1,228 +0,0 @@ -/* - Copyright 2011-2017 David Robillard <http://drobilla.net> - - Permission to use, copy, modify, and/or distribute this software for any - purpose with or without fee is hereby granted, provided that the above - copyright notice and this permission notice appear in all copies. - - THIS SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES - WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF - MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR - ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES - WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN - ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF - OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. -*/ - -#include "zix/ring.h" - -#ifdef HAVE_MLOCK -# include <sys/mman.h> -# define ZIX_MLOCK(ptr, size) mlock((ptr), (size)) -#elif defined(_WIN32) -# include <windows.h> -# define ZIX_MLOCK(ptr, size) VirtualLock((ptr), (size)) -#else -# pragma message("warning: No memory locking, possible RT violations") -# define ZIX_MLOCK(ptr, size) -#endif - -#if __STDC_VERSION__ >= 201112L && !defined(__STDC_NO_ATOMICS__) -# include <stdatomic.h> -# define ZIX_WRITE_BARRIER() atomic_thread_fence(memory_order_release) -# define ZIX_READ_BARRIER() atomic_thread_fence(memory_order_acquire) -#elif defined(__APPLE__) /* Pre 10.12 */ -# include <libkern/OSAtomic.h> -# define ZIX_WRITE_BARRIER() OSMemoryBarrier() -# define ZIX_READ_BARRIER() OSMemoryBarrier() -#elif defined(_WIN32) -# include <windows.h> -# define ZIX_WRITE_BARRIER() MemoryBarrier() -# define ZIX_READ_BARRIER() MemoryBarrier() -#elif (__GNUC__ > 4) || (__GNUC__ == 4 && __GNUC_MINOR__ >= 1) -# define ZIX_WRITE_BARRIER() __sync_synchronize() -# define ZIX_READ_BARRIER() __sync_synchronize() -#else -# pragma message("warning: No memory barriers, possible SMP bugs") -# define ZIX_WRITE_BARRIER() -# define ZIX_READ_BARRIER() -#endif - -#include <stdint.h> -#include <stdlib.h> -#include <string.h> - -struct ZixRingImpl { - uint32_t write_head; ///< Read index into buf - uint32_t read_head; ///< Write index into buf - uint32_t size; ///< Size (capacity) in bytes - uint32_t size_mask; ///< Mask for fast modulo - char* buf; ///< Contents -}; - -static inline uint32_t -next_power_of_two(uint32_t size) -{ - // http://graphics.stanford.edu/~seander/bithacks.html#RoundUpPowerOf2 - size--; - size |= size >> 1; - size |= size >> 2; - size |= size >> 4; - size |= size >> 8; - size |= size >> 16; - size++; - return size; -} - -ZixRing* -zix_ring_new(uint32_t size) -{ - ZixRing* ring = (ZixRing*)malloc(sizeof(ZixRing)); - ring->write_head = 0; - ring->read_head = 0; - ring->size = next_power_of_two(size); - ring->size_mask = ring->size - 1; - ring->buf = (char*)malloc(ring->size); - return ring; -} - -void -zix_ring_free(ZixRing* ring) -{ - if (ring) { - free(ring->buf); - free(ring); - } -} - -void -zix_ring_mlock(ZixRing* ring) -{ - ZIX_MLOCK(ring, sizeof(ZixRing)); - ZIX_MLOCK(ring->buf, ring->size); -} - -void -zix_ring_reset(ZixRing* ring) -{ - ring->write_head = 0; - ring->read_head = 0; -} - -static inline uint32_t -read_space_internal(const ZixRing* ring, uint32_t r, uint32_t w) -{ - if (r < w) { - return w - r; - } else { - return (w - r + ring->size) & ring->size_mask; - } -} - -uint32_t -zix_ring_read_space(const ZixRing* ring) -{ - return read_space_internal(ring, ring->read_head, ring->write_head); -} - -static inline uint32_t -write_space_internal(const ZixRing* ring, uint32_t r, uint32_t w) -{ - if (r == w) { - return ring->size - 1; - } else if (r < w) { - return ((r - w + ring->size) & ring->size_mask) - 1; - } else { - return (r - w) - 1; - } -} - -uint32_t -zix_ring_write_space(const ZixRing* ring) -{ - return write_space_internal(ring, ring->read_head, ring->write_head); -} - -uint32_t -zix_ring_capacity(const ZixRing* ring) -{ - return ring->size - 1; -} - -static inline uint32_t -peek_internal(const ZixRing* ring, uint32_t r, uint32_t w, - uint32_t size, void* dst) -{ - if (read_space_internal(ring, r, w) < size) { - return 0; - } - - if (r + size < ring->size) { - memcpy(dst, &ring->buf[r], size); - } else { - const uint32_t first_size = ring->size - r; - memcpy(dst, &ring->buf[r], first_size); - memcpy((char*)dst + first_size, &ring->buf[0], size - first_size); - } - - return size; -} - -uint32_t -zix_ring_peek(ZixRing* ring, void* dst, uint32_t size) -{ - return peek_internal(ring, ring->read_head, ring->write_head, size, dst); -} - -uint32_t -zix_ring_read(ZixRing* ring, void* dst, uint32_t size) -{ - const uint32_t r = ring->read_head; - const uint32_t w = ring->write_head; - - if (peek_internal(ring, r, w, size, dst)) { - ZIX_READ_BARRIER(); - ring->read_head = (r + size) & ring->size_mask; - return size; - } else { - return 0; - } -} - -uint32_t -zix_ring_skip(ZixRing* ring, uint32_t size) -{ - const uint32_t r = ring->read_head; - const uint32_t w = ring->write_head; - if (read_space_internal(ring, r, w) < size) { - return 0; - } - - ZIX_READ_BARRIER(); - ring->read_head = (r + size) & ring->size_mask; - return size; -} - -uint32_t -zix_ring_write(ZixRing* ring, const void* src, uint32_t size) -{ - const uint32_t r = ring->read_head; - const uint32_t w = ring->write_head; - if (write_space_internal(ring, r, w) < size) { - return 0; - } - - if (w + size <= ring->size) { - memcpy(&ring->buf[w], src, size); - ZIX_WRITE_BARRIER(); - ring->write_head = (w + size) & ring->size_mask; - } else { - const uint32_t this_size = ring->size - w; - memcpy(&ring->buf[w], src, this_size); - memcpy(&ring->buf[0], (const char*)src + this_size, size - this_size); - ZIX_WRITE_BARRIER(); - ring->write_head = size - this_size; - } - - return size; -} diff --git a/src/zix/ring.h b/src/zix/ring.h deleted file mode 100644 index c687667..0000000 --- a/src/zix/ring.h +++ /dev/null @@ -1,130 +0,0 @@ -/* - Copyright 2011-2014 David Robillard <http://drobilla.net> - - Permission to use, copy, modify, and/or distribute this software for any - purpose with or without fee is hereby granted, provided that the above - copyright notice and this permission notice appear in all copies. - - THIS SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES - WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF - MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR - ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES - WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN - ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF - OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. -*/ - -#ifndef ZIX_RING_H -#define ZIX_RING_H - -#include "zix/common.h" - -#include <stdint.h> - -#ifdef __cplusplus -extern "C" { -#endif - -/** - @addtogroup zix - @{ - @name Ring - @{ -*/ - -/** - A lock-free ring buffer. - - Thread-safe with a single reader and single writer, and realtime safe - on both ends. -*/ -typedef struct ZixRingImpl ZixRing; - -/** - Create a new ring. - @param size Size in bytes (note this may be rounded up). - - At most `size` - 1 bytes may be stored in the ring at once. -*/ -ZixRing* -zix_ring_new(uint32_t size); - -/** - Destroy a ring. -*/ -void -zix_ring_free(ZixRing* ring); - -/** - Lock the ring data into physical memory. - - This function is NOT thread safe or real-time safe, but it should be called - after zix_ring_new() to lock all ring memory to avoid page faults while - using the ring (i.e. this function MUST be called first in order for the - ring to be truly real-time safe). - -*/ -void -zix_ring_mlock(ZixRing* ring); - -/** - Reset (empty) a ring. - - This function is NOT thread-safe, it may only be called when there are no - readers or writers. -*/ -void -zix_ring_reset(ZixRing* ring); - -/** - Return the number of bytes of space available for reading. -*/ -uint32_t -zix_ring_read_space(const ZixRing* ring); - -/** - Return the number of bytes of space available for writing. -*/ -uint32_t -zix_ring_write_space(const ZixRing* ring); - -/** - Return the capacity (i.e. total write space when empty). -*/ -uint32_t -zix_ring_capacity(const ZixRing* ring); - -/** - Read from the ring without advancing the read head. -*/ -uint32_t -zix_ring_peek(ZixRing* ring, void* dst, uint32_t size); - -/** - Read from the ring and advance the read head. -*/ -uint32_t -zix_ring_read(ZixRing* ring, void* dst, uint32_t size); - -/** - Skip data in the ring (advance read head without reading). -*/ -uint32_t -zix_ring_skip(ZixRing* ring, uint32_t size); - -/** - Write data to the ring. -*/ -uint32_t -zix_ring_write(ZixRing* ring, const void* src, uint32_t size); - -/** - @} - @} -*/ - -#ifdef __cplusplus -} /* extern "C" */ -#endif - -#endif /* ZIX_RING_H */ diff --git a/src/zix/sem.h b/src/zix/sem.h deleted file mode 100644 index e306052..0000000 --- a/src/zix/sem.h +++ /dev/null @@ -1,237 +0,0 @@ -/* - Copyright 2012-2014 David Robillard <http://drobilla.net> - - Permission to use, copy, modify, and/or distribute this software for any - purpose with or without fee is hereby granted, provided that the above - copyright notice and this permission notice appear in all copies. - - THIS SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES - WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF - MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR - ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES - WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN - ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF - OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. -*/ - -#ifndef ZIX_SEM_H -#define ZIX_SEM_H - -#include "zix/common.h" - -#ifdef __APPLE__ -# include <mach/mach.h> -#elif defined(_WIN32) -# include <limits.h> -# include <windows.h> -#else -# include <semaphore.h> -# include <errno.h> -#endif - -#ifdef __cplusplus -extern "C" { -#endif - -/** - @addtogroup zix - @{ - @name Semaphore - @{ -*/ - -/** - A counting semaphore. - - This is an integer that is always positive, and has two main operations: - increment (post) and decrement (wait). If a decrement can not be performed - (i.e. the value is 0) the caller will be blocked until another thread posts - and the operation can succeed. - - Semaphores can be created with any starting value, but typically this will - be 0 so the semaphore can be used as a simple signal where each post - corresponds to one wait. - - Semaphores are very efficient (much moreso than a mutex/cond pair). In - particular, at least on Linux, post is async-signal-safe, which means it - does not block and will not be interrupted. If you need to signal from - a realtime thread, this is the most appropriate primitive to use. -*/ -typedef struct ZixSemImpl ZixSem; - -/** - Create and initialize `sem` to `initial`. -*/ -static inline ZixStatus -zix_sem_init(ZixSem* sem, unsigned initial); - -/** - Destroy `sem`. -*/ -static inline void -zix_sem_destroy(ZixSem* sem); - -/** - Increment (and signal any waiters). - Realtime safe. -*/ -static inline void -zix_sem_post(ZixSem* sem); - -/** - Wait until count is > 0, then decrement. - Obviously not realtime safe. -*/ -static inline ZixStatus -zix_sem_wait(ZixSem* sem); - -/** - Non-blocking version of wait(). - - @return true if decrement was successful (lock was acquired). -*/ -static inline bool -zix_sem_try_wait(ZixSem* sem); - -/** - @cond -*/ - -#ifdef __APPLE__ - -struct ZixSemImpl { - semaphore_t sem; -}; - -static inline ZixStatus -zix_sem_init(ZixSem* sem, unsigned val) -{ - return semaphore_create(mach_task_self(), &sem->sem, SYNC_POLICY_FIFO, val) - ? ZIX_STATUS_ERROR : ZIX_STATUS_SUCCESS; -} - -static inline void -zix_sem_destroy(ZixSem* sem) -{ - semaphore_destroy(mach_task_self(), sem->sem); -} - -static inline void -zix_sem_post(ZixSem* sem) -{ - semaphore_signal(sem->sem); -} - -static inline ZixStatus -zix_sem_wait(ZixSem* sem) -{ - if (semaphore_wait(sem->sem) != KERN_SUCCESS) { - return ZIX_STATUS_ERROR; - } - return ZIX_STATUS_SUCCESS; -} - -static inline bool -zix_sem_try_wait(ZixSem* sem) -{ - const mach_timespec_t zero = { 0, 0 }; - return semaphore_timedwait(sem->sem, zero) == KERN_SUCCESS; -} - -#elif defined(_WIN32) - -struct ZixSemImpl { - HANDLE sem; -}; - -static inline ZixStatus -zix_sem_init(ZixSem* sem, unsigned initial) -{ - sem->sem = CreateSemaphore(NULL, initial, LONG_MAX, NULL); - return (sem->sem) ? ZIX_STATUS_ERROR : ZIX_STATUS_SUCCESS; -} - -static inline void -zix_sem_destroy(ZixSem* sem) -{ - CloseHandle(sem->sem); -} - -static inline void -zix_sem_post(ZixSem* sem) -{ - ReleaseSemaphore(sem->sem, 1, NULL); -} - -static inline ZixStatus -zix_sem_wait(ZixSem* sem) -{ - if (WaitForSingleObject(sem->sem, INFINITE) != WAIT_OBJECT_0) { - return ZIX_STATUS_ERROR; - } - return ZIX_STATUS_SUCCESS; -} - -static inline bool -zix_sem_try_wait(ZixSem* sem) -{ - return WaitForSingleObject(sem->sem, 0) == WAIT_OBJECT_0; -} - -#else /* !defined(__APPLE__) && !defined(_WIN32) */ - -struct ZixSemImpl { - sem_t sem; -}; - -static inline ZixStatus -zix_sem_init(ZixSem* sem, unsigned initial) -{ - return sem_init(&sem->sem, 0, initial) - ? ZIX_STATUS_ERROR : ZIX_STATUS_SUCCESS; -} - -static inline void -zix_sem_destroy(ZixSem* sem) -{ - sem_destroy(&sem->sem); -} - -static inline void -zix_sem_post(ZixSem* sem) -{ - sem_post(&sem->sem); -} - -static inline ZixStatus -zix_sem_wait(ZixSem* sem) -{ - while (sem_wait(&sem->sem)) { - if (errno != EINTR) { - return ZIX_STATUS_ERROR; - } - /* Otherwise, interrupted, so try again. */ - } - - return ZIX_STATUS_SUCCESS; -} - -static inline bool -zix_sem_try_wait(ZixSem* sem) -{ - return (sem_trywait(&sem->sem) == 0); -} - -#endif - -/** - @endcond - @} - @} -*/ - -#ifdef __cplusplus -} /* extern "C" */ -#endif - -#endif /* ZIX_SEM_H */ diff --git a/src/zix/thread.h b/src/zix/thread.h deleted file mode 100644 index 5802c99..0000000 --- a/src/zix/thread.h +++ /dev/null @@ -1,133 +0,0 @@ -/* - Copyright 2012-2014 David Robillard <http://drobilla.net> - - Permission to use, copy, modify, and/or distribute this software for any - purpose with or without fee is hereby granted, provided that the above - copyright notice and this permission notice appear in all copies. - - THIS SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES - WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF - MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR - ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES - WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN - ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF - OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. -*/ - -#ifndef ZIX_THREAD_H -#define ZIX_THREAD_H - -#include "zix/common.h" - -#ifdef _WIN32 -# include <windows.h> -#else -# include <errno.h> -# include <pthread.h> -#endif - -#ifdef __cplusplus -extern "C" { -#else -# include <stdbool.h> -#endif - -/** - @addtogroup zix - @{ - @name Thread - @{ -*/ - -#ifdef _WIN32 -typedef HANDLE ZixThread; -#else -typedef pthread_t ZixThread; -#endif - -/** - Initialize `thread` to a new thread. - - The thread will immediately be launched, calling `function` with `arg` - as the only parameter. -*/ -static inline ZixStatus -zix_thread_create(ZixThread* thread, - size_t stack_size, - void* (*function)(void*), - void* arg); - -/** - Join `thread` (block until `thread` exits). -*/ -static inline ZixStatus -zix_thread_join(ZixThread thread, void** retval); - -#ifdef _WIN32 - -static inline ZixStatus -zix_thread_create(ZixThread* thread, - size_t stack_size, - void* (*function)(void*), - void* arg) -{ - *thread = CreateThread(NULL, stack_size, - (LPTHREAD_START_ROUTINE)function, arg, - 0, NULL); - return *thread ? ZIX_STATUS_SUCCESS : ZIX_STATUS_ERROR; -} - -static inline ZixStatus -zix_thread_join(ZixThread thread, void** retval) -{ - return WaitForSingleObject(thread, INFINITE) - ? ZIX_STATUS_SUCCESS : ZIX_STATUS_ERROR; -} - -#else /* !defined(_WIN32) */ - -static inline ZixStatus -zix_thread_create(ZixThread* thread, - size_t stack_size, - void* (*function)(void*), - void* arg) -{ - pthread_attr_t attr; - pthread_attr_init(&attr); - pthread_attr_setstacksize(&attr, stack_size); - - const int ret = pthread_create(thread, NULL, function, arg); - pthread_attr_destroy(&attr); - - if (ret == EAGAIN) { - return ZIX_STATUS_NO_MEM; - } else if (ret == EINVAL) { - return ZIX_STATUS_BAD_ARG; - } else if (ret == EPERM) { - return ZIX_STATUS_BAD_PERMS; - } else if (ret) { - return ZIX_STATUS_ERROR; - } - - return ZIX_STATUS_SUCCESS; -} - -static inline ZixStatus -zix_thread_join(ZixThread thread, void** retval) -{ - return pthread_join(thread, retval) - ? ZIX_STATUS_ERROR : ZIX_STATUS_SUCCESS; -} - -#endif - -/** - @} - @} -*/ - -#ifdef __cplusplus -} /* extern "C" */ -#endif - -#endif /* ZIX_THREAD_H */ diff --git a/subprojects/lilv.wrap b/subprojects/lilv.wrap new file mode 100644 index 0000000..61b77c5 --- /dev/null +++ b/subprojects/lilv.wrap @@ -0,0 +1,14 @@ +# Copyright 2022-2025 David Robillard <d@drobilla.net> +# SPDX-License-Identifier: 0BSD OR ISC + +[wrap-file] +directory = lilv-0.24.26 +source_url = https://download.drobilla.net/lilv-0.24.26.tar.xz +source_filename = lilv-0.24.26.tar.xz +source_hash = 22feed30bc0f952384a25c2f6f4b04e6d43836408798ed65a8a934c055d5d8ac + +# [wrap-git] +# url = https://gitlab.com/lv2/lilv.git +# push-url = ssh://git@gitlab.com:lv2/lilv.git +# revision = v0.24.26 +# depth = 1 diff --git a/subprojects/lv2.wrap b/subprojects/lv2.wrap new file mode 100644 index 0000000..ce82cf8 --- /dev/null +++ b/subprojects/lv2.wrap @@ -0,0 +1,8 @@ +# Copyright 2022 David Robillard <d@drobilla.net> +# SPDX-License-Identifier: 0BSD OR ISC + +[wrap-git] +url = https://gitlab.com/lv2/lv2.git +push-url = ssh://git@gitlab.com:lv2/lv2.git +revision = main +depth = 1 diff --git a/subprojects/serd.wrap b/subprojects/serd.wrap new file mode 100644 index 0000000..3b84a4c --- /dev/null +++ b/subprojects/serd.wrap @@ -0,0 +1,14 @@ +# Copyright 2022-2025 David Robillard <d@drobilla.net> +# SPDX-License-Identifier: 0BSD OR ISC + +# [wrap-file] +# directory = serd-0.32.4 +# source_url = https://download.drobilla.net/serd-0.32.4.tar.xz +# source_filename = serd-0.32.4.tar.xz +# source_hash = cbefb569e8db686be8c69cb3866a9538c7cb055e8f24217dd6a4471effa7d349 + +[wrap-git] +url = https://gitlab.com/drobilla/serd.git +push-url = ssh://git@gitlab.com:drobilla/serd.git +revision = main +depth = 1 diff --git a/subprojects/sord.wrap b/subprojects/sord.wrap new file mode 100644 index 0000000..89b2933 --- /dev/null +++ b/subprojects/sord.wrap @@ -0,0 +1,14 @@ +# Copyright 2022-2025 David Robillard <d@drobilla.net> +# SPDX-License-Identifier: 0BSD OR ISC + +[wrap-file] +directory = sord-0.16.18 +source_url = https://download.drobilla.net/sord-0.16.18.tar.xz +source_filename = sord-0.16.18.tar.xz +source_hash = 4f398b635894491a4774b1498959805a08e11734c324f13d572dea695b13d3b3 + +# [wrap-git] +# url = https://gitlab.com/drobilla/sord.git +# push-url = ssh://git@gitlab.com:drobilla/sord.git +# revision = v0.16.18 +# depth = 1 diff --git a/subprojects/sratom.wrap b/subprojects/sratom.wrap new file mode 100644 index 0000000..1524426 --- /dev/null +++ b/subprojects/sratom.wrap @@ -0,0 +1,14 @@ +# Copyright 2022-2025 David Robillard <d@drobilla.net> +# SPDX-License-Identifier: 0BSD OR ISC + +[wrap-file] +directory = sratom-0.6.18 +source_url = https://download.drobilla.net/sratom-0.6.18.tar.xz +source_filename = sratom-0.6.18.tar.xz +source_hash = 4c6a6d9e0b4d6c01cc06a8849910feceb92e666cb38779c614dd2404a9931e92 + +# [wrap-git] +# url = https://gitlab.com/lv2/sratom.git +# push-url = ssh://git@gitlab.com:lv2/sratom.git +# revision = v0.6.18 +# depth = 1 diff --git a/subprojects/suil.wrap b/subprojects/suil.wrap new file mode 100644 index 0000000..16e28d4 --- /dev/null +++ b/subprojects/suil.wrap @@ -0,0 +1,14 @@ +# Copyright 2022-2025 David Robillard <d@drobilla.net> +# SPDX-License-Identifier: 0BSD OR ISC + +[wrap-file] +directory = suil-0.10.22 +source_url = https://download.drobilla.net/suil-0.10.22.tar.xz +source_filename = suil-0.10.22.tar.xz +source_hash = d720969e0f44a99d5fba35c733a43ed63a16b0dab867970777efca4b25387eb7 + +# [wrap-git] +# url = https://gitlab.com/lv2/suil.git +# push-url = ssh://git@gitlab.com:lv2/suil.git +# revision = v0.10.22 +# depth = 1 diff --git a/subprojects/zix.wrap b/subprojects/zix.wrap new file mode 100644 index 0000000..531d29c --- /dev/null +++ b/subprojects/zix.wrap @@ -0,0 +1,14 @@ +# Copyright 2022-2025 David Robillard <d@drobilla.net> +# SPDX-License-Identifier: 0BSD OR ISC + +[wrap-file] +directory = zix-0.6.2 +source_url = https://download.drobilla.net/zix-0.6.2.tar.xz +source_filename = zix-0.6.2.tar.xz +source_hash = 4bc771abf4fcf399ea969a1da6b375f0117784f8fd0e2db356a859f635f616a7 + +# [wrap-git] +# url = https://gitlab.com/drobilla/zix.git +# push-url = ssh://git@gitlab.com:drobilla/zix.git +# revision = v0.6.2 +# depth = 1 diff --git a/test/meson.build b/test/meson.build new file mode 100644 index 0000000..5e89d48 --- /dev/null +++ b/test/meson.build @@ -0,0 +1,104 @@ +# Copyright 2019-2024 David Robillard <d@drobilla.net> +# SPDX-License-Identifier: 0BSD OR ISC + +######## +# Lint # +######## + +all_sources = ( + common_sources + files( + '../src/attributes.h', + '../src/backend.h', + '../src/control.h', + '../src/frontend.h', + '../src/jack.c', + '../src/jalv.h', + '../src/jalv_config.h', + '../src/jalv_console.c', + '../src/jalv_gtk.c', + '../src/jalv_qt.cpp', + '../src/jalv_qt.hpp', + '../src/log.h', + '../src/lv2_evbuf.h', + '../src/nodes.h', + '../src/options.h', + '../src/port.h', + '../src/portaudio.c', + '../src/state.h', + '../src/symap.h', + '../src/types.h', + '../src/urids.h', + '../src/worker.h', + ) +) + +if get_option('lint') + if not meson.is_subproject() + # Check release metadata + autoship = find_program('autoship', required: get_option('tests')) + if autoship.found() + test( + 'autoship', + autoship, + args: ['test', jalv_src_root], + suite: 'data', + ) + endif + + # Check code with cppcheck + cppcheck = find_program('cppcheck', required: false) + if cppcheck.found() + compdb_path = join_paths(jalv_build_root, 'compile_commands.json') + suppress_path = join_paths(jalv_src_root, '.suppress.cppcheck') + test( + 'cppcheck', + cppcheck, + args: [ + '--enable=warning,style,performance,portability', + '--error-exitcode=1', + '--project=' + compdb_path, + '--suppressions-list=' + suppress_path, + '-q', + ['-i', jalv_build_root], + ], + suite: 'code', + ) + endif + endif + + # Check licensing metadata + reuse = find_program('reuse', required: false) + if reuse.found() + test( + 'REUSE', + reuse, + args: ['--root', jalv_src_root, 'lint'], + suite: 'data', + ) + endif + + # Check code formatting + clang_format = find_program('clang-format', required: false) + if clang_format.found() + test( + 'format', + clang_format, + args: ['--Werror', '--dry-run'] + all_sources, + suite: 'code', + ) + endif +endif + +############## +# Unit Tests # +############## + +test( + 'test_symap', + executable( + 'test_symap', + files('../src/symap.c'), + c_args: c_suppressions + ['-DSYMAP_STANDALONE'], + dependencies: [zix_dep], + ), +) @@ -1,16 +0,0 @@ -#!/usr/bin/env python - -# Minimal waf script for projects that include waflib directly - -from waflib import Context, Scripting - -import inspect -import os - -def main(): - script_path = os.path.abspath(inspect.getfile(inspect.getmodule(main))) - project_path = os.path.dirname(script_path) - Scripting.waf_entry_point(os.getcwd(), Context.WAFVERSION, project_path) - -if __name__ == '__main__': - main() diff --git a/waflib b/waflib deleted file mode 160000 -Subproject 0bde0c2e022c479b8c7e3933eca0cbc01282562 diff --git a/wscript b/wscript deleted file mode 100644 index af363ca..0000000 --- a/wscript +++ /dev/null @@ -1,258 +0,0 @@ -#!/usr/bin/env python - -import os -import subprocess - -from waflib import Options -from waflib.extras import autowaf as autowaf - -# Version of this package (even if built as a child) -JALV_VERSION = '1.6.4' - -# Mandatory waf variables -APPNAME = 'jalv' # Package name for waf dist -VERSION = JALV_VERSION # Package version for waf dist -top = '.' # Source directory -out = 'build' # Build directory - -# Release variables -uri = 'http://drobilla.net/sw/jalv' -dist_pattern = 'http://download.drobilla.net/jalv-%d.%d.%d.tar.bz2' -post_tags = ['Hacking', 'LAD', 'LV2', 'Jalv'] - -def options(ctx): - ctx.load('compiler_c') - ctx.load('compiler_cxx') - ctx.add_flags( - ctx.configuration_options(), - {'portaudio': 'use PortAudio backend, not JACK', - 'no-jack-session': 'do not build JACK session support', - 'no-gui': 'do not build any GUIs', - 'no-gtk': 'do not build Gtk GUI', - 'no-gtkmm': 'do not build Gtkmm GUI', - 'no-gtk2': 'do not build Gtk2 GUI', - 'no-gtk3': 'do not build Gtk3 GUI', - 'no-qt': 'do not build Qt GUI', - 'no-qt4': 'do not build Qt4 GUI', - 'no-qt5': 'do not build Qt5 GUI'}) - -def configure(conf): - conf.load('compiler_c', cache=True) - conf.load('compiler_cxx', cache=True) - conf.load('autowaf', cache=True) - autowaf.set_c_lang(conf, 'c99') - - conf.check_pkg('lv2 >= 1.16.0', uselib_store='LV2') - conf.check_pkg('lilv-0 >= 0.24.0', uselib_store='LILV') - conf.check_pkg('serd-0 >= 0.24.0', uselib_store='SERD') - conf.check_pkg('sord-0 >= 0.14.0', uselib_store='SORD') - conf.check_pkg('sratom-0 >= 0.6.0', uselib_store='SRATOM') - if Options.options.portaudio: - conf.check_pkg('portaudio-2.0 >= 2.0.0', - uselib_store='PORTAUDIO', mandatory=False) - else: - conf.check_pkg('jack >= 0.120.0', uselib_store='JACK') - - if not Options.options.no_gui and not Options.options.no_gtk: - if not Options.options.no_gtk2: - conf.check_pkg('gtk+-2.0 >= 2.18.0', uselib_store='GTK2', - mandatory=False) - if not Options.options.no_gtkmm: - conf.check_pkg('gtkmm-2.4 >= 2.20.0', uselib_store='GTKMM2', - mandatory=False) - if not Options.options.no_gtk3: - conf.check_pkg('gtk+-3.0 >= 3.0.0', uselib_store='GTK3', - mandatory=False) - - if not Options.options.no_gui and not Options.options.no_qt: - if not Options.options.no_qt4: - conf.check_pkg('QtGui >= 4.0.0', uselib_store='QT4', - mandatory=False) - if conf.env.HAVE_QT4: - if not conf.find_program('moc-qt4', var='MOC4', mandatory=False): - conf.find_program('moc', var='MOC4') - - if not Options.options.no_qt5: - conf.check_pkg('Qt5Widgets >= 5.1.0', uselib_store='QT5', - mandatory=False) - if conf.env.HAVE_QT5: - if not conf.find_program('moc-qt5', var='MOC5', mandatory=False): - conf.find_program('moc', var='MOC5') - - have_gui = (conf.env.HAVE_GTK2 or conf.env.HAVE_GTKMM2 or conf.env.HAVE_GTK3 or - conf.env.HAVE_QT4 or conf.env.HAVE_QT5) - if have_gui: - conf.check_pkg('suil-0 >= 0.10.0', uselib_store='SUIL') - - if conf.env.HAVE_JACK: - conf.check_function( - 'c', 'jack_port_type_get_buffer_size', - header_name = 'jack/jack.h', - define_name = 'HAVE_JACK_PORT_TYPE_GET_BUFFER_SIZE', - uselib = 'JACK', - mandatory = False) - - conf.check_function('c', 'jack_set_property', - header_name = 'jack/metadata.h', - define_name = 'HAVE_JACK_METADATA', - uselib = 'JACK', - mandatory = False) - - defines = ['_POSIX_C_SOURCE=200809L'] - - conf.check_function('c', 'isatty', - header_name = 'unistd.h', - defines = defines, - define_name = 'HAVE_ISATTY', - mandatory = False) - - conf.check_function('c', 'fileno', - header_name = 'stdio.h', - defines = defines, - define_name = 'HAVE_FILENO', - mandatory = False) - - conf.check_function('c', 'mlock', - header_name = 'sys/mman.h', - defines = defines, - define_name = 'HAVE_MLOCK', - mandatory = False) - - conf.check_function('c', 'sigaction', - header_name = 'signal.h', - defines = defines, - define_name = 'HAVE_SIGACTION', - mandatory = False) - - if conf.is_defined('HAVE_ISATTY') and conf.is_defined('HAVE_FILENO'): - conf.env.append_unique('CFLAGS', ['-D_POSIX_C_SOURCE=200809L']) - - if not Options.options.no_jack_session: - conf.define('JALV_JACK_SESSION', 1) - - conf.write_config_header('jalv_config.h', remove=False) - - autowaf.display_summary( - conf, - {'Backend': 'Jack' if conf.env.HAVE_JACK else 'PortAudio', - 'Jack metadata support': conf.is_defined('HAVE_JACK_METADATA'), - 'Gtk 2.0 support': bool(conf.env.HAVE_GTK2), - 'Gtk 3.0 support': bool(conf.env.HAVE_GTK3), - 'Gtkmm 2.0 support': bool(conf.env.HAVE_GTKMM2), - 'Qt 4.0 support': bool(conf.env.HAVE_QT4), - 'Qt 5.0 support': bool(conf.env.HAVE_QT5), - 'Color output': bool(conf.env.JALV_WITH_COLOR)}) - -def build(bld): - libs = 'LILV SUIL JACK SERD SORD SRATOM LV2 PORTAUDIO' - source = ''' - src/control.c - src/jalv.c - src/log.c - src/lv2_evbuf.c - src/state.c - src/symap.c - src/worker.c - src/zix/ring.c - ''' - - if bld.env.HAVE_JACK: - source += 'src/jack.c' - - # Non-GUI internal JACK client library - obj = bld(features = 'c cshlib', - source = source + ' src/jalv_console.c', - target = 'jalv', - includes = ['.', 'src'], - lib = ['pthread'], - uselib = libs, - install_path = '${LIBDIR}/jack') - obj.env.cshlib_PATTERN = '%s.so' - elif bld.env.HAVE_PORTAUDIO: - source += 'src/portaudio.c' - - # Non-GUI version - obj = bld(features = 'c cprogram', - source = source + ' src/jalv_console.c', - target = 'jalv', - includes = ['.', 'src'], - lib = ['pthread'], - uselib = libs, - install_path = '${BINDIR}') - - # Gtk2 version - if bld.env.HAVE_GTK2: - obj = bld(features = 'c cprogram', - source = source + ' src/jalv_gtk.c', - target = 'jalv.gtk', - includes = ['.', 'src'], - lib = ['pthread', 'm'], - uselib = libs + ' GTK2', - install_path = '${BINDIR}') - - # Gtk3 version - if bld.env.HAVE_GTK3: - obj = bld(features = 'c cprogram', - source = source + ' src/jalv_gtk.c', - target = 'jalv.gtk3', - includes = ['.', 'src'], - lib = ['pthread', 'm'], - uselib = libs + ' GTK3', - install_path = '${BINDIR}') - - # Gtkmm version - if bld.env.HAVE_GTKMM2: - obj = bld(features = 'c cxx cxxprogram', - source = source + ' src/jalv_gtkmm2.cpp', - target = 'jalv.gtkmm', - includes = ['.', 'src'], - lib = ['pthread'], - uselib = libs + ' GTKMM2', - install_path = '${BINDIR}') - - # Qt4 version - if bld.env.HAVE_QT4: - obj = bld(rule = '${MOC4} ${SRC} > ${TGT}', - source = 'src/jalv_qt.cpp', - target = 'jalv_qt4_meta.hpp') - obj = bld(features = 'c cxx cxxprogram', - source = source + ' src/jalv_qt.cpp', - target = 'jalv.qt4', - includes = ['.', 'src'], - lib = ['pthread'], - uselib = libs + ' QT4', - install_path = '${BINDIR}') - - # Qt5 version - if bld.env.HAVE_QT5: - obj = bld(rule = '${MOC5} ${SRC} > ${TGT}', - source = 'src/jalv_qt.cpp', - target = 'jalv_qt5_meta.hpp') - obj = bld(features = 'c cxx cxxprogram', - source = source + ' src/jalv_qt.cpp', - target = 'jalv.qt5', - includes = ['.', 'src'], - lib = ['pthread'], - uselib = libs + ' QT5', - install_path = '${BINDIR}', - cxxflags = ['-fPIC']) - - # Man pages - bld.install_files('${MANDIR}/man1', bld.path.ant_glob('doc/*.1')) - -def lint(ctx): - "checks code for style issues" - import subprocess - cmd = ("clang-tidy -p=. -header-filter=src/ -checks=\"*," + - "-clang-analyzer-alpha.*," + - "-google-readability-todo," + - "-llvm-header-guard," + - "-llvm-include-order," + - "-misc-unused-parameters," + - "-readability-else-after-return\" " + - "$(find .. -name '*.c')") - subprocess.call(cmd, cwd='build', shell=True) - -def dist(ctx): - ctx.base_path = ctx.path - ctx.excl = ctx.get_excl() + ' .gitmodules' |