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
+5 -3
View File
@@ -7,6 +7,7 @@
@prefix ui: <http://lv2plug.in/ns/extensions/ui#>. @prefix ui: <http://lv2plug.in/ns/extensions/ui#>.
@prefix units: <http://lv2plug.in/ns/extensions/units#>. @prefix units: <http://lv2plug.in/ns/extensions/units#>.
@prefix urid: <http://lv2plug.in/ns/ext/urid#>. @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 param: <http://lv2plug.in/ns/ext/parameters#>.
@prefix patch: <http://lv2plug.in/ns/ext/patch#>. @prefix patch: <http://lv2plug.in/ns/ext/patch#>.
@prefix state: <http://lv2plug.in/ns/ext/state#>. @prefix state: <http://lv2plug.in/ns/ext/state#>.
@@ -20,7 +21,7 @@
rdfs:range atom:Path. rdfs:range atom:Path.
<@NAM_LV2_ID@> <@NAM_LV2_ID@>
a lv2:Plugin, lv2:SimulatorPlugin; a lv2:Plugin, lv2:SimulatorPlugin, doap:Project;
doap:name "Neural Amp Modeler"; doap:name "Neural Amp Modeler";
lv2:project <@NAM_LV2_ID@>; lv2:project <@NAM_LV2_ID@>;
lv2:minorVersion @PROJECT_VERSION_MINOR@; lv2:minorVersion @PROJECT_VERSION_MINOR@;
@@ -33,8 +34,9 @@
]; ];
lv2:requiredFeature urid:map, work:schedule; lv2:requiredFeature urid:map, work:schedule;
lv2:optionalFeature lv2:hardRTCapable; lv2:optionalFeature lv2:hardRTCapable, opts:options, state:threadSafeRestore;
lv2:extensionData work:interface, state:interface; lv2:extensionData work:interface, state:interface, opts:interface;
opts:supportedOption <http://lv2plug.in/ns/ext/buf-size#maxBlockLength>;
rdfs:comment """ rdfs:comment """
An LV2 implementation of Neural Amp Modeler. An LV2 implementation of Neural Amp Modeler.
+13 -5
View File
@@ -63,13 +63,14 @@ static void cleanup(LV2_Handle instance)
static const void* extension_data(const char* uri) static const void* extension_data(const char* uri)
{ {
static const LV2_State_Interface state = {NAM::Plugin::save, NAM::Plugin::restore}; 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 }; 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; return &state;
}
if (!strcmp(uri, LV2_WORKER__interface)) if (!strcmp(uri, LV2_WORKER__interface))
return &worker; return &worker;
@@ -90,5 +91,12 @@ static const LV2_Descriptor descriptor =
LV2_SYMBOL_EXPORT const LV2_Descriptor* lv2_descriptor(uint32_t index) 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;
} }
+113 -91
View File
@@ -11,16 +11,19 @@
namespace NAM { namespace NAM {
Plugin::Plugin() Plugin::Plugin()
{ {
// Turn on fast tanh approximation
activations::Activation::enable_fast_tanh();
// prevent allocations on the audio thread // prevent allocations on the audio thread
currentModelPath.reserve(MAX_FILE_NAME+1); currentModelPath.reserve(MAX_FILE_NAME+1);
} }
Plugin::~Plugin()
{
delete currentModel;
}
bool Plugin::initialize(double rate, const LV2_Feature* const* features) noexcept 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) { for (size_t i = 0; features[i]; ++i) {
if (std::string(features[i]->URI) == std::string(LV2_URID__map)) 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); schedule = static_cast<LV2_Worker_Schedule*>(features[i]->data);
else if (std::string(features[i]->URI) == std::string(LV2_LOG__log)) else if (std::string(features[i]->URI) == std::string(LV2_LOG__log))
logger.log = static_cast<LV2_Log_Log*>(features[i]->data); 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); 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_Int = map->map(map->handle, LV2_ATOM__Int);
uris.atom_Path = map->map(map->handle, LV2_ATOM__Path); uris.atom_Path = map->map(map->handle, LV2_ATOM__Path);
uris.atom_URID = map->map(map->handle, LV2_ATOM__URID); 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_Set = map->map(map->handle, LV2_PATCH__Set);
uris.patch_Get = map->map(map->handle, LV2_PATCH__Get); uris.patch_Get = map->map(map->handle, LV2_PATCH__Get);
uris.patch_property = map->map(map->handle, LV2_PATCH__property); uris.patch_property = map->map(map->handle, LV2_PATCH__property);
uris.patch_value = map->map(map->handle, LV2_PATCH__value); uris.patch_value = map->map(map->handle, LV2_PATCH__value);
uris.units_frame = map->map(map->handle, LV2_UNITS__frame); 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); uris.model_Path = map->map(map->handle, MODEL_URI);
if (options != nullptr)
options_set(this, options);
return true; 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, LV2_Worker_Status Plugin::work(LV2_Handle instance, LV2_Worker_Respond_Function respond, LV2_Worker_Respond_Handle handle,
uint32_t size, const void* data) uint32_t size, const void* data)
{ {
switch (*((const uint32_t*)data)) switch (*(const LV2WorkType*)data)
{ {
case kWorkTypeLoad: case kWorkTypeLoad:
auto msg = reinterpret_cast<const LV2LoadModelMsg*>(data); {
auto msg = static_cast<const LV2LoadModelMsg*>(data);
auto nam = static_cast<NAM::Plugin*>(instance); auto nam = static_cast<NAM::Plugin*>(instance);
try try
{ {
// If we had a previous model, delete it // load model from path
if (nam->deleteModel) const size_t pathlen = strlen(msg->path);
{ ::DSP* model;
nam->deleteModel.reset();
}
if (strlen(msg->path) == 0) if (pathlen == 0 || pathlen >= MAX_FILE_NAME)
{ {
// avoid logging an error on an empty path. // avoid logging an error on an empty path.
// but do clear the model. // but do clear the model.
nam->stagedModel = nullptr; model = nullptr;
nam->stagedModelPath = msg->path; }
} else else
{ {
lv2_log_trace(&nam->logger, "Staging model change: `%s`\n", msg->path); lv2_log_trace(&nam->logger, "Staging model change: `%s`\n", msg->path);
nam->stagedModel = get_dsp(msg->path); model = get_dsp(msg->path).release();
nam->stagedModelPath = msg->path;
// Enable model loudness normalization // 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); respond(handle, sizeof(response), &response);
return LV2_WORKER_SUCCESS; return LV2_WORKER_SUCCESS;
@@ -113,82 +133,83 @@ namespace NAM {
break; break;
} }
return LV2_WORKER_ERR_UNKNOWN; case kWorkTypeFree:
}
LV2_Worker_Status Plugin::work_response(LV2_Handle instance, uint32_t size, const void* data)
{ {
switch (*((const uint32_t*)data)) auto msg = static_cast<const LV2FreeModelMsg*>(data);
{ delete msg->model;
case kWorkTypeSwitch:
try
{
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);
return LV2_WORKER_SUCCESS; return LV2_WORKER_SUCCESS;
} }
catch (std::exception& e)
{
}
case kWorkTypeSwitch:
// should not happen!
break; break;
} }
return LV2_WORKER_ERR_UNKNOWN; 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 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_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_sequence_head(&atom_forge, &sequence_frame, uris.units_frame);
LV2_ATOM_SEQUENCE_FOREACH(ports.control, event) LV2_ATOM_SEQUENCE_FOREACH(ports.control, event)
{ {
if (event->body.type == uris.atom_Object) if (event->body.type == uris.atom_Object)
{ {
const auto obj = reinterpret_cast<LV2_Atom_Object*>(&event->body); const auto obj = reinterpret_cast<LV2_Atom_Object*>(&event->body);
if (obj->body.otype == uris.patch_Get) { if (obj->body.otype == uris.patch_Get)
lv2_atom_forge_frame_time(&atom_forge, 0); {
write_set_patch(currentModelPath); write_current_path();
} }
else if (obj->body.otype == uris.patch_Set)
if (obj->body.otype == uris.patch_Set)
{ {
const LV2_Atom* property = NULL; const LV2_Atom* property = NULL;
const LV2_Atom* file_path = 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 &&
if (((const LV2_Atom_URID*)property)->body == uris.model_Path) file_path->size > 0 && file_path->size < MAX_FILE_NAME)
{
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, {} }; LV2LoadModelMsg msg = { kWorkTypeLoad, {} };
memcpy(msg.path, file_path + 1, file_path->size);
memcpy(msg.path, (const char*)LV2_ATOM_BODY_CONST(file_path), file_path->size);
schedule->schedule_work(schedule->handle, sizeof(msg), &msg); schedule->schedule_work(schedule->handle, sizeof(msg), &msg);
} }
} }
} }
} }
}
}
// convert input level from db // convert input level from db
float desiredInputLevel = powf(10, *(ports.input_level) * 0.05f); float desiredInputLevel = powf(10, *(ports.input_level) * 0.05f);
@@ -213,10 +234,7 @@ namespace NAM {
} }
} }
if (currentModel == nullptr) if (currentModel != nullptr)
{
}
else
{ {
currentModel->process(&ports.audio_out, &ports.audio_out, 1, n_samples, 1.0, 1.0, mNAMParams); currentModel->process(&ports.audio_out, &ports.audio_out, 1, n_samples, 1.0, 1.0, mNAMParams);
currentModel->finalize_(n_samples); currentModel->finalize_(n_samples);
@@ -244,15 +262,28 @@ namespace NAM {
ports.audio_out[i] *= outputLevel; ports.audio_out[i] *= outputLevel;
} }
} }
if (stateChanged)
{
stateChanged = false;
lv2_atom_forge_frame_time(&atom_forge, 0);
write_state_changed();
} }
lv2_atom_forge_pop(&atom_forge,&sequence_frame); 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)
{
if (options[i].key == nam->uris.bufSize_maxBlockLength && options[i].type == nam->uris.atom_Int)
{
nam->maxBufferSize = *(const int32_t*)options[i].value;
break;
}
}
return LV2_OPTIONS_SUCCESS;
} }
LV2_State_Status Plugin::save(LV2_Handle instance, LV2_State_Store_Function store, LV2_State_Handle handle, LV2_State_Status Plugin::save(LV2_Handle instance, LV2_State_Store_Function store, LV2_State_Handle handle,
@@ -289,7 +320,7 @@ namespace NAM {
} }
else 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); free(apath);
#endif #endif
} }
@@ -338,7 +369,7 @@ namespace NAM {
LV2_State_Status result = LV2_STATE_SUCCESS; LV2_State_Status result = LV2_STATE_SUCCESS;
if (pathLen < 1024) if (pathLen < MAX_FILE_NAME)
{ {
// Schedule model to be loaded by the provided worker // Schedule model to be loaded by the provided worker
NAM::LV2LoadModelMsg msg = { NAM::kWorkTypeLoad, {} }; NAM::LV2LoadModelMsg msg = { NAM::kWorkTypeLoad, {} };
@@ -348,7 +379,7 @@ namespace NAM {
} }
else 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; result = LV2_STATE_ERR_UNKNOWN;
} }
@@ -361,7 +392,7 @@ namespace NAM {
} }
else 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); free(path);
#endif #endif
} }
@@ -369,27 +400,18 @@ namespace NAM {
return result; return result;
} }
void Plugin::write_set_patch( std::string filename) void Plugin::write_current_path()
{ {
LV2_Atom_Forge_Frame frame; 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_object(&atom_forge, &frame, 0, uris.patch_Set);
lv2_atom_forge_key(&atom_forge, uris.patch_property); lv2_atom_forge_key(&atom_forge, uris.patch_property);
lv2_atom_forge_urid(&atom_forge, uris.model_Path); lv2_atom_forge_urid(&atom_forge, uris.model_Path);
lv2_atom_forge_key(&atom_forge, uris.patch_value); 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); 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);
}
} }
+28 -17
View File
@@ -14,6 +14,8 @@
#include <lv2/log/logger.h> #include <lv2/log/logger.h>
#include <lv2/urid/urid.h> #include <lv2/urid/urid.h>
#include <lv2/atom/forge.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/patch/patch.h>
#include <lv2/worker/worker.h> #include <lv2/worker/worker.h>
#include <lv2/state/state.h> #include <lv2/state/state.h>
@@ -25,15 +27,28 @@
#define MODEL_URI PlUGIN_URI "#model" #define MODEL_URI PlUGIN_URI "#model"
namespace NAM { namespace NAM {
static constexpr unsigned int MAX_FILE_NAME = 1024;
enum LV2WorkType { enum LV2WorkType {
kWorkTypeLoad, kWorkTypeLoad,
kWorkTypeSwitch kWorkTypeSwitch,
kWorkTypeFree
}; };
struct LV2LoadModelMsg { struct LV2LoadModelMsg {
LV2WorkType type; 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 { class Plugin {
@@ -49,28 +64,25 @@ namespace NAM {
Ports ports = {}; Ports ports = {};
LV2_URID_Map* map; LV2_URID_Map* map = nullptr;
LV2_Log_Logger logger; LV2_Log_Logger logger = {};
LV2_Worker_Schedule* schedule; LV2_Worker_Schedule* schedule = nullptr;
std::unique_ptr<::DSP> currentModel;
std::unique_ptr<::DSP> stagedModel;
std::unique_ptr<::DSP> deleteModel;
bool stateChanged = false;
::DSP* currentModel = nullptr;
std::string currentModelPath; std::string currentModelPath;
std::string stagedModelPath;
std::unordered_map<std::string, double> mNAMParams = {}; std::unordered_map<std::string, double> mNAMParams = {};
Plugin(); Plugin();
~Plugin() = default; ~Plugin();
bool initialize(double rate, const LV2_Feature* const* features) noexcept; bool initialize(double rate, const LV2_Feature* const* features) noexcept;
void process(uint32_t n_samples) noexcept; void process(uint32_t n_samples) noexcept;
void write_set_patch(std::string filename); void write_current_path();
void write_state_changed();
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, static LV2_Worker_Status work(LV2_Handle instance, LV2_Worker_Respond_Function respond, LV2_Worker_Respond_Handle handle,
uint32_t size, const void* data); uint32_t size, const void* data);
@@ -82,19 +94,17 @@ namespace NAM {
const LV2_Feature* const* features); const LV2_Feature* const* features);
private: private:
static constexpr size_t MAX_FILE_NAME = 1024;
struct URIs { struct URIs {
LV2_URID atom_Object; LV2_URID atom_Object;
LV2_URID atom_Float; LV2_URID atom_Float;
LV2_URID atom_Int; LV2_URID atom_Int;
LV2_URID atom_Path; LV2_URID atom_Path;
LV2_URID atom_URID; LV2_URID atom_URID;
LV2_URID bufSize_maxBlockLength;
LV2_URID patch_Set; LV2_URID patch_Set;
LV2_URID patch_Get; LV2_URID patch_Get;
LV2_URID patch_property; LV2_URID patch_property;
LV2_URID patch_value; LV2_URID patch_value;
LV2_URID state_StateChanged;
LV2_URID units_frame; LV2_URID units_frame;
LV2_URID model_Path; LV2_URID model_Path;
}; };
@@ -107,5 +117,6 @@ namespace NAM {
float m_rate; float m_rate;
float inputLevel = 0; float inputLevel = 0;
float outputLevel = 0; float outputLevel = 0;
int32_t maxBufferSize = 0;
}; };
} }