Merge pull request #34 from moddevices/mod-cleanup

Rework worker and cleanup
This commit is contained in:
Mike Oliphant
2023-06-15 11:39:39 -07:00
committed by GitHub
4 changed files with 167 additions and 124 deletions
+8 -6
View File
@@ -7,6 +7,7 @@
@prefix ui: <http://lv2plug.in/ns/extensions/ui#>.
@prefix units: <http://lv2plug.in/ns/extensions/units#>.
@prefix urid: <http://lv2plug.in/ns/ext/urid#>.
@prefix opts: <http://lv2plug.in/ns/ext/options#> .
@prefix param: <http://lv2plug.in/ns/ext/parameters#>.
@prefix patch: <http://lv2plug.in/ns/ext/patch#>.
@prefix state: <http://lv2plug.in/ns/ext/state#>.
@@ -14,13 +15,13 @@
@prefix mod: <http://moddevices.com/ns/mod#>.
<@NAM_LV2_ID@#model>
a lv2:Parameter;
a lv2:Parameter;
mod:fileTypes "nam,nammodel";
rdfs:label "Neural Model";
rdfs:range atom:Path.
rdfs:label "Neural Model";
rdfs:range atom:Path.
<@NAM_LV2_ID@>
a lv2:Plugin, lv2:SimulatorPlugin;
a lv2:Plugin, lv2:SimulatorPlugin, doap:Project;
doap:name "Neural Amp Modeler";
lv2:project <@NAM_LV2_ID@>;
lv2:minorVersion @PROJECT_VERSION_MINOR@;
@@ -33,8 +34,9 @@
];
lv2:requiredFeature urid:map, work:schedule;
lv2:optionalFeature lv2:hardRTCapable;
lv2:extensionData work:interface, state:interface;
lv2:optionalFeature lv2:hardRTCapable, opts:options, state:threadSafeRestore;
lv2:extensionData work:interface, state:interface, opts:interface;
opts:supportedOption <http://lv2plug.in/ns/ext/buf-size#maxBlockLength>;
rdfs:comment """
An LV2 implementation of Neural Amp Modeler.
+14 -6
View File
@@ -63,13 +63,14 @@ static void cleanup(LV2_Handle instance)
static const void* extension_data(const char* uri)
{
static const LV2_State_Interface state = {NAM::Plugin::save, NAM::Plugin::restore};
static const LV2_Worker_Interface worker = { NAM::Plugin::work, NAM::Plugin::work_response, NULL };
static const LV2_Options_Interface options = { NAM::Plugin::options_get, NAM::Plugin::options_set };
static const LV2_State_Interface state = { NAM::Plugin::save, NAM::Plugin::restore};
static const LV2_Worker_Interface worker = { NAM::Plugin::work, NAM::Plugin::work_response, NULL };
if (!strcmp(uri, LV2_STATE__interface)) {
if (!strcmp(uri, LV2_OPTIONS__interface))
return &options;
if (!strcmp(uri, LV2_STATE__interface))
return &state;
}
if (!strcmp(uri, LV2_WORKER__interface))
return &worker;
@@ -90,5 +91,12 @@ static const LV2_Descriptor descriptor =
LV2_SYMBOL_EXPORT const LV2_Descriptor* lv2_descriptor(uint32_t index)
{
return index == 0 ? &descriptor : nullptr;
if (index == 0) {
// Turn on fast tanh approximation
activations::Activation::enable_fast_tanh();
return &descriptor;
}
return nullptr;
}
+116 -94
View File
@@ -11,16 +11,19 @@
namespace NAM {
Plugin::Plugin()
{
// Turn on fast tanh approximation
activations::Activation::enable_fast_tanh();
// prevent allocations on the audio thread
currentModelPath.reserve(MAX_FILE_NAME+1);
}
Plugin::~Plugin()
{
delete currentModel;
}
bool Plugin::initialize(double rate, const LV2_Feature* const* features) noexcept
{
logger.log = nullptr;
// for fetching initial options, can be null
LV2_Options_Option* options = nullptr;
for (size_t i = 0; features[i]; ++i) {
if (std::string(features[i]->URI) == std::string(LV2_URID__map))
@@ -29,6 +32,8 @@ namespace NAM {
schedule = static_cast<LV2_Worker_Schedule*>(features[i]->data);
else if (std::string(features[i]->URI) == std::string(LV2_LOG__log))
logger.log = static_cast<LV2_Log_Log*>(features[i]->data);
else if (std::string(features[i]->URI) == std::string(LV2_OPTIONS__options))
options = static_cast<LV2_Options_Option*>(features[i]->data);
}
lv2_log_logger_set_map(&logger, map);
@@ -54,53 +59,68 @@ namespace NAM {
uris.atom_Int = map->map(map->handle, LV2_ATOM__Int);
uris.atom_Path = map->map(map->handle, LV2_ATOM__Path);
uris.atom_URID = map->map(map->handle, LV2_ATOM__URID);
uris.bufSize_maxBlockLength = map->map(map->handle, LV2_BUF_SIZE__maxBlockLength);
uris.patch_Set = map->map(map->handle, LV2_PATCH__Set);
uris.patch_Get = map->map(map->handle, LV2_PATCH__Get);
uris.patch_property = map->map(map->handle, LV2_PATCH__property);
uris.patch_value = map->map(map->handle, LV2_PATCH__value);
uris.units_frame = map->map(map->handle, LV2_UNITS__frame);
uris.state_StateChanged = map->map(map->handle, LV2_STATE__StateChanged);
uris.model_Path = map->map(map->handle, MODEL_URI);
if (options != nullptr)
options_set(this, options);
return true;
}
// runs on non-RT, can block or use [de]allocations
LV2_Worker_Status Plugin::work(LV2_Handle instance, LV2_Worker_Respond_Function respond, LV2_Worker_Respond_Handle handle,
uint32_t size, const void* data)
{
switch (*((const uint32_t*)data))
switch (*(const LV2WorkType*)data)
{
case kWorkTypeLoad:
auto msg = reinterpret_cast<const LV2LoadModelMsg*>(data);
{
auto msg = static_cast<const LV2LoadModelMsg*>(data);
auto nam = static_cast<NAM::Plugin*>(instance);
try
{
// If we had a previous model, delete it
if (nam->deleteModel)
{
nam->deleteModel.reset();
}
// load model from path
const size_t pathlen = strlen(msg->path);
::DSP* model;
if (strlen(msg->path) == 0)
{
if (pathlen == 0 || pathlen >= MAX_FILE_NAME)
{
// avoid logging an error on an empty path.
// but do clear the model.
nam->stagedModel = nullptr;
nam->stagedModelPath = msg->path;
} else
model = nullptr;
}
else
{
lv2_log_trace(&nam->logger, "Staging model change: `%s`\n", msg->path);
nam->stagedModel = get_dsp(msg->path);
nam->stagedModelPath = msg->path;
model = get_dsp(msg->path).release();
// Enable model loudness normalization
nam->stagedModel->SetNormalize(true);
model->SetNormalize(true);
// Pre-run model to ensure all needed buffers are allocated in advance
if (const int32_t numSamples = nam->maxBufferSize)
{
float* buffer = new float[numSamples];
std::unordered_map<std::string, double> params = {};
model->process(&buffer, &buffer, 1, numSamples, 1.0, 1.0, params);
model->finalize_(numSamples);
delete[] buffer;
}
}
LV2WorkType response = kWorkTypeSwitch;
LV2SwitchModelMsg response = { kWorkTypeSwitch, {}, model };
memcpy(response.path, msg->path, pathlen);
respond(handle, sizeof(response), &response);
return LV2_WORKER_SUCCESS;
@@ -111,80 +131,81 @@ namespace NAM {
}
break;
}
}
return LV2_WORKER_ERR_UNKNOWN;
}
LV2_Worker_Status Plugin::work_response(LV2_Handle instance, uint32_t size, const void* data)
{
switch (*((const uint32_t*)data))
{
case kWorkTypeSwitch:
try
case kWorkTypeFree:
{
auto nam = static_cast<NAM::Plugin*>(instance);
std::swap(nam->currentModel, nam->stagedModel);
nam->currentModelPath = nam->stagedModelPath;
assert(nam->currentModelPath.capacity() >= MAX_FILE_NAME + 1);
nam->stateChanged = true;
nam->deleteModel = std::move(nam->stagedModel);
nam->write_set_patch(nam->currentModelPath);
auto msg = static_cast<const LV2FreeModelMsg*>(data);
delete msg->model;
return LV2_WORKER_SUCCESS;
}
catch (std::exception& e)
{
}
break;
case kWorkTypeSwitch:
// should not happen!
break;
}
return LV2_WORKER_ERR_UNKNOWN;
}
// runs on RT, right after process(), must not block or [de]allocate memory
LV2_Worker_Status Plugin::work_response(LV2_Handle instance, uint32_t size, const void* data)
{
if (*(const LV2WorkType*)data != kWorkTypeSwitch)
return LV2_WORKER_ERR_UNKNOWN;
auto msg = static_cast<const LV2SwitchModelMsg*>(data);
auto nam = static_cast<NAM::Plugin*>(instance);
// prepare reply for deleting old model
LV2FreeModelMsg reply = { kWorkTypeFree, nam->currentModel };
// swap current model with new one
nam->currentModel = msg->model;
nam->currentModelPath = msg->path;
assert(nam->currentModelPath.capacity() >= MAX_FILE_NAME + 1);
// send reply
nam->schedule->schedule_work(nam->schedule->handle, sizeof(reply), &reply);
// report change to host/ui
nam->write_current_path();
return LV2_WORKER_SUCCESS;
}
void Plugin::process(uint32_t n_samples) noexcept
{
lv2_atom_forge_set_buffer(&atom_forge,(uint8_t*)ports.notify,ports.notify->atom.size);
lv2_atom_forge_sequence_head(&atom_forge,&sequence_frame,uris.units_frame);
lv2_atom_forge_set_buffer(&atom_forge, (uint8_t*)ports.notify, ports.notify->atom.size);
lv2_atom_forge_sequence_head(&atom_forge, &sequence_frame, uris.units_frame);
LV2_ATOM_SEQUENCE_FOREACH(ports.control, event)
{
if (event->body.type == uris.atom_Object)
{
const auto obj = reinterpret_cast<LV2_Atom_Object*>(&event->body);
if (obj->body.otype == uris.patch_Get) {
lv2_atom_forge_frame_time(&atom_forge, 0);
write_set_patch(currentModelPath);
if (obj->body.otype == uris.patch_Get)
{
write_current_path();
}
if (obj->body.otype == uris.patch_Set)
else if (obj->body.otype == uris.patch_Set)
{
const LV2_Atom* property = NULL;
const LV2_Atom* file_path = NULL;
lv2_atom_object_get(obj, uris.patch_property, &property, 0);
lv2_atom_object_get(obj,
uris.patch_property, &property,
uris.patch_value, &file_path,
0);
if (property && (property->type == uris.atom_URID))
if (property && property->type == uris.atom_URID &&
((const LV2_Atom_URID*)property)->body == uris.model_Path &&
file_path && file_path->type == uris.atom_Path &&
file_path->size > 0 && file_path->size < MAX_FILE_NAME)
{
if (((const LV2_Atom_URID*)property)->body == uris.model_Path)
{
lv2_atom_object_get(obj, uris.patch_value, &file_path, 0);
if (file_path && (file_path->size > 0) && (file_path->size < 1024))
{
LV2LoadModelMsg msg = { kWorkTypeLoad, {} };
memcpy(msg.path, (const char*)LV2_ATOM_BODY_CONST(file_path), file_path->size);
schedule->schedule_work(schedule->handle, sizeof(msg), &msg);
}
}
LV2LoadModelMsg msg = { kWorkTypeLoad, {} };
memcpy(msg.path, file_path + 1, file_path->size);
schedule->schedule_work(schedule->handle, sizeof(msg), &msg);
}
}
}
@@ -213,10 +234,7 @@ namespace NAM {
}
}
if (currentModel == nullptr)
{
}
else
if (currentModel != nullptr)
{
currentModel->process(&ports.audio_out, &ports.audio_out, 1, n_samples, 1.0, 1.0, mNAMParams);
currentModel->finalize_(n_samples);
@@ -244,15 +262,28 @@ namespace NAM {
ports.audio_out[i] *= outputLevel;
}
}
}
if (stateChanged)
uint32_t Plugin::options_get(LV2_Handle, LV2_Options_Option*)
{
// currently unused
return LV2_OPTIONS_ERR_UNKNOWN;
}
uint32_t Plugin::options_set(LV2_Handle instance, const LV2_Options_Option* options)
{
auto nam = static_cast<NAM::Plugin*>(instance);
for (int i=0; options[i].key && options[i].type; ++i)
{
stateChanged = false;
lv2_atom_forge_frame_time(&atom_forge, 0);
write_state_changed();
if (options[i].key == nam->uris.bufSize_maxBlockLength && options[i].type == nam->uris.atom_Int)
{
nam->maxBufferSize = *(const int32_t*)options[i].value;
break;
}
}
lv2_atom_forge_pop(&atom_forge,&sequence_frame);
return LV2_OPTIONS_SUCCESS;
}
LV2_State_Status Plugin::save(LV2_Handle instance, LV2_State_Store_Function store, LV2_State_Handle handle,
@@ -289,7 +320,7 @@ namespace NAM {
}
else
{
#ifndef _WIN32 // Can't free library allocated memory on Windows
#ifndef _WIN32 // Can't free host-allocated memory on plugin side under Windows
free(apath);
#endif
}
@@ -338,7 +369,7 @@ namespace NAM {
LV2_State_Status result = LV2_STATE_SUCCESS;
if (pathLen < 1024)
if (pathLen < MAX_FILE_NAME)
{
// Schedule model to be loaded by the provided worker
NAM::LV2LoadModelMsg msg = { NAM::kWorkTypeLoad, {} };
@@ -348,7 +379,7 @@ namespace NAM {
}
else
{
lv2_log_error(&nam->logger, "Model path is too long (max 1024 chars)\n");
lv2_log_error(&nam->logger, "Model path is too long (max %u chars)\n", MAX_FILE_NAME);
result = LV2_STATE_ERR_UNKNOWN;
}
@@ -361,7 +392,7 @@ namespace NAM {
}
else
{
#ifndef _WIN32 // Can't free library allocated memory on Windows
#ifndef _WIN32 // Can't free host-allocated memory on plugin side under Windows
free(path);
#endif
}
@@ -369,27 +400,18 @@ namespace NAM {
return result;
}
void Plugin::write_set_patch( std::string filename)
void Plugin::write_current_path()
{
LV2_Atom_Forge_Frame frame;
lv2_atom_forge_frame_time(&atom_forge, 0);
lv2_atom_forge_object(&atom_forge, &frame, 0, uris.patch_Set);
lv2_atom_forge_key(&atom_forge, uris.patch_property);
lv2_atom_forge_urid(&atom_forge, uris.model_Path);
lv2_atom_forge_key(&atom_forge, uris.patch_value);
lv2_atom_forge_path(&atom_forge, filename.c_str(), filename.length());
lv2_atom_forge_path(&atom_forge, currentModelPath.c_str(), currentModelPath.length() + 1);
lv2_atom_forge_pop(&atom_forge, &frame);
}
void Plugin::write_state_changed()
{
LV2_Atom_Forge_Frame frame;
lv2_atom_forge_object(&atom_forge, &frame, 0, uris.state_StateChanged);
/* object with no properties */
lv2_atom_forge_pop(&atom_forge, &frame);
}
}
+29 -18
View File
@@ -14,6 +14,8 @@
#include <lv2/log/logger.h>
#include <lv2/urid/urid.h>
#include <lv2/atom/forge.h>
#include <lv2/buf-size/buf-size.h>
#include <lv2/options/options.h>
#include <lv2/patch/patch.h>
#include <lv2/worker/worker.h>
#include <lv2/state/state.h>
@@ -25,15 +27,28 @@
#define MODEL_URI PlUGIN_URI "#model"
namespace NAM {
static constexpr unsigned int MAX_FILE_NAME = 1024;
enum LV2WorkType {
kWorkTypeLoad,
kWorkTypeSwitch
kWorkTypeSwitch,
kWorkTypeFree
};
struct LV2LoadModelMsg {
LV2WorkType type;
char path[1024];
char path[MAX_FILE_NAME];
};
struct LV2SwitchModelMsg {
LV2WorkType type;
char path[MAX_FILE_NAME];
::DSP* model;
};
struct LV2FreeModelMsg {
LV2WorkType type;
::DSP* model;
};
class Plugin {
@@ -49,28 +64,25 @@ namespace NAM {
Ports ports = {};
LV2_URID_Map* map;
LV2_Log_Logger logger;
LV2_Worker_Schedule* schedule;
std::unique_ptr<::DSP> currentModel;
std::unique_ptr<::DSP> stagedModel;
std::unique_ptr<::DSP> deleteModel;
bool stateChanged = false;
LV2_URID_Map* map = nullptr;
LV2_Log_Logger logger = {};
LV2_Worker_Schedule* schedule = nullptr;
::DSP* currentModel = nullptr;
std::string currentModelPath;
std::string stagedModelPath;
std::unordered_map<std::string, double> mNAMParams = {};
Plugin();
~Plugin() = default;
~Plugin();
bool initialize(double rate, const LV2_Feature* const* features) noexcept;
void process(uint32_t n_samples) noexcept;
void write_set_patch(std::string filename);
void write_state_changed();
void write_current_path();
static uint32_t options_get(LV2_Handle instance, LV2_Options_Option* options);
static uint32_t options_set(LV2_Handle instance, const LV2_Options_Option* options);
static LV2_Worker_Status work(LV2_Handle instance, LV2_Worker_Respond_Function respond, LV2_Worker_Respond_Handle handle,
uint32_t size, const void* data);
@@ -82,19 +94,17 @@ namespace NAM {
const LV2_Feature* const* features);
private:
static constexpr size_t MAX_FILE_NAME = 1024;
struct URIs {
LV2_URID atom_Object;
LV2_URID atom_Float;
LV2_URID atom_Int;
LV2_URID atom_Path;
LV2_URID atom_URID;
LV2_URID bufSize_maxBlockLength;
LV2_URID patch_Set;
LV2_URID patch_Get;
LV2_URID patch_property;
LV2_URID patch_value;
LV2_URID state_StateChanged;
LV2_URID units_frame;
LV2_URID model_Path;
};
@@ -107,5 +117,6 @@ namespace NAM {
float m_rate;
float inputLevel = 0;
float outputLevel = 0;
int32_t maxBufferSize = 0;
};
}