From ea783414b68512c15b9523cde2bfb4f93e433d56 Mon Sep 17 00:00:00 2001 From: David Robillard Date: Fri, 27 May 2022 13:20:05 -0400 Subject: Format all code with clang-format --- .clang-format | 26 + src/control.c | 255 +++--- src/jack.c | 863 +++++++++++---------- src/jalv.c | 2136 ++++++++++++++++++++++++++------------------------- src/jalv_console.c | 378 +++++---- src/jalv_gtk.c | 1944 ++++++++++++++++++++++++---------------------- src/jalv_gtkmm2.cpp | 74 +- src/jalv_internal.h | 509 ++++++------ src/jalv_qt.cpp | 947 +++++++++++------------ src/log.c | 65 +- src/lv2_evbuf.c | 157 ++-- src/lv2_evbuf.h | 6 +- src/portaudio.c | 322 ++++---- src/state.c | 329 ++++---- src/symap.c | 284 ++++--- src/worker.c | 158 ++-- 16 files changed, 4316 insertions(+), 4137 deletions(-) create mode 100644 .clang-format diff --git a/.clang-format b/.clang-format new file mode 100644 index 0000000..f935f70 --- /dev/null +++ b/.clang-format @@ -0,0 +1,26 @@ +--- +AlignConsecutiveAssignments: true +AlignConsecutiveDeclarations: true +AlignEscapedNewlinesLeft: true +BasedOnStyle: Mozilla +BraceWrapping: + AfterNamespace: false + AfterClass: true + AfterEnum: false + AfterExternBlock: false + AfterFunction: true + AfterStruct: false + SplitEmptyFunction: false + SplitEmptyRecord: false +BreakBeforeBraces: Custom +Cpp11BracedListStyle: true +ForEachMacros: + - LILV_FOREACH + - foreach +IndentCaseLabels: false +IndentPPDirectives: AfterHash +KeepEmptyLinesAtTheStartOfBlocks: false +SpacesInContainerLiterals: false +StatementMacros: + - _Pragma +... diff --git a/src/control.c b/src/control.c index 8b619a9..ca3a73f 100644 --- a/src/control.c +++ b/src/control.c @@ -30,150 +30,169 @@ int scale_point_cmp(const ScalePoint* a, const ScalePoint* b) { - if (a->value < b->value) { - return -1; - } + if (a->value < b->value) { + return -1; + } - if (a->value == b->value) { - return 0; - } + if (a->value == b->value) { + return 0; + } - return 1; + return 1; } ControlID* new_port_control(Jalv* jalv, uint32_t index) { - 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; + 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; } static bool has_range(Jalv* jalv, const LilvNode* subject, const char* 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(jalv->world, range_uri); + const bool result = + lilv_world_ask(jalv->world, subject, jalv->nodes.rdfs_range, range); + + lilv_node_free(range); + return result; } ControlID* new_property_control(Jalv* jalv, const LilvNode* property) { - 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; + 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->property = jalv->map.map(jalv, lilv_node_as_uri(property)); + + id->label = + lilv_world_get(jalv->world, property, jalv->nodes.rdfs_label, NULL); + 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; } 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; + controls->controls = (ControlID**)realloc( + controls->controls, (controls->n_controls + 1) * sizeof(ControlID*)); + + 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]; - } - } + for (size_t i = 0; i < controls->n_controls; ++i) { + if (controls->controls[i]->property == property) { + return controls->controls[i]; + } + } - return NULL; + return NULL; } diff --git a/src/jack.c b/src/jack.c index 96012f6..e232cde 100644 --- a/src/jack.c +++ b/src/jack.c @@ -31,7 +31,7 @@ #include #ifdef HAVE_JACK_METADATA -# include +# include #endif #include @@ -42,509 +42,526 @@ #include struct JalvBackend { - jack_client_t* client; ///< Jack client - bool is_internal_client; ///< Running inside jackd + jack_client_t* client; ///< Jack client + bool is_internal_client; ///< Running inside jackd }; /** Internal Jack client initialization entry point */ -int jack_initialize(jack_client_t* client, const char* load_init); +int +jack_initialize(jack_client_t* client, const char* load_init); /** Internal Jack client finalization entry point */ -void jack_finish(void* arg); +void +jack_finish(void* arg); /** Jack buffer size callback. */ static int jack_buffer_size_cb(jack_nframes_t nframes, void* data) { - Jalv* const jalv = (Jalv*)data; - jalv->block_length = nframes; - jalv->buf_size_set = true; + 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); + jalv->midi_buf_size = jack_port_type_get_buffer_size(jalv->backend->client, + JACK_DEFAULT_MIDI_TYPE); #endif - jalv_allocate_port_buffers(jalv); - return 0; + jalv_allocate_port_buffers(jalv); + return 0; } /** Jack shutdown callback. */ static void jack_shutdown_cb(void* data) { - Jalv* const jalv = (Jalv*)data; - jalv_close_ui(jalv); - zix_sem_post(&jalv->done); + Jalv* const jalv = (Jalv*)data; + jalv_close_ui(jalv); + zix_sem_post(&jalv->done); } /** Jack process callback. */ static REALTIME int jack_process_cb(jack_nframes_t nframes, void* data) { - 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)); + 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)); + } 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_CONST(&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 = 0; - uint32_t subframes = 0; - uint32_t type = 0; - uint32_t size = 0; - uint8_t* body = NULL; - 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; + } 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_CONST(&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 = 0; + uint32_t subframes = 0; + uint32_t type = 0; + uint32_t size = 0; + uint8_t* body = NULL; + 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; } /** Calculate latency assuming all ports depend on each other. */ static void jack_latency_cb(jack_latency_callback_mode_t mode, void* data) { - 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); - } - } + 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); + } + } } static jack_client_t* jack_create_client(Jalv* jalv) { - 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 */ - if (!client) { - client = jack_client_open( - jack_name, - (jalv->opts.name_exact ? JackUseExactName : JackNullOption), - NULL); - } - - free(jack_name); - - return client; + 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 */ + if (!client) { + client = jack_client_open( + jack_name, + (jalv->opts.name_exact ? JackUseExactName : JackNullOption), + NULL); + } + + free(jack_name); + + return client; } JalvBackend* jalv_backend_init(Jalv* jalv) { - jack_client_t* const client = - jalv->backend ? jalv->backend->client : jack_create_client(jalv); + jack_client_t* const client = + jalv->backend ? jalv->backend->client : jack_create_client(jalv); - if (!client) { - return NULL; - } + if (!client) { + return NULL; + } - printf("JACK Name: %s\n", jack_get_client_name(client)); + 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; + /* 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); + jalv->midi_buf_size = + jack_port_type_get_buffer_size(client, JACK_DEFAULT_MIDI_TYPE); #endif - /* 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); - - 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*)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); + + 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; } void jalv_backend_close(Jalv* jalv) { - if (jalv->backend) { - if (!jalv->backend->is_internal_client) { - jack_client_close(jalv->backend->client); - } - - free(jalv->backend); - jalv->backend = NULL; - } + if (jalv->backend) { + if (!jalv->backend->is_internal_client) { + jack_client_close(jalv->backend->client); + } + + free(jalv->backend); + jalv->backend = NULL; + } } void jalv_backend_activate(Jalv* jalv) { - jack_activate(jalv->backend->client); + jack_activate(jalv->backend->client); } void jalv_backend_deactivate(Jalv* jalv) { - if (jalv->backend && !jalv->backend->is_internal_client) { - jack_deactivate(jalv->backend->client); - } + if (jalv->backend && !jalv->backend->is_internal_client) { + jack_deactivate(jalv->backend->client); + } } void jalv_backend_activate_port(Jalv* jalv, 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; + 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; + 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; #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; - } + 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), "%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 - 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); - } + 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 + 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); + } #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); - snprintf(cmd, cmd_len + 1, "jalv %s", 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; + 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); + snprintf(cmd, cmd_len + 1, "jalv %s", 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* const jalv = (Jalv*)arg; - if (jalv) { - if (jalv_close(jalv)) { - fprintf(stderr, "Failed to close Jalv\n"); - } - - free(jalv); - } + Jalv* const jalv = (Jalv*)arg; + if (jalv) { + if (jalv_close(jalv)) { + fprintf(stderr, "Failed to close Jalv\n"); + } + + free(jalv); + } } diff --git a/src/jalv.c b/src/jalv.c index 9de7f31..f181373 100644 --- a/src/jalv.c +++ b/src/jalv.c @@ -51,12 +51,12 @@ #include "zix/sem.h" #ifdef HAVE_SUIL -#include "suil/suil.h" +# include "suil/suil.h" #endif #ifdef _WIN32 -# include /* for _mktemp */ -# define snprintf _snprintf +# include /* for _mktemp */ +# define snprintf _snprintf #endif #include @@ -73,15 +73,15 @@ #define NS_XSD "http://www.w3.org/2001/XMLSchema#" #ifndef MIN -# define MIN(a, b) (((a) < (b)) ? (a) : (b)) +# define MIN(a, b) (((a) < (b)) ? (a) : (b)) #endif #ifndef MAX -# define MAX(a, b) (((a) > (b)) ? (a) : (b)) +# define MAX(a, b) (((a) > (b)) ? (a) : (b)) #endif #ifndef ARRAY_SIZE -# define ARRAY_SIZE(arr) (sizeof(arr) / sizeof(arr[0])) +# define ARRAY_SIZE(arr) (sizeof(arr) / sizeof(arr[0])) #endif /* Size factor for UI ring buffers. The ring size is a few times the size of @@ -91,62 +91,60 @@ */ #define N_BUFFER_CYCLES 16 -static ZixSem* exit_sem = NULL; /**< Exit semaphore used by signal handler*/ +static ZixSem* exit_sem = NULL; /**< Exit semaphore used by signal handler*/ static LV2_URID -map_uri(LV2_URID_Map_Handle handle, - const char* uri) +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; + 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) +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; + 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 */ 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. */ static bool feature_is_supported(Jalv* jalv, const char* uri) { - 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; + 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; } /** Abort and exit on error */ static void die(const char* msg) { - fprintf(stderr, "%s\n", msg); - exit(EXIT_FAILURE); + fprintf(stderr, "%s\n", msg); + exit(EXIT_FAILURE); } /** @@ -155,68 +153,68 @@ die(const char* msg) (e.g. buffers) is done later in activate_port(). */ static void -create_port(Jalv* jalv, - uint32_t port_index, - float default_value) +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; + 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; + } 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); + } 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); } /** @@ -225,31 +223,31 @@ create_port(Jalv* jalv, void jalv_create_ports(Jalv* jalv) { - 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) { - const uint32_t index = lilv_port_get_index(jalv->plugin, control_input); - if (jalv->ports[index].type == TYPE_EVENT) { - jalv->control_in = index; - } else { - fprintf(stderr, - "warning: Non-event port %u has lv2:control designation, " - "ignored\n", - index); - } - } - - free(default_values); + 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) { + const uint32_t index = lilv_port_get_index(jalv->plugin, control_input); + if (jalv->ports[index].type == TYPE_EVENT) { + jalv->control_in = index; + } else { + fprintf(stderr, + "warning: Non-event port %u has lv2:control designation, " + "ignored\n", + index); + } + } + + free(default_values); } /** @@ -258,26 +256,26 @@ jalv_create_ports(Jalv* jalv) void jalv_allocate_port_buffers(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; - } - } + 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; + } + } } /** @@ -289,85 +287,84 @@ jalv_allocate_port_buffers(Jalv* jalv) struct Port* 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) { + struct Port* 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* 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 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, 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); } void @@ -376,220 +373,220 @@ jalv_set_control(const ControlID* control, LV2_URID type, const void* body) { - 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* 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); + } } void jalv_ui_instantiate(Jalv* jalv, const char* native_ui_type, void* parent) { #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, - &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); + 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, + &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); #endif } bool jalv_ui_is_resizable(Jalv* jalv) { - if (!jalv->ui) { - return false; - } + 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); + 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); + LilvNodes* fs_matches = lilv_world_find_nodes(jalv->world, s, p, fs); + LilvNodes* nrs_matches = lilv_world_find_nodes(jalv->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); + 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 !fs_matches && !nrs_matches; } void -jalv_ui_write(void* const jalv_handle, - uint32_t port_index, - uint32_t buffer_size, - uint32_t protocol, - const void* buffer) +jalv_ui_write(void* const jalv_handle, + uint32_t port_index, + uint32_t buffer_size, + uint32_t protocol, + const void* buffer) { - Jalv* const jalv = (Jalv*)jalv_handle; - - if (protocol != 0 && protocol != jalv->urids.atom_eventTransfer) { - fprintf(stderr, "UI write with unsupported protocol %u (%s)\n", - protocol, unmap_uri(jalv, protocol)); - return; - } - - if (port_index >= jalv->num_ports) { - fprintf(stderr, "UI write to out of range port index %u\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)); + Jalv* const jalv = (Jalv*)jalv_handle; + + if (protocol != 0 && protocol != jalv->urids.atom_eventTransfer) { + fprintf(stderr, + "UI write with unsupported protocol %u (%s)\n", + protocol, + unmap_uri(jalv, protocol)); + return; + } + + if (port_index >= jalv->num_ports) { + fprintf(stderr, "UI write to out of range port index %u\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)); } void jalv_apply_ui_events(Jalv* jalv, uint32_t nframes) { - 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 %u\n", - ev.protocol); - } - } + 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 %u\n", ev.protocol); + } + } } uint32_t jalv_ui_port_index(void* const controller, const char* symbol) { - Jalv* const jalv = (Jalv*)controller; - struct Port* port = jalv_port_by_symbol(jalv, symbol); + Jalv* const jalv = (Jalv*)controller; + struct Port* port = jalv_port_by_symbol(jalv, symbol); - return port ? port->index : LV2UI_INVALID_PORT_INDEX; + return port ? port->index : LV2UI_INVALID_PORT_INDEX; } void jalv_init_ui(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); - } + // 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); + } } bool @@ -599,757 +596,794 @@ jalv_send_to_ui(Jalv* jalv, uint32_t size, const void* body) { - /* 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; - } - - fprintf(stderr, "Plugin => UI buffer overflow!\n"); - return false; + /* 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; + } + + fprintf(stderr, "Plugin => UI buffer overflow!\n"); + return false; } bool jalv_run(Jalv* jalv, uint32_t nframes) { - /* 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; + /* 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; } int jalv_update(Jalv* 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; + /* 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; } 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; + 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; } static void signal_handler(int ZIX_UNUSED(sig)) { - zix_sem_post(exit_sem); + zix_sem_post(exit_sem); } static void init_feature(LV2_Feature* const dest, const char* const URI, void* data) { - dest->URI = URI; - dest->data = data; + dest->URI = URI; + dest->data = data; } static void setup_signals(Jalv* const jalv) { - exit_sem = &jalv->done; + 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); + 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); + /* May not work in combination with fgets in the console interface */ + signal(SIGINT, signal_handler); + signal(SIGTERM, signal_handler); #endif } static const LilvUI* jalv_select_custom_ui(const Jalv* const jalv) { - const char* const native_ui_type_uri = jalv_native_ui_type(); + const char* const native_ui_type_uri = jalv_native_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); + 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; - } + lilv_node_free(uri); + return ui; + } #ifdef HAVE_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); - } + 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 - 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); + 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); + 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); + 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); + lilv_world_unload_resource(jalv->world, ui_node); - if (supported) { - return ui; - } - } - } + if (supported) { + return ui; + } + } + } - return NULL; + return NULL; } 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; + 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); + suil_init(argc, argv, SUIL_ARG_NONE); #endif - if (jalv_init(argc, argv, &jalv->opts)) { - jalv_close(jalv); - return -1; - } - - 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_scaleFactor = symap_map(jalv->symap, LV2_UI__scaleFactor); - jalv->urids.ui_updateRate = symap_map(jalv->symap, LV2_UI__updateRate); + if (jalv_init(argc, argv, &jalv->opts)) { + jalv_close(jalv); + return -1; + } + + 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_scaleFactor = symap_map(jalv->symap, LV2_UI__scaleFactor); + jalv->urids.ui_updateRate = symap_map(jalv->symap, LV2_UI__updateRate); #ifdef _WIN32 - jalv->temp_dir = jalv_strdup("jalvXXXXXX"); - _mktemp(jalv->temp_dir); + 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); + char* templ = jalv_strdup("/tmp/jalv-XXXXXX"); + jalv->temp_dir = jalv_strjoin(mkdtemp(templ), "/"); + free(templ); #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); - - jalv->features.request_value.handle = jalv; - init_feature(&jalv->features.request_value_feature, - LV2_UI__requestValue, &jalv->features.request_value); - - 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_extensionData = lilv_new_uri(world, LV2_CORE__extensionData); - 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.ui_showInterface = lilv_new_uri(world, LV2_UI__showInterface); - 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 */ - jalv->uis = lilv_plugin_get_uis(jalv->plugin); - if (!jalv->opts.generic_ui) { - if ((jalv->ui = jalv_select_custom_ui(jalv))) { - const char* host_type_uri = jalv_native_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); - } - } - } - - /* 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); - } - - if (jalv->opts.scale_factor == 0.0) { - /* Calculate the monitor's scale factor. */ - jalv->ui_scale_factor = jalv_ui_scale_factor(jalv); - } else { - /* Use user-specified UI scale factor. */ - jalv->ui_scale_factor = jalv->opts.scale_factor; - } - - /* 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: %u bytes\n", jalv->opts.buffer_size); - fprintf(stderr, "Update rate: %.01f Hz\n", jalv->ui_update_hz); - fprintf(stderr, "Scale factor: %.01f\n", jalv->ui_scale_factor); - - /* 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, jalv->urids.ui_scaleFactor, - sizeof(float), jalv->urids.atom_Float, &jalv->ui_scale_factor }, - { 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->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); + + jalv->features.request_value.handle = jalv; + init_feature(&jalv->features.request_value_feature, + LV2_UI__requestValue, + &jalv->features.request_value); + + 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_extensionData = lilv_new_uri(world, LV2_CORE__extensionData); + 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.ui_showInterface = lilv_new_uri(world, LV2_UI__showInterface); + 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 */ + jalv->uis = lilv_plugin_get_uis(jalv->plugin); + if (!jalv->opts.generic_ui) { + if ((jalv->ui = jalv_select_custom_ui(jalv))) { + const char* host_type_uri = jalv_native_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); + } + } + } + + /* 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); + } + + if (jalv->opts.scale_factor == 0.0) { + /* Calculate the monitor's scale factor. */ + jalv->ui_scale_factor = jalv_ui_scale_factor(jalv); + } else { + /* Use user-specified UI scale factor. */ + jalv->ui_scale_factor = jalv->opts.scale_factor; + } + + /* 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: %u bytes\n", jalv->opts.buffer_size); + fprintf(stderr, "Update rate: %.01f Hz\n", jalv->ui_update_hz); + fprintf(stderr, "Scale factor: %.01f\n", jalv->ui_scale_factor); + + /* 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, + jalv->urids.ui_scaleFactor, + sizeof(float), + jalv->urids.atom_Float, + &jalv->ui_scale_factor}, + {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; } int jalv_close(Jalv* const jalv) { - jalv->exit = true; + jalv->exit = true; - fprintf(stderr, "Exiting...\n"); + fprintf(stderr, "Exiting...\n"); - /* Terminate the worker */ - jalv_worker_finish(&jalv->worker); + /* 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); + /* 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); - /* Destroy the worker */ - jalv_worker_destroy(&jalv->worker); + /* Destroy the worker */ + jalv_worker_destroy(&jalv->worker); - /* Deactivate plugin */ + /* Deactivate plugin */ #ifdef HAVE_SUIL - suil_instance_free(jalv->ui_instance); + 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); + 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); + 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.load); - free(jalv->opts.controls); - - return 0; + 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.load); + free(jalv->opts.controls); + + return 0; } int main(int argc, char** argv) { - Jalv jalv; - memset(&jalv, '\0', sizeof(Jalv)); + Jalv jalv; + memset(&jalv, '\0', sizeof(Jalv)); - if (jalv_open(&jalv, &argc, &argv)) { - return EXIT_FAILURE; - } + if (jalv_open(&jalv, &argc, &argv)) { + return EXIT_FAILURE; + } - /* Set up signal handlers */ - setup_signals(&jalv); + /* Set up signal handlers */ + setup_signals(&jalv); - /* Run UI (or prompt at console) */ - jalv_open_ui(&jalv); + /* Run UI (or prompt at console) */ + jalv_open_ui(&jalv); - /* Wait for finish signal from UI or signal handler */ - zix_sem_wait(&jalv.done); + /* Wait for finish signal from UI or signal handler */ + zix_sem_wait(&jalv.done); - return jalv_close(&jalv); + return jalv_close(&jalv); } diff --git a/src/jalv_console.c b/src/jalv_console.c index 13eb330..2e43495 100644 --- a/src/jalv_console.c +++ b/src/jalv_console.c @@ -15,8 +15,8 @@ */ #define _POSIX_C_SOURCE 200809L -#define _XOPEN_SOURCE 600 -#define _BSD_SOURCE 1 +#define _XOPEN_SOURCE 600 +#define _BSD_SOURCE 1 #define _DEFAULT_SOURCE 1 #include "jalv_config.h" @@ -38,21 +38,21 @@ 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, " -U URI Load the UI with the given URI\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, " -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"); + 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, " -U URI Load the UI with the given URI\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, " -x Exact JACK client name (exit if taken)\n"); + return error ? 1 : 0; } void @@ -62,96 +62,94 @@ jalv_ui_port_event(Jalv* jalv, uint32_t protocol, const void* buffer) { - if (jalv->ui_instance) { - suil_instance_port_event(jalv->ui_instance, port_index, - buffer_size, protocol, buffer); - } + if (jalv->ui_instance) { + suil_instance_port_event( + jalv->ui_instance, port_index, buffer_size, protocol, buffer); + } } int jalv_init(int* argc, char*** argv, JalvOptions* 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); - } + 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); + } - 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->ui_uri = 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); - } - } + 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->ui_uri = 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; + return 0; } const char* jalv_native_ui_type(void) { - return NULL; + return NULL; } static void jalv_print_controls(Jalv* jalv, bool writable, 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->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); + } + } } static int @@ -160,147 +158,147 @@ jalv_print_preset(Jalv* ZIX_UNUSED(jalv), const LilvNode* title, 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[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); - 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 %1023[a-zA-Z0-9_] %f", sym, &value) == 2 || - sscanf(cmd, "%1023[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); + 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 %1023[a-zA-Z0-9_] %f", sym, &value) == 2 || + sscanf(cmd, "%1023[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"); + } } bool jalv_discover_ui(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); - } + 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)); + 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); - } + // 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; - } + show_iface->hide(suil_instance_get_handle(jalv->ui_instance)); + return true; + } #endif - return false; + return false; } float jalv_ui_refresh_rate(Jalv* ZIX_UNUSED(jalv)) { - return 30.0f; + return 30.0f; } float jalv_ui_scale_factor(Jalv* ZIX_UNUSED(jalv)) { - return 1.0f; + return 1.0f; } int jalv_open_ui(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[1024]; - printf("> "); - if (fgets(line, sizeof(line), stdin)) { - jalv_process_command(jalv, line); - } else { - break; - } - } - } else { - zix_sem_wait(&jalv->done); - } + 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); + // Caller waits on the done sem, so increment it again to exit + zix_sem_post(&jalv->done); - return 0; + return 0; } int jalv_close_ui(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 f909425..33b4b48 100644 --- a/src/jalv_gtk.c +++ b/src/jalv_gtk.c @@ -49,268 +49,347 @@ static bool updating = false; /** Widget for a control. */ typedef struct { - GtkSpinButton* spin; - GtkWidget* control; + GtkSpinButton* spin; + GtkWidget* 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); - } + if (lilv_node_is_float(node) || lilv_node_is_int(node)) { + return lilv_node_as_float(node); + } - return fallback; + 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 +#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 +#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 } static void size_request(GtkWidget* widget, GtkRequisition* req) { - #if GTK_MAJOR_VERSION == 3 - gtk_widget_get_preferred_size(widget, NULL, req); - #else - gtk_widget_size_request(widget, req); - #endif +#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(GtkWidget* ZIX_UNUSED(widget), gpointer ZIX_UNUSED(data)) { - gtk_main_quit(); + gtk_main_quit(); } int jalv_init(int* argc, char*** argv, JalvOptions* opts) { - GOptionEntry entries[] = { - { "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 }, - { "ui-uri", 'U', 0, G_OPTION_ARG_STRING, &opts->ui_uri, - "Load the UI with the given URI", "URI" }, - { "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}, - { "scale-factor", 0, 0, G_OPTION_ARG_DOUBLE, &opts->scale_factor, - "UI scale factor", 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; + GOptionEntry entries[] = { + {"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}, + {"ui-uri", + 'U', + 0, + G_OPTION_ARG_STRING, + &opts->ui_uri, + "Load the UI with the given URI", + "URI"}, + {"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}, + {"scale-factor", + 0, + 0, + G_OPTION_ARG_DOUBLE, + &opts->scale_factor, + "UI scale factor", + 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 char* jalv_native_ui_type(void) { #if GTK_MAJOR_VERSION == 2 - return "http://lv2plug.in/ns/extensions/ui#GtkUI"; + return "http://lv2plug.in/ns/extensions/ui#GtkUI"; #elif GTK_MAJOR_VERSION == 3 - return "http://lv2plug.in/ns/extensions/ui#Gtk3UI"; + return "http://lv2plug.in/ns/extensions/ui#Gtk3UI"; #else - return NULL; + return NULL; #endif } static void 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(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, 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) { - 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 = 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; } 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, gpointer ZIX_UNUSED(data)) { - return strcmp(((const PresetMenu*)a)->label, ((const PresetMenu*)b)->label); + return strcmp(((const PresetMenu*)a)->label, ((const PresetMenu*)b)->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); + 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); } static int @@ -319,185 +398,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); + } + + 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(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)); } 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_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); } static void @@ -506,41 +590,41 @@ 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(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 = lrintf(value); - set_control(control, sizeof(ival), control->jalv->forge.Int, &ival); - } else if (control->value_type == control->jalv->forge.Long) { - const int64_t lval = lrintf(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); - } + if (control->value_type == control->jalv->forge.Int) { + const int32_t ival = lrintf(value); + set_control(control, sizeof(ival), control->jalv->forge.Int, &ival); + } else if (control->value_type == control->jalv->forge.Long) { + const int64_t lval = lrintf(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); + } } static double @@ -549,23 +633,23 @@ get_atom_double(Jalv* jalv, LV2_URID type, const void* body) { - if (type == jalv->forge.Int || type == jalv->forge.Bool) { - return *(const int32_t*)body; - } + 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.Long) { + return *(const int64_t*)body; + } - if (type == jalv->forge.Float) { - return *(const float*)body; - } + if (type == jalv->forge.Float) { + return *(const float*)body; + } - if (type == jalv->forge.Double) { - return *(const double*)body; - } + if (type == jalv->forge.Double) { + return *(const double*)body; + } - return NAN; + return NAN; } static void @@ -575,46 +659,44 @@ control_changed(Jalv* jalv, 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 = {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"); + } } static int @@ -623,21 +705,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; - } - - 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) { + fprintf(stderr, "patch:Set message with no property\n"); + return 1; + } + + if ((*property)->atom.type != jalv->forge.URID) { + fprintf(stderr, "patch:Set property is not a URID\n"); + return 1; + } + + return 0; } static int @@ -645,20 +729,18 @@ 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; - } - - 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) { + fprintf(stderr, "patch:Put message with no body\n"); + return 1; + } + + 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; } static LV2UI_Request_Value_Status @@ -667,49 +749,47 @@ on_request_value(LV2UI_Feature_Handle handle, const LV2_URID ZIX_UNUSED(type), const LV2_Feature* const* ZIX_UNUSED(features)) { - Jalv* jalv = (Jalv*)handle; - ControlID* control = get_property_control(&jalv->controls, key); + Jalv* jalv = (Jalv*)handle; + ControlID* control = get_property_control(&jalv->controls, key); - if (!control) { - return LV2UI_REQUEST_VALUE_ERR_UNKNOWN; - } + if (!control) { + return LV2UI_REQUEST_VALUE_ERR_UNKNOWN; + } - if (control->value_type != jalv->forge.Path) { - return LV2UI_REQUEST_VALUE_ERR_UNSUPPORTED; - } + 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, - GTK_STOCK_CANCEL, GTK_RESPONSE_CANCEL, - GTK_STOCK_OK, GTK_RESPONSE_OK, - NULL); + GtkWidget* dialog = gtk_file_chooser_dialog_new("Choose file", + GTK_WINDOW(jalv->window), + GTK_FILE_CHOOSER_ACTION_OPEN, + GTK_STOCK_CANCEL, + GTK_RESPONSE_CANCEL, + GTK_STOCK_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)); + 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); + set_control(control, strlen(path) + 1, jalv->forge.Path, path); - g_free(path); - } + g_free(path); + } - gtk_widget_destroy(dialog); + gtk_widget_destroy(dialog); - return 0; + 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 @@ -719,334 +799,329 @@ jalv_ui_port_event(Jalv* jalv, uint32_t protocol, const void* buffer) { - if (jalv->ui_instance) { - suil_instance_port_event(jalv->ui_instance, port_index, - buffer_size, protocol, buffer); - return; - } - - 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; - } - - if (protocol == 0) { - return; // No widget (probably notOnGUI) - } - - 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*)jalv->ports[port_index].widget) { + control_changed(jalv, + (Controller*)jalv->ports[port_index].widget, + buffer_size, + jalv->forge.Float, + buffer); + return; + } + + if (protocol == 0) { + return; // No widget (probably notOnGUI) + } + + 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; + } } 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 = {0, {{0}}}; - 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) { - set_float_control((const ControlID*)data, - gtk_toggle_button_get_active(button) ? 1.0f : 0.0f); - return FALSE; + set_float_control((const ControlID*)data, + gtk_toggle_button_get_active(button) ? 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); + ControlID* control = (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, control->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)); + ControlID* control = (ControlID*)data; + Jalv* jalv = control->jalv; + const char* filename = + gtk_file_chooser_get_filename(GTK_FILE_CHOOSER(widget)); - set_control(control, strlen(filename) + 1, jalv->forge.Path, filename); + set_control(control, strlen(filename) + 1, 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 (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); - - 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); + + 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* 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); } 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( - "%s", 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* 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( + "%s", 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); } static Controller* make_toggle(ControlID* record, float value) { - GtkWidget* check = gtk_check_button_new(); + GtkWidget* check = gtk_check_button_new(); - gtk_widget_set_sensitive(check, record->is_writable); + gtk_widget_set_sensitive(check, record->is_writable); - if (value) { - gtk_toggle_button_set_active(GTK_TOGGLE_BUTTON(check), TRUE); - } + if (value) { + gtk_toggle_button_set_active(GTK_TOGGLE_BUTTON(check), 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(check), "toggled", G_CALLBACK(toggle_changed), record); + } - return new_controller(NULL, check); + return new_controller(NULL, check); } 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(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) { - GtkWidget* label = gtk_label_new(NULL); - const char* fmt = title ? "%s" : "%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* label = gtk_label_new(NULL); + const char* fmt = title ? "%s" : "%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; } static void @@ -1055,191 +1130,220 @@ add_control_row(GtkWidget* table, 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, 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); } static int 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; - } - - 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_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; + } + + 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; } 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_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); } bool jalv_discover_ui(Jalv* ZIX_UNUSED(jalv)) { - return TRUE; + return TRUE; } float jalv_ui_refresh_rate(Jalv* ZIX_UNUSED(jalv)) { #if GTK_MAJOR_VERSION == 2 - return 30.0f; + 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; + return rate < 30.0f ? 30.0f : rate; #endif } @@ -1247,94 +1351,92 @@ float jalv_ui_scale_factor(Jalv* ZIX_UNUSED(jalv)) { #if GTK_MAJOR_VERSION == 2 - return 1.0f; + return 1.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); - return (float)gdk_monitor_get_scale_factor(monitor); + return (float)gdk_monitor_get_scale_factor(monitor); #endif } int jalv_open_ui(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); - } - - 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(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 = {0, 0}; - GtkRequisition box_size = {0, 0}; - 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; + 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); + } + + 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(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 = {0, 0}; + GtkRequisition box_size = {0, 0}; + 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; } int jalv_close_ui(Jalv* ZIX_UNUSED(jalv)) { - gtk_main_quit(); - return 0; + gtk_main_quit(); + return 0; } LV2_RESTORE_WARNINGS diff --git a/src/jalv_gtkmm2.cpp b/src/jalv_gtkmm2.cpp index ca49602..a967563 100644 --- a/src/jalv_gtkmm2.cpp +++ b/src/jalv_gtkmm2.cpp @@ -36,14 +36,14 @@ static Gtk::Main* jalv_gtk_main = nullptr; int jalv_init(int* argc, char*** argv, JalvOptions*) { - jalv_gtk_main = new Gtk::Main(*argc, *argv); - return 0; + 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"; + return "http://lv2plug.in/ns/extensions/ui#GtkUI"; } void @@ -53,72 +53,72 @@ jalv_ui_port_event(Jalv* jalv, uint32_t protocol, const void* buffer) { - if (jalv->ui_instance) { - suil_instance_port_event(jalv->ui_instance, port_index, - buffer_size, protocol, buffer); - } + if (jalv->ui_instance) { + suil_instance_port_event( + jalv->ui_instance, port_index, buffer_size, protocol, buffer); + } } bool jalv_discover_ui(Jalv*) { - return true; + return true; } float jalv_ui_refresh_rate(Jalv*) { - return 30.0f; + return 30.0f; } float jalv_ui_scale_factor(Jalv*) { - return 1.0f; + return 1.0f; } int jalv_open_ui(Jalv* jalv) { - auto* const window = new Gtk::Window(); + auto* const window = new Gtk::Window(); - if (jalv->ui) { - jalv_ui_instantiate(jalv, jalv_native_ui_type(), nullptr); - } + if (jalv->ui) { + jalv_ui_instantiate(jalv, jalv_native_ui_type(), nullptr); + } - if (jalv->ui_instance) { - auto* const widget = static_cast( - suil_instance_get_widget(jalv->ui_instance)); + if (jalv->ui_instance) { + auto* const widget = + static_cast(suil_instance_get_widget(jalv->ui_instance)); - Gtk::Widget* widgetmm = Glib::wrap(widget); - window->add(*Gtk::manage(widgetmm)); - widgetmm->show_all(); + Gtk::Widget* widgetmm = Glib::wrap(widget); + window->add(*Gtk::manage(widgetmm)); + widgetmm->show_all(); - g_timeout_add(1000 / jalv->ui_update_hz, - reinterpret_cast(jalv_update), - jalv); - } else { - Gtk::Button* button = Gtk::manage(new Gtk::Button("Close")); - window->add(*Gtk::manage(button)); - } + g_timeout_add(1000 / jalv->ui_update_hz, + reinterpret_cast(jalv_update), + jalv); + } else { + Gtk::Button* button = Gtk::manage(new Gtk::Button("Close")); + window->add(*Gtk::manage(button)); + } - jalv_init_ui(jalv); + jalv_init_ui(jalv); - window->set_resizable(jalv_ui_is_resizable(jalv)); - window->show_all(); + window->set_resizable(jalv_ui_is_resizable(jalv)); + window->show_all(); - Gtk::Main::run(*window); + Gtk::Main::run(*window); - delete window; - delete jalv_gtk_main; - zix_sem_post(&jalv->done); + delete window; + delete jalv_gtk_main; + zix_sem_post(&jalv->done); - return 0; + return 0; } int jalv_close_ui(Jalv*) { - Gtk::Main::quit(); - return 0; + Gtk::Main::quit(); + return 0; } diff --git a/src/jalv_internal.h b/src/jalv_internal.h index e14dab6..4a710d7 100644 --- a/src/jalv_internal.h +++ b/src/jalv_internal.h @@ -31,7 +31,7 @@ #include "serd/serd.h" #include "sratom/sratom.h" #ifdef HAVE_SUIL -#include "suil/suil.h" +# include "suil/suil.h" #endif #include "lv2/atom/atom.h" @@ -46,7 +46,7 @@ #include "lv2/worker/worker.h" #ifdef HAVE_ISATTY -# include +# include #endif #include @@ -57,15 +57,15 @@ #include #ifdef __clang__ -# define REALTIME __attribute__((annotate("realtime"))) +# define REALTIME __attribute__((annotate("realtime"))) #else -# define REALTIME +# define REALTIME #endif #ifdef __GNUC__ -# define JALV_LOG_FUNC(fmt, arg1) __attribute__((format(printf, fmt, arg1))) +# define JALV_LOG_FUNC(fmt, arg1) __attribute__((format(printf, fmt, arg1))) #else -# define JALV_LOG_FUNC(fmt, arg1) +# define JALV_LOG_FUNC(fmt, arg1) #endif #ifdef __cplusplus @@ -78,71 +78,62 @@ typedef struct JalvBackend JalvBackend; typedef struct Jalv Jalv; -enum PortFlow { - FLOW_UNKNOWN, - FLOW_INPUT, - FLOW_OUTPUT -}; +enum PortFlow { FLOW_UNKNOWN, FLOW_INPUT, FLOW_OUTPUT }; -enum PortType { - TYPE_UNKNOWN, - TYPE_CONTROL, - TYPE_AUDIO, - TYPE_EVENT, - TYPE_CV -}; +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 + 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) + PORT, ///< Control port + PROPERTY ///< Property (set via atom message) } ControlType; typedef struct { - float value; - char* label; + float value; + char* label; } ScalePoint; /** Order scale points by value. */ -int scale_point_cmp(const ScalePoint* a, const ScalePoint* b); +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) + 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* @@ -152,8 +143,8 @@ ControlID* new_property_control(Jalv* jalv, const LilvNode* property); typedef struct { - size_t n_controls; - ControlID** controls; + size_t n_controls; + ControlID** controls; } Controls; void @@ -166,200 +157,196 @@ 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[]; + 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* 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 - 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 + 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 buffer_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; 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_scaleFactor; - LV2_URID ui_updateRate; + 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_scaleFactor; + 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_extensionData; - 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* ui_showInterface; - LilvNode* work_interface; - LilvNode* work_schedule; - LilvNode* end; ///< NULL terminator for easy freeing of entire structure + 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_extensionData; + 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* ui_showInterface; + 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 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 + 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[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; + 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; 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) + 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) + 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 ui_scale_factor; ///< UI scale factor - 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; + 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 ui_scale_factor; ///< UI scale factor + 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 @@ -430,9 +417,7 @@ int jalv_close_ui(Jalv* jalv); void -jalv_ui_instantiate(Jalv* jalv, - const char* native_ui_type, - void* parent); +jalv_ui_instantiate(Jalv* jalv, const char* native_ui_type, void* parent); bool jalv_ui_is_resizable(Jalv* jalv); @@ -497,12 +482,9 @@ void jalv_save(Jalv* jalv, const char* dir); void -jalv_save_port_values(Jalv* jalv, - SerdWriter* writer, - const SerdNode* subject); +jalv_save_port_values(Jalv* jalv, SerdWriter* writer, const SerdNode* subject); char* -jalv_make_path(LV2_State_Make_Path_Handle handle, - const char* path); +jalv_make_path(LV2_State_Make_Path_Handle handle, const char* path); void jalv_apply_state(Jalv* jalv, LilvState* state); @@ -516,70 +498,65 @@ atom_to_turtle(LV2_URID_Unmap* unmap, 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); + 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; + 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); + 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'; + memcpy(out, a, a_len); + memcpy(out + a_len, b, b_len); + out[a_len + b_len] = '\0'; - return out; + return out; } JALV_LOG_FUNC(3, 4) int -jalv_printf(LV2_Log_Handle handle, - LV2_URID type, - const char* fmt, ...); +jalv_printf(LV2_Log_Handle handle, LV2_URID type, const char* fmt, ...); JALV_LOG_FUNC(3, 0) int -jalv_vprintf(LV2_Log_Handle handle, - LV2_URID type, - const char* fmt, - va_list ap); +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); - } + if (isatty(fileno(stream))) { + return fprintf(stream, "\033[0;%dm", color); + } #endif - return 0; + return 0; } static inline void jalv_ansi_reset(FILE* stream) { #ifdef HAVE_ISATTY - if (isatty(fileno(stream))) { - fprintf(stream, "\033[0m"); - fflush(stream); - } + if (isatty(fileno(stream))) { + fprintf(stream, "\033[0m"); + fflush(stream); + } #endif } #ifdef __cplusplus -} // extern "C" +} // extern "C" #endif -#endif // JALV_INTERNAL_H +#endif // JALV_INTERNAL_H diff --git a/src/jalv_qt.cpp b/src/jalv_qt.cpp index 9293a08..c7c2743 100644 --- a/src/jalv_qt.cpp +++ b/src/jalv_qt.cpp @@ -59,290 +59,286 @@ #include #define CONTROL_WIDTH 150 -#define DIAL_STEPS 10000 +#define DIAL_STEPS 10000 static QApplication* app = nullptr; class FlowLayout : public QLayout { public: - explicit FlowLayout(QWidget* parent, - int margin, - int hSpacing, - int vSpacing); - - 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; + explicit FlowLayout(QWidget* parent, int margin, int hSpacing, int vSpacing); + + 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 itemList; - int m_hSpace; - int m_vSpace; + QList itemList; + int m_hSpace; + int m_vSpace; }; FlowLayout::FlowLayout(QWidget* parent, int margin, int hSpacing, int vSpacing) - : QLayout(parent), m_hSpace(hSpacing), m_vSpace(vSpacing) + : QLayout(parent) + , m_hSpace(hSpacing) + , m_vSpace(vSpacing) { - setContentsMargins(margin, margin, margin, margin); + setContentsMargins(margin, margin, margin, margin); } FlowLayout::FlowLayout(int margin, int hSpacing, int vSpacing) - : m_hSpace(hSpacing), m_vSpace(vSpacing) + : m_hSpace(hSpacing) + , m_vSpace(vSpacing) { - setContentsMargins(margin, margin, margin, margin); + setContentsMargins(margin, margin, margin, margin); } FlowLayout::~FlowLayout() { - QLayoutItem* item = nullptr; - 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; - } + if (m_hSpace >= 0) { + return m_hSpace; + } - return smartSpacing(QStyle::PM_LayoutHorizontalSpacing); + return smartSpacing(QStyle::PM_LayoutHorizontalSpacing); } int FlowLayout::verticalSpacing() const { - if (m_vSpace >= 0) { - return m_vSpace; - } + if (m_vSpace >= 0) { + return m_vSpace; + } - return smartSpacing(QStyle::PM_LayoutVerticalSpacing); + 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); - } + if (index >= 0 && index < itemList.size()) { + return itemList.takeAt(index); + } - return nullptr; + return nullptr; } Qt::Orientations FlowLayout::expandingDirections() const { - return {}; + 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 = nullptr; - foreach (item, itemList) { - size = size.expandedTo(item->minimumSize()); - } + QSize size = {}; + QLayoutItem* item = nullptr; + foreach (item, itemList) { + size = size.expandedTo(item->minimumSize()); + } - return size + QSize(2 * margin(), 2 * margin()); + return size + QSize(2 * margin(), 2 * margin()); } int -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); - - QRect effectiveRect = rect.adjusted(+left, +top, -right, -bottom); - int x = effectiveRect.x(); - int y = effectiveRect.y(); - int lineHeight = 0; - - QLayoutItem* item = nullptr; - foreach (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; +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); + + QRect effectiveRect = rect.adjusted(+left, +top, -right, -bottom); + int x = effectiveRect.x(); + int y = effectiveRect.y(); + int lineHeight = 0; + + QLayoutItem* item = nullptr; + foreach (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; - } + QObject* parent = this->parent(); + if (!parent) { + return -1; + } - if (parent->isWidgetType()) { - auto* const pw = static_cast(parent); - return pw->style()->pixelMetric(pm, nullptr, pw); - } + if (parent->isWidgetType()) { + auto* const pw = static_cast(parent); + return pw->style()->pixelMetric(pm, nullptr, pw); + } - return static_cast(parent)->spacing(); + return static_cast(parent)->spacing(); } class PresetAction : public QAction { - Q_OBJECT // NOLINT + 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); - } + 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; + Jalv* _jalv; + LilvNode* _preset; }; struct PortContainer { - Jalv* jalv; - struct Port* port; + Jalv* jalv; + struct Port* port; }; class Control : public QGroupBox { - Q_OBJECT // NOLINT + Q_OBJECT // NOLINT -public: - explicit Control(PortContainer portContainer, QWidget* parent); + public : explicit Control(PortContainer portContainer, QWidget* parent); - Q_SLOT void dialChanged(int value); + Q_SLOT void dialChanged(int value); - void setValue(float 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; - const LilvPlugin* plugin; - struct Port* port; - - QLabel* label; - QString name; - int steps; - float max; - float min; - bool isInteger; - bool isEnum; - bool isLogarithmic; - - std::vector scalePoints; - std::map scaleMap; + void setRange(float min, float max); + QString getValueLabel(float value); + float getValue(); + int stringWidth(const QString& str); + + QDial* dial; + const LilvPlugin* plugin; + struct Port* port; + + QLabel* label; + QString name; + int steps; + float max; + float min; + bool isInteger; + bool isEnum; + bool isLogarithmic; + + std::vector scalePoints; + std::map scaleMap; }; #include "jalv_qt5_meta.hpp" // IWYU pragma: keep @@ -352,16 +348,16 @@ extern "C" { int jalv_init(int* argc, char*** argv, JalvOptions*) { - app = new QApplication(*argc, *argv, true); - app->setStyleSheet("QGroupBox::title { subcontrol-position: top center }"); + app = new QApplication(*argc, *argv, true); + app->setStyleSheet("QGroupBox::title { subcontrol-position: top center }"); - return 0; + return 0; } const char* jalv_native_ui_type(void) { - return "http://lv2plug.in/ns/extensions/ui#Qt5UI"; + return "http://lv2plug.in/ns/extensions/ui#Qt5UI"; } void @@ -371,29 +367,28 @@ jalv_ui_port_event(Jalv* jalv, 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(jalv->ports[port_index].widget); - if (control) { - control->setValue(*static_cast(buffer)); - } - } + if (jalv->ui_instance) { + suil_instance_port_event( + jalv->ui_instance, port_index, buffer_size, protocol, buffer); + } else { + auto* const control = static_cast(jalv->ports[port_index].widget); + if (control) { + control->setValue(*static_cast(buffer)); + } + } } class Timer : public QTimer { public: - explicit Timer(Jalv* jalv) : _jalv(jalv) {} + explicit Timer(Jalv* jalv) + : _jalv(jalv) + {} - void timerEvent(QTimerEvent*) override { - jalv_update(_jalv); - } + void timerEvent(QTimerEvent*) override { jalv_update(_jalv); } private: - Jalv* _jalv; + Jalv* _jalv; }; static int @@ -402,388 +397,384 @@ add_preset_to_menu(Jalv* jalv, const LilvNode* title, void* data) { - auto* const menu = static_cast(data); - const char* label = lilv_node_as_string(title); + auto* const menu = static_cast(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; } Control::Control(PortContainer portContainer, QWidget* parent) - : QGroupBox(parent) - , dial(new QDial()) - , plugin(portContainer.jalv->plugin) - , port(portContainer.port) - , label(new QLabel()) - , max(1.0f) - , min(0.0f) - , isInteger(false) - , isEnum(false) - , isLogarithmic(false) -{ - JalvNodes* nodes = &portContainer.jalv->nodes; - 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 - 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 - 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); + : QGroupBox(parent) + , dial(new QDial()) + , plugin(portContainer.jalv->plugin) + , port(portContainer.port) + , label(new QLabel()) + , max(1.0f) + , min(0.0f) + , isInteger(false) + , isEnum(false) + , isLogarithmic(false) +{ + JalvNodes* nodes = &portContainer.jalv->nodes; + 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 + 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 + 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 = 0.0f; + 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 * logf(value / min) / logf(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()]; - } + if (isEnum) { + return scalePoints[dial->value()]; + } - if (isInteger) { - return dial->value(); - } + if (isInteger) { + return dial->value(); + } - if (isLogarithmic) { - return min * powf(max / min, (float)dial->value() / (steps - 1)); - } + if (isLogarithmic) { + return min * powf(max / min, (float)dial->value() / (steps - 1)); + } - return (float)dial->value() / steps; + return (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) { - float value = getValue(); + float value = getValue(); - label->setText(getValueLabel(value)); - port->control = value; + label->setText(getValueLabel(value)); + port->control = value; } static bool -portGroupLessThan(const PortContainer &p1, const PortContainer &p2) +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; + 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)) + : (intptr_t(group1) - 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* build_control_widget(Jalv* jalv) { - const LilvPlugin* plugin = jalv->plugin; - LilvWorld* world = jalv->world; - - QList 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) { - PortContainer portContainer = portContainers[i]; - Port* 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 (!lilv_node_equals(group, lastGroup)) { - /* Group has changed */ - 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; - - 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 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) { + PortContainer portContainer = portContainers[i]; + Port* 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 (!lilv_node_equals(group, lastGroup)) { + /* Group has changed */ + 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; + + 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; } bool jalv_discover_ui(Jalv*) { - return true; + return true; } float jalv_ui_refresh_rate(Jalv*) { - return (float)QGuiApplication::primaryScreen()->refreshRate(); + return (float)QGuiApplication::primaryScreen()->refreshRate(); } float jalv_ui_scale_factor(Jalv*) { - return (float)QGuiApplication::primaryScreen()->devicePixelRatio(); + return (float)QGuiApplication::primaryScreen()->devicePixelRatio(); } int jalv_open_ui(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); + 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); + 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); + 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); - } + if (jalv->ui && !jalv->opts.generic_ui) { + jalv_ui_instantiate(jalv, jalv_native_ui_type(), win); + } - QWidget* widget = nullptr; - if (jalv->ui_instance) { - widget = - static_cast(suil_instance_get_widget(jalv->ui_instance)); - } else { - QWidget* controlWidget = build_control_widget(jalv); + QWidget* widget = nullptr; + if (jalv->ui_instance) { + widget = static_cast(suil_instance_get_widget(jalv->ui_instance)); + } else { + QWidget* controlWidget = build_control_widget(jalv); - widget = new QScrollArea(); - static_cast(widget)->setWidget(controlWidget); - static_cast(widget)->setWidgetResizable(true); - widget->setMinimumWidth(800); - widget->setMinimumHeight(600); - } + widget = new QScrollArea(); + static_cast(widget)->setWidget(controlWidget); + static_cast(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); + 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->setCentralWidget(widget); + app->connect(app, SIGNAL(lastWindowClosed()), app, SLOT(quit())); - jalv_init_ui(jalv); + jalv_init_ui(jalv); - 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()); - } + 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()); + } - auto* const timer = new Timer(jalv); - timer->start(1000 / jalv->ui_update_hz); + auto* const timer = new Timer(jalv); + timer->start(1000 / jalv->ui_update_hz); - int ret = app->exec(); - zix_sem_post(&jalv->done); - return ret; + int ret = app->exec(); + zix_sem_post(&jalv->done); + return ret; } int jalv_close_ui(Jalv*) { - app->quit(); - return 0; + app->quit(); + return 0; } -} // extern "C" +} // extern "C" diff --git a/src/log.c b/src/log.c index dbf9805..3d1bfec 100644 --- a/src/log.c +++ b/src/log.c @@ -24,44 +24,39 @@ #include int -jalv_printf(LV2_Log_Handle handle, - LV2_URID type, - const char* fmt, ...) +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; + va_list args; + va_start(args, fmt); + const int ret = jalv_vprintf(handle, type, fmt, args); + va_end(args); + return ret; } int -jalv_vprintf(LV2_Log_Handle handle, - LV2_URID type, - const char* fmt, - va_list ap) +jalv_vprintf(LV2_Log_Handle handle, LV2_URID type, const char* fmt, va_list ap) { - // 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; + // 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; } diff --git a/src/lv2_evbuf.c b/src/lv2_evbuf.c index 61e5720..0d36dc9 100644 --- a/src/lv2_evbuf.c +++ b/src/lv2_evbuf.c @@ -23,103 +23,104 @@ #include 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; + LV2_Atom_Sequence buf; }; static inline uint32_t lv2_evbuf_pad_size(uint32_t size) { - return (size + 7) & (~7); + 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; + // 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; } void lv2_evbuf_free(LV2_Evbuf* evbuf) { - free(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_evbuf_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) { - if (!lv2_evbuf_is_valid(iter)) { - return iter; - } - - LV2_Evbuf* evbuf = iter.evbuf; - uint32_t offset = iter.offset; - uint32_t size = 0; - 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_Evbuf* evbuf = iter.evbuf; + uint32_t offset = iter.offset; + uint32_t size = 0; + 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; } bool @@ -130,24 +131,25 @@ lv2_evbuf_get(LV2_Evbuf_Iterator iter, uint32_t* size, uint8_t** 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 = (uint8_t*)LV2_ATOM_BODY(&aev->body); - return true; + return true; } bool @@ -158,25 +160,26 @@ lv2_evbuf_write(LV2_Evbuf_Iterator* iter, uint32_t size, const uint8_t* data) { - (void)subframes; + (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_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_evbuf_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 f77d3b5..40acbe5 100644 --- a/src/lv2_evbuf.h +++ b/src/lv2_evbuf.h @@ -22,7 +22,7 @@ #ifdef __cplusplus extern "C" { #else -#include +# include #endif /** @@ -34,8 +34,8 @@ typedef struct LV2_Evbuf_Impl 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; /** diff --git a/src/portaudio.c b/src/portaudio.c index bbfa871..dda88ae 100644 --- a/src/portaudio.c +++ b/src/portaudio.c @@ -17,12 +17,12 @@ #include "jalv_internal.h" #include "worker.h" -#include #include #include +#include struct JalvBackend { - PaStream* stream; + PaStream* stream; }; static int @@ -33,191 +33,195 @@ pa_process_cb(const void* inputs, PaStreamCallbackFlags flags, void* handle) { - 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; + 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; } static JalvBackend* pa_error(const char* msg, PaError err) { - fprintf(stderr, "error: %s (%s)\n", msg, Pa_GetErrorText(err)); - Pa_Terminate(); - return NULL; + fprintf(stderr, "error: %s (%s)\n", msg, Pa_GetErrorText(err)); + Pa_Terminate(); + return NULL; } JalvBackend* jalv_backend_init(Jalv* jalv) { - 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; + 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; } void jalv_backend_close(Jalv* jalv) { - Pa_Terminate(); - free(jalv->backend); - jalv->backend = NULL; + Pa_Terminate(); + free(jalv->backend); + jalv->backend = NULL; } void jalv_backend_activate(Jalv* jalv) { - const int st = Pa_StartStream(jalv->backend->stream); - if (st != paNoError) { - fprintf(stderr, "error: Error starting audio stream (%s)\n", - Pa_GetErrorText(st)); - } + const int st = Pa_StartStream(jalv->backend->stream); + if (st != paNoError) { + fprintf( + stderr, "error: Error starting audio stream (%s)\n", Pa_GetErrorText(st)); + } } void jalv_backend_deactivate(Jalv* jalv) { - const int st = Pa_CloseStream(jalv->backend->stream); - if (st != paNoError) { - fprintf(stderr, "error: Error closing audio stream (%s)\n", - Pa_GetErrorText(st)); - } + const int st = Pa_CloseStream(jalv->backend->stream); + if (st != paNoError) { + fprintf( + stderr, "error: Error closing audio stream (%s)\n", Pa_GetErrorText(st)); + } } void jalv_backend_activate_port(Jalv* jalv, 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; - } + 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; + } } diff --git a/src/state.c b/src/state.c index d7dcb71..1c54cf0 100644 --- a/src/state.c +++ b/src/state.c @@ -31,13 +31,12 @@ #include char* -jalv_make_path(LV2_State_Make_Path_Handle handle, - const char* path) +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 + return jalv_strjoin(jalv->save_dir ? jalv->save_dir : jalv->temp_dir, path); } static const void* @@ -46,77 +45,85 @@ 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* 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; } 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; + 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; } 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 { + fprintf(stderr, + "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 @@ -126,86 +133,87 @@ set_port_value(const char* port_symbol, 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 = 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 { - 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* 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 = 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 { + 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)); + } } void jalv_apply_state(Jalv* jalv, 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; - } - } + 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; + } + } } 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->map, preset); + jalv_apply_state(jalv, jalv->preset); + return 0; } int @@ -215,35 +223,42 @@ 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; + 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; } 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/symap.c b/src/symap.c index b699269..196c963 100644 --- a/src/symap.c +++ b/src/symap.c @@ -38,56 +38,56 @@ */ 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; + /** + 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; }; Symap* symap_new(void) { - Symap* map = (Symap*)malloc(sizeof(Symap)); - map->symbols = NULL; - map->index = NULL; - map->size = 0; - return map; + Symap* map = (Symap*)malloc(sizeof(Symap)); + map->symbols = NULL; + map->index = NULL; + map->size = 0; + return map; } void symap_free(Symap* map) { - if (!map) { - return; - } + if (!map) { + return; + } - for (uint32_t i = 0; i < map->size; ++i) { - free(map->symbols[i]); - } + for (uint32_t i = 0; i < map->size; ++i) { + free(map->symbols[i]); + } - free(map->symbols); - free(map->index); - free(map); + free(map->symbols); + free(map->index); + free(map); } static char* symap_strdup(const char* 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* copy = (char*)malloc(len + 1); + memcpy(copy, str, len + 1); + return copy; } /** @@ -97,146 +97,144 @@ symap_strdup(const char* str) static uint32_t symap_search(const Symap* map, const char* sym, bool* exact) { - *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; - int cmp = 0; - - while (upper >= lower) { - i = lower + ((upper - lower) / 2); - 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; + *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; + int cmp = 0; + + while (upper >= lower) { + i = lower + ((upper - lower) / 2); + 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) { - bool exact = false; - 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) { + assert(!strcmp(map->symbols[map->index[index]], sym)); + return map->index[index]; + } + + return 0; } uint32_t symap_map(Symap* map, const char* sym) { - 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]; - } - - 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; + 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]; + } + + 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; } const char* symap_unmap(Symap* map, uint32_t id) { - if (id == 0) { - return NULL; - } + if (id == 0) { + return NULL; + } - if (id <= map->size) { - return map->symbols[id - 1]; - } + if (id <= map->size) { + return map->symbols[id - 1]; + } - return NULL; + return NULL; } #ifdef STANDALONE -#include +# include static void symap_dump(Symap* 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"); + 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"); } int main() { - #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; +# 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; } #endif /* STANDALONE */ diff --git a/src/worker.c b/src/worker.c index 3c42ffb..5192066 100644 --- a/src/worker.c +++ b/src/worker.c @@ -30,43 +30,43 @@ jalv_worker_respond(LV2_Worker_Respond_Handle handle, 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; + 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; } static void* worker_func(void* data) { - 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* 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; } void @@ -75,37 +75,37 @@ jalv_worker_init(Jalv* ZIX_UNUSED(jalv), const LV2_Worker_Interface* iface, bool threaded) { - 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); + 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); } void jalv_worker_finish(JalvWorker* worker) { - if (worker->threaded) { - zix_sem_post(&worker->sem); - zix_thread_join(worker->thread, NULL); - } + if (worker->threaded) { + zix_sem_post(&worker->sem); + zix_thread_join(worker->thread, NULL); + } } void jalv_worker_destroy(JalvWorker* worker) { - if (worker->requests) { - if (worker->threaded) { - zix_ring_free(worker->requests); - } - zix_ring_free(worker->responses); - free(worker->response); - } + if (worker->requests) { + if (worker->threaded) { + zix_ring_free(worker->requests); + } + zix_ring_free(worker->responses); + free(worker->response); + } } LV2_Worker_Status @@ -113,38 +113,38 @@ jalv_worker_schedule(LV2_Worker_Schedule_Handle handle, uint32_t size, const void* 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* 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; } void jalv_worker_emit_responses(JalvWorker* worker, LilvInstance* instance) { - 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)); + 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); + zix_ring_read(worker->responses, (char*)worker->response, size); - worker->iface->work_response( - instance->lv2_handle, size, worker->response); + worker->iface->work_response( + instance->lv2_handle, size, worker->response); - read_space -= sizeof(size) + size; - } - } + read_space -= sizeof(size) + size; + } + } } -- cgit v1.2.1