Filter.cpp 10.2 KB
Newer Older
1
/**********
2
 * Copyright (c) 2022, Coriander Violet Pines. All rights reserved.
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
 * This file is part of Substation by Slime Child Audio and is governed by the attached license.
 *
 * Author: C. V. Pines
 */

#include "_plugin.hpp"

#include "FilterExpanderData.hpp"
#include "Settings.hpp"

#include <algorithm>
#include <array>

#include <slime/Math.hpp>
#include <slime/app/ModulePanel.hpp>
#include <slime/dsp/LadderFilter.hpp>
#include <slime/engine/Expanders.hpp>
#include <slime/skin/Ersatz.hpp>
#include <slime/ui/UI.hpp>

#include <dsp/approx.hpp>
#include <dsp/digital.hpp>
#include <math.hpp>
#include <random.hpp>
#include <simd/Vector.hpp>
#include <simd/functions.hpp>

namespace slime {
namespace plugin {
namespace substation {

typedef engine::ExpandableModule<detail::FilterToExpanderData, detail::ExpanderToFilterData> Base;

struct FilterModule : Base {
	enum class QualityLevel : std::size_t { LOW, MEDIUM, HIGH };

	// Mutable config
	std::shared_ptr<QualityLevel> quality_level;

	// Internal state
	std::array<slime::dsp::FourPoleLadderLowpass<math::float_simd>, math::SIMD_PAR> filters;
	std::array<math::float_simd, math::SIMD_PAR> frequency;
	rack::dsp::ClockDivider param_divider, light_divider, expander_divider;
	bool use_left, use_right;

	enum ParamIds { FREQ_PARAM, RES_PARAM, FM_AMOUNT_PARAM, NUM_PARAMS };

	enum InputIds { FREQ_INPUT, FM_INPUT, SIGNAL_INPUT, NUM_INPUTS };

	enum OutputIds { SIGNAL_OUTPUT, NUM_OUTPUTS };

	enum LightIds { LEFT_EXPANDER_LIGHT, RIGHT_EXPANDER_LIGHT, NUM_LIGHTS };

	FilterModule(void) : Base() {
		config(NUM_PARAMS, NUM_INPUTS, NUM_OUTPUTS, NUM_LIGHTS);

		configInput(FREQ_INPUT, "Cutoff");
		configInput(FM_INPUT, "FM");
		configInput(SIGNAL_INPUT, "Signal");
		configOutput(SIGNAL_OUTPUT, "Signal");
		configBypass(SIGNAL_INPUT, SIGNAL_OUTPUT);

		// 20 Hz to 20000 Hz
		configParam(FREQ_PARAM, 0.0f, slime::math::LOG_2_10 * 3.0f, slime::math::LOG_2_10 * 1.5f, "Frequency", " Hz",
					2.0f, 20.0f);
		configParam(RES_PARAM, 0.0f, 1.2f, 0.0f, "Resonance", "%", 0.0f, 100.0f);
		configParam(FM_AMOUNT_PARAM, -1.0f, 1.0f, 0.0f, "FM Amount", "%", 0.0f, 100.0f);

		param_divider.setDivision(8);  // Min 5512 Hz
		light_divider.setDivision(512);
		expander_divider.setDivision(8192);

		use_left = false;
		use_right = false;

		quality_level = std::make_shared<QualityLevel>(QualityLevel::LOW);
		setQuality(*quality_level);
	}

	void onReset(void) override {
		for (auto& filter : filters) {
			filter.reset();
		}

		param_divider.reset();
		frequency.fill(20.0f * rack::dsp::approxExp2_taylor5<math::float_simd>(slime::math::LOG_2_10 * 1.5f));

		*quality_level = QualityLevel::LOW;
		setQuality(QualityLevel::LOW);
	}

	// Serialize state not captured by params
	json_t* dataToJson() override {
		json_t* root = json_object();

		// Quality level
		json_object_set_new(root, "quality_level", json_integer(static_cast<std::size_t>(*quality_level)));

		return root;
	}

	// Deserialize state not captured by params
	void dataFromJson(json_t* root) override {
		// Quality level
		json_t* quality_level_json = json_object_get(root, "quality_level");
		if (quality_level_json) {
			*quality_level = static_cast<QualityLevel>(json_integer_value(quality_level_json));
			setQuality(*quality_level);
		}
	}

	void process(const ProcessArgs& args) override {
		// Update when expanders change
		if (updateExpanders()) {
			use_left = hasLeftExpander() && fromLeftExpander()->connected_to_right;
			use_right = hasRightExpander() && fromRightExpander()->connected_to_left;
		}

		// Also update periodically, since connection info is delayed
		if (expander_divider.process()) {
			use_left = hasLeftExpander() && fromLeftExpander()->connected_to_right;
			use_right = hasRightExpander() && fromRightExpander()->connected_to_left;
		}

		size_t channels = std::max(std::max(inputs[SIGNAL_INPUT].getChannels(), inputs[FREQ_INPUT].getChannels()),
								   inputs[FM_INPUT].getChannels());
		if (channels < 1) {
			channels = 1;
		}

		outputs[SIGNAL_OUTPUT].setChannels(channels);

		// Update params
		if (param_divider.process()) {
			math::float_simd base_res = params[RES_PARAM].getValue();

			for (size_t ch = 0; ch < channels; ch += math::float_simd::size) {
				size_t simd_index = ch / math::float_simd::size;

				auto* filter = &filters[simd_index];

				math::float_simd pitch = rack::simd::clamp(
					params[FREQ_PARAM].getValue() + inputs[FREQ_INPUT].getPolyVoltageSimd<math::float_simd>(ch) +
						params[FM_AMOUNT_PARAM].getValue() * inputs[FM_INPUT].getPolyVoltageSimd<math::float_simd>(ch),
					0.0f, slime::math::LOG_2_10 * 3.0f);
				math::float_simd freq = 20.0f * rack::dsp::approxExp2_taylor5<math::float_simd>(pitch);

				// Resonance from expander
				math::float_simd res = base_res;

				if (use_left) {
					res += fromLeftExpander()->resonance_offset[simd_index];
				}

				if (use_right) {
					res += fromRightExpander()->resonance_offset[simd_index];
				}

				res = rack::simd::clamp(res, 0.0f, 1.2f);

				filter->setCutoffFrequency(freq);
				filter->setResonance(res);
			}
		}

		// To expanders
		toLeftExpander()->channels = channels;
		toRightExpander()->channels = channels;

		// Run filter
		for (size_t ch = 0; ch < channels; ch += math::float_simd::size) {
			size_t simd_index = ch / math::float_simd::size;
			auto* filter = &filters[simd_index];

			math::float_simd in = inputs[SIGNAL_INPUT].getPolyVoltageSimd<math::float_simd>(ch);
			in += 1e-6f * (2.0f * rack::random::uniform() - 1.0f);
			filter->process(args.sampleTime, in);

			outputs[SIGNAL_OUTPUT].setVoltageSimd(filter->lowpass4(), ch);

			// To expanders
			if (use_left) {
				auto* expander = toLeftExpander();
				expander->lowpass2[simd_index] = filter->lowpass2();
				expander->bandpass2[simd_index] = filter->bandpass2();
				expander->bandpass4[simd_index] = filter->bandpass4();
			}

			if (use_right) {
				auto* expander = toRightExpander();
				expander->lowpass2[simd_index] = filter->lowpass2();
				expander->bandpass2[simd_index] = filter->bandpass2();
				expander->bandpass4[simd_index] = filter->bandpass4();
			}
		}

		// Lights
		if (light_divider.process()) {
			lights[LEFT_EXPANDER_LIGHT].setSmoothBrightness(
				use_left ? 1.0f : 0.0f, args.sampleTime * light_divider.division * settings.light_trigger_fade);
			lights[RIGHT_EXPANDER_LIGHT].setSmoothBrightness(
				use_right ? 1.0f : 0.0f, args.sampleTime * light_divider.division * settings.light_trigger_fade);
		}

		sendExpanderMessages();
	}

	void setQuality(QualityLevel level) {
		std::size_t filter_quality;
		std::size_t param_division;

		switch (level) {
			default:
			case QualityLevel::LOW:
				filter_quality = 6;
				param_division = 8;
				break;

			case QualityLevel::MEDIUM:
				filter_quality = 9;
				param_division = 3;
				break;

			case QualityLevel::HIGH:
				filter_quality = 12;
				param_division = 1;
				break;
		}

		param_divider.setDivision(param_division);
		for (auto& filter : filters) {
			filter.setOversample(filter_quality);
		}
	}

	inline bool matchLeftSlug(const std::string& value) override { return value == modelFilterPlus->slug; }
	inline bool matchRightSlug(const std::string& value) override { return value == modelFilterPlus->slug; }
};

struct FilterWidget : rack::app::ModuleWidget {
	FilterWidget(FilterModule* module) {
		setModule(module);

		// Panel
		app::ModulePanel::makePanel(7ull)
			->addImageBackground(rack::asset::plugin(pluginInstance, "res/Filter_400z.png"))
			->addSvgBackground(rack::asset::plugin(pluginInstance, "res/Filter_Text.svg"))
			->attach(this);

		using namespace skin::ersatz;

		// Test build warning
#if defined(SLIME_DEBUG)
		TestBuildWarning::makeComponent()->attach(this);
#endif

		// Logo
		BrandLogo::makeComponent(BrandLogo::Size::FULL)->attach(this);

		// Inputs
		rack::math::Vec inputs[] = {{10.16f, 90.17f}, {25.4f, 90.17f}, {10.16f, 106.69f}};
		for (size_t i = 0; i < FilterModule::NUM_INPUTS; i++) {
			Port::makeComponent()
				->setPositionMm(inputs[i])
				->center()
				->setInput()
				->setCustomColors(settings.cable_colors)
				->attach(module, i, this);
		}

		// Outputs
		Port::makeComponent()
			->setPositionMm(25.4f, 106.69f)
			->center()
			->setOutput()
			->setCustomColors(settings.cable_colors)
			->attach(module, FilterModule::SIGNAL_OUTPUT, this);

		// Knobs
		Knob::makeComponent(Knob::Size::BIG)
			->setPositionMm(17.68f, 27.94f)
			->center()
			->attach(module, FilterModule::FREQ_PARAM, this);

		rack::math::Vec knobs[] = {{10.16f, 54.62f}, {25.4f, 54.62f}};
		for (size_t i = FilterModule::RES_PARAM; i < FilterModule::NUM_PARAMS; i++) {
			Knob::makeComponent(Knob::Size::MEDIUM)
				->setPositionMm(knobs[i - FilterModule::RES_PARAM])
				->center()
				->attach(module, i, this);
		}

		// Lights
		rack::math::Vec lights[] = {{0.4f, 3.05f}, {1.0f, 3.05f}};
		for (size_t i = 0; i < FilterModule::NUM_LIGHTS; i++) {
			MonochromeLED::makeComponent(MonochromeLED::Size::SMALL, MonochromeLED::Color::MINT)
				->setPositionIn(lights[i])
				->center()
				->attach(module, i, this);
		}
	}

	void appendContextMenu(rack::ui::Menu* menu) override {
		menu->addChild(new rack::ui::MenuSeparator);

		rack::ui::MenuLabel* modelLabel = new rack::ui::MenuLabel;
		modelLabel->text = "Module Settings";
		menu->addChild(modelLabel);

		auto* pmodule = dynamic_cast<FilterModule*>(module);
		if (!pmodule) {
			FATAL("Module was not set when appending context menu; cannot bind callbacks.");
			return;
		}

		{  // Quality
			auto quality = new slime::ui::MapChoiceMenuItem<FilterModule::QualityLevel>(
				pmodule->quality_level, {{FilterModule::QualityLevel::LOW, "Default"},
										 {FilterModule::QualityLevel::MEDIUM, "High"},
										 {FilterModule::QualityLevel::HIGH, "Extreme"}});
			quality->text = "Quality";
			quality->getInvoker() += std::bind(&FilterModule::setQuality, pmodule, std::placeholders::_1);
			menu->addChild(quality);
		}

		{  // Add expander
			auto item = new slime::ui::ModuleInstantionMenuItem;
			item->text = "Add expander (right, 4HP)";
			item->module_widget = this;
			item->model = modelFilterPlus;
			menu->addChild(item);
		}

		settings.appendContextMenu(menu);
	}
};

rack::plugin::Model* modelFilter = rack::createModel<FilterModule, FilterWidget>("SlimeChild-Substation-OpenSource-Filter");

}  // namespace substation
}  // namespace plugin
}  // namespace slime