MayaFlux 1.0.0
Digital-First Multimedia Processing Framework
Loading...
Searching...
No Matches
DuctNetwork.cpp
Go to the documentation of this file.
1#include "DuctNetwork.hpp"
2
5
7
8namespace Acoustics = Kinesis::Acoustics;
9
10namespace {
11
12 constexpr uint8_t k_empty = 0;
13 constexpr uint8_t k_ready = 1;
14 constexpr uint8_t k_busy = 2;
15 constexpr uint8_t k_retired = 3;
16
17}
18
20 Acoustics::DuctGrid grid;
21 Acoustics::DuctSpec spec;
22 Acoustics::DuctLoss loss;
23 double friction {};
24 double viscosity {};
25 std::vector<double> pressure;
26 std::vector<double> velocity;
27 bool keep_state { false };
28 std::shared_ptr<TerminationOperator> mouth;
29 std::shared_ptr<TerminationOperator> bell;
30};
31
32//-----------------------------------------------------------------------------
33// Construction
34//-----------------------------------------------------------------------------
35
36DuctNetwork::DuctNetwork(double length, double radius, double sample_rate)
37 : DuctNetwork(length, std::vector<double> { radius, radius }, sample_rate)
38{
39}
40
41DuctNetwork::DuctNetwork(double length, const std::vector<double>& radii, double sample_rate)
43{
44 setup(length, Profile { .radii = radii, .function = {} }, sample_rate);
45}
46
47DuctNetwork::DuctNetwork(double length, std::function<double(double)> radius, double sample_rate)
49{
50 setup(length, Profile { .radii = {}, .function = std::move(radius) }, sample_rate);
51}
52
54
55void DuctNetwork::setup(double length, Profile profile, double sample_rate)
56{
57 m_sample_rate = static_cast<uint32_t>(sample_rate);
60
61 std::scoped_lock lock(m_producer_mutex);
62 m_length = length;
63 m_rate = sample_rate;
64 m_profile = std::move(profile);
65 m_mouth = std::make_shared<ReedOperator>();
66 m_bell = std::make_shared<RadiationOperator>();
67
70
71 if (auto prepared = build(m_length, m_profile, m_losses, m_mouth_volume, m_mouth, m_bell)) {
72 m_applied_friction = prepared->friction;
73 m_applied_viscosity = prepared->viscosity;
74 m_intervals = prepared->grid.intervals;
75 m_courant = prepared->grid.courant;
76 m_bandwidth = prepared->grid.bandwidth;
77 m_field_points.store(prepared->grid.intervals + 1, std::memory_order_relaxed);
78 m_field.reserve(prepared->grid.intervals + 1);
79 m_active = std::move(prepared);
80 }
81}
82
83//-----------------------------------------------------------------------------
84// Building and installing grids
85//-----------------------------------------------------------------------------
86
87std::shared_ptr<DuctNetwork::Prepared> DuctNetwork::build(
88 double length,
89 const Profile& profile,
90 const Losses& losses,
91 double mouth_volume,
92 const std::shared_ptr<TerminationOperator>& mouth,
93 const std::shared_ptr<TerminationOperator>& bell) const
94{
95 const Acoustics::DuctSpec spec { .length = length, .sample_rate = m_rate, .mouth_volume = mouth_volume };
96
97 std::expected<Acoustics::DuctGrid, Acoustics::DuctError> grid = std::unexpected(Acoustics::DuctError::INVALID_PROFILE);
98 if (!profile.radii.empty()) {
99 grid = Acoustics::make_duct_grid(spec, profile.radii);
100 } else if (profile.function) {
101 grid = Acoustics::make_duct_grid(spec, profile.function);
102 }
103
104 if (!grid) {
106 "DuctNetwork could not build a grid: {}", Reflect::enum_to_string(grid.error()));
107 return nullptr;
108 }
109
110 if (!mouth || !bell
111 || !mouth->accepts(*grid, spec, DuctEnd::MOUTH)
112 || !bell->accepts(*grid, spec, DuctEnd::BELL)) {
114 "DuctNetwork terminations cannot terminate the {} interval duct", grid->intervals);
115 return nullptr;
116 }
117
118 auto prepared = std::make_shared<Prepared>();
119 prepared->spec = spec;
120 prepared->pressure.assign(grid->intervals + 1, 0.0);
121 prepared->velocity.assign(grid->intervals, 0.0);
122 prepared->grid = std::move(*grid);
123 prepared->mouth = mouth;
124 prepared->bell = bell;
125
126 prepared->friction = losses.friction;
127 prepared->viscosity = losses.viscosity;
128 if (losses.automatic) {
129 const auto& areas = prepared->grid.area;
130 const double mean_area = std::accumulate(areas.begin(), areas.end(), 0.0) / static_cast<double>(areas.size());
131 std::tie(prepared->friction, prepared->viscosity) = Acoustics::viscothermal_rates(
132 std::sqrt(mean_area / std::numbers::pi), spec.sound_speed, spec.air_density);
133 }
134
135 if (!prepared->loss.configure(prepared->grid, prepared->friction, prepared->viscosity)) {
137 "DuctNetwork wall losses of {} and {} cannot be applied", prepared->friction, prepared->viscosity);
138 return nullptr;
139 }
140
141 return prepared;
142}
143
144void DuctNetwork::publish(std::shared_ptr<Prepared> next)
145{
146 m_intervals = next->grid.intervals;
147 m_courant = next->grid.courant;
148 m_bandwidth = next->grid.bandwidth;
149 m_applied_friction = next->friction;
150 m_applied_viscosity = next->viscosity;
151
152 while (m_audio_buffer_lock.test_and_set(std::memory_order_acquire)) {
153 std::this_thread::yield();
154 }
155 m_field.reserve(next->grid.intervals + 1);
156 m_audio_buffer_lock.clear(std::memory_order_release);
157
158 for (;;) {
159 uint8_t state = m_handoff.load(std::memory_order_acquire);
160
161 if (state == k_retired) {
162 m_slot.reset();
163 m_handoff.store(k_empty, std::memory_order_release);
164 } else if (state == k_ready) {
165 if (m_handoff.compare_exchange_strong(state, k_busy, std::memory_order_acq_rel)) {
166 next->keep_state = next->keep_state && m_slot->keep_state;
167 m_slot = std::move(next);
168 m_handoff.store(k_ready, std::memory_order_release);
169 return;
170 }
171 } else if (state == k_busy) {
172 std::this_thread::yield();
173 } else {
174 m_slot = std::move(next);
175 m_handoff.store(k_ready, std::memory_order_release);
176 return;
177 }
178 }
179}
180
182{
183 uint8_t expected = k_ready;
184 if (!m_handoff.compare_exchange_strong(expected, k_busy, std::memory_order_acq_rel)) {
185 return;
186 }
187
188 std::swap(m_active, m_slot);
189 m_handoff.store(k_retired, std::memory_order_release);
190
191 const bool carry = m_active->keep_state && m_slot && !m_slot->pressure.empty();
192 if (carry) {
193 Acoustics::resample_line(m_slot->pressure, m_active->pressure, 0.0);
194 Acoustics::resample_line(m_slot->velocity, m_active->velocity, 0.5);
195 }
196 bind(*m_active, carry);
197}
198
199void DuctNetwork::bind(Prepared& prepared, bool keep)
200{
201 if (keep) {
202 prepared.mouth->retarget(prepared.grid, prepared.spec, DuctEnd::MOUTH);
203 prepared.bell->retarget(prepared.grid, prepared.spec, DuctEnd::BELL);
204 } else {
205 prepared.mouth->prepare(prepared.grid, prepared.spec, DuctEnd::MOUTH);
206 prepared.bell->prepare(prepared.grid, prepared.spec, DuctEnd::BELL);
207 m_previous_outflow = 0.0;
208 }
209 m_field_points.store(prepared.grid.intervals + 1, std::memory_order_relaxed);
210}
211
213{
214 if (m_active) {
215 bind(*m_active, false);
216 }
217}
218
220{
221 std::scoped_lock lock(m_producer_mutex);
223 publish(std::move(next));
224 }
225}
226
227//-----------------------------------------------------------------------------
228// Shape and terminations
229//-----------------------------------------------------------------------------
230
231bool DuctNetwork::set_length(double length)
232{
233 std::scoped_lock lock(m_producer_mutex);
234 auto next = build(length, m_profile, m_losses, m_mouth_volume, m_mouth, m_bell);
235 if (!next) {
236 return false;
237 }
238
239 next->keep_state = true;
240
241 m_length = length;
242 publish(std::move(next));
243 return true;
244}
245
246bool DuctNetwork::set_radius(double radius)
247{
248 return set_profile(std::vector<double> { radius, radius });
249}
250
251bool DuctNetwork::set_profile(const std::vector<double>& radii)
252{
253 std::scoped_lock lock(m_producer_mutex);
254 Profile profile { .radii = radii, .function = {} };
255 auto next = build(m_length, profile, m_losses, m_mouth_volume, m_mouth, m_bell);
256 if (!next) {
257 return false;
258 }
259
260 next->keep_state = true;
261
262 m_profile = std::move(profile);
263 publish(std::move(next));
264 return true;
265}
266
267bool DuctNetwork::set_profile(std::function<double(double)> radius)
268{
269 std::scoped_lock lock(m_producer_mutex);
270 Profile profile { .radii = {}, .function = std::move(radius) };
271 auto next = build(m_length, profile, m_losses, m_mouth_volume, m_mouth, m_bell);
272 if (!next) {
273 return false;
274 }
275
276 next->keep_state = true;
277
278 m_profile = std::move(profile);
279 publish(std::move(next));
280 return true;
281}
282
284{
285 std::scoped_lock lock(m_producer_mutex);
286 auto next = build(m_length, m_profile, m_losses, volume, m_mouth, m_bell);
287 if (!next) {
288 return false;
289 }
290
291 next->keep_state = true;
292
293 m_mouth_volume = volume;
294 publish(std::move(next));
295 return true;
296}
297
298bool DuctNetwork::set_wall_losses(double friction, double viscosity)
299{
300 std::scoped_lock lock(m_producer_mutex);
301 const Losses losses { .automatic = false, .friction = friction, .viscosity = viscosity };
302 auto next = build(m_length, m_profile, losses, m_mouth_volume, m_mouth, m_bell);
303 if (!next) {
304 return false;
305 }
306
307 next->keep_state = true;
308
309 m_losses = losses;
310 publish(std::move(next));
311 return true;
312}
313
315{
316 std::scoped_lock lock(m_producer_mutex);
317 const Losses losses { .automatic = true };
318 auto next = build(m_length, m_profile, losses, m_mouth_volume, m_mouth, m_bell);
319 if (!next) {
320 return false;
321 }
322
323 next->keep_state = true;
324
325 m_losses = losses;
326 publish(std::move(next));
327 return true;
328}
329
330bool DuctNetwork::set_mouth(std::shared_ptr<TerminationOperator> termination)
331{
332 std::scoped_lock lock(m_producer_mutex);
333 auto next = build(m_length, m_profile, m_losses, m_mouth_volume, termination, m_bell);
334 if (!next) {
335 return false;
336 }
337
338 next->keep_state = true;
339
340 m_operator_chain->remove(m_mouth);
341 m_mouth = std::move(termination);
343 publish(std::move(next));
344 return true;
345}
346
347bool DuctNetwork::set_bell(std::shared_ptr<TerminationOperator> termination)
348{
349 std::scoped_lock lock(m_producer_mutex);
350 auto next = build(m_length, m_profile, m_losses, m_mouth_volume, m_mouth, termination);
351 if (!next) {
352 return false;
353 }
354
355 next->keep_state = true;
356
357 m_operator_chain->remove(m_bell);
358 m_bell = std::move(termination);
360 publish(std::move(next));
361 return true;
362}
363
364std::shared_ptr<TerminationOperator> DuctNetwork::get_mouth() const
365{
366 std::scoped_lock lock(m_producer_mutex);
367 return m_mouth;
368}
369
370std::shared_ptr<TerminationOperator> DuctNetwork::get_bell() const
371{
372 std::scoped_lock lock(m_producer_mutex);
373 return m_bell;
374}
375
377{
378 m_pickup.store(std::clamp(position, 0.0, 1.0), std::memory_order_relaxed);
379}
380
381//-----------------------------------------------------------------------------
382// Processing
383//-----------------------------------------------------------------------------
384
385void DuctNetwork::process_batch(unsigned int num_samples)
386{
389
390 if (!is_enabled() || !m_active || num_samples == 0) {
391 m_scratch.assign(num_samples, 0.0);
393 return;
394 }
395
399
400 Prepared& state = *m_active;
401 state.mouth->process(static_cast<float>(num_samples));
402 state.bell->process(static_cast<float>(num_samples));
403
404 const Output output = m_output.load(std::memory_order_relaxed);
405 const double pickup = m_pickup.load(std::memory_order_relaxed);
406 const Acoustics::DuctGrid& grid = state.grid;
407
408 m_scratch.assign(num_samples, 0.0);
409 for (unsigned int i = 0; i < num_samples; ++i) {
410 Acoustics::advance_velocity(state.velocity, state.pressure, grid.velocity_gain);
411 state.loss.apply(state.velocity);
412
413 const auto [mouth_pressure, mouth_inflow] = state.mouth->couple(state.pressure.front(), state.velocity.front());
414 Acoustics::advance_pressure(state.pressure, state.velocity, grid.pressure_gain);
415 state.pressure.front() = mouth_pressure;
416
417 const auto [bell_pressure, bell_inflow] = state.bell->couple(state.pressure.back(), -state.velocity.back());
418 state.pressure.back() = bell_pressure;
419
420 const double outflow = -bell_inflow;
421 m_scratch[i] = output == Output::RADIATED
422 ? Acoustics::radiated_pressure(outflow, m_previous_outflow, grid.time_step, state.spec.air_density)
423 : Acoustics::sample_pressure(state.pressure, pickup);
424 m_previous_outflow = outflow;
425 }
426
428}
429
430void DuctNetwork::publish_block(std::span<const double> block)
431{
432 while (m_audio_buffer_lock.test_and_set(std::memory_order_acquire)) {
433 std::this_thread::yield();
434 }
435
436 m_last_audio_buffer.assign(block.begin(), block.end());
439
440 if (m_active) {
441 m_field.assign(m_active->pressure.begin(), m_active->pressure.end());
442 }
443
444 m_audio_buffer_lock.clear(std::memory_order_release);
445}
446
447//-----------------------------------------------------------------------------
448// Parameter mapping
449//-----------------------------------------------------------------------------
450
452{
453 for (const auto& mapping : m_parameter_mappings) {
454 if (mapping.mode != MappingMode::BROADCAST || !mapping.broadcast_source) {
455 continue;
456 }
457
458 const ParameterKey key { .name = mapping.param_name, .hash = mapping.param_hash };
459 const double value = mapping.broadcast_source->get_last_output();
460
461 if (key.matches("pickup")) {
463 } else if (key.matches("scale")) {
464 m_output_scale = std::max(0.0, value);
465 } else {
466 m_active->mouth->set_mapped_parameter(key, value);
467 m_active->bell->set_mapped_parameter(key, value);
468 }
469 }
470}
471
473{
474 if (const auto pickup = m_controls.pickup.pending()) {
475 apply_pickup_position(*pickup);
476 }
477 if (const auto output = m_controls.output.pending()) {
478 m_output.store(*output > 0.5 ? Output::PICKUP : Output::RADIATED, std::memory_order_relaxed);
479 }
480
481 const auto forward = [this](std::string_view name, Control& control) {
482 if (name == "scale" || name == "pickup" || name == "output") {
483 return;
484 }
485 if (const auto value = control.pending()) {
486 const ParameterKey key = parameter_key(name);
487 m_active->mouth->set_mapped_parameter(key, *value);
488 m_active->bell->set_mapped_parameter(key, *value);
489 }
490 };
491
492 std::apply(
493 [&](const auto&... member) { (forward(member.name, member.get(m_controls)), ...); },
495}
496
498 const std::string& param_name,
499 const std::shared_ptr<Node>& source,
500 MappingMode mode)
501{
502 unmap_parameter(param_name);
503
504 ParameterMapping mapping;
505 mapping.param_name = param_name;
506 mapping.mode = mode;
507 mapping.param_hash = parameter_hash(param_name);
508 mapping.broadcast_source = source;
509 mapping.network_source = nullptr;
510
511 m_parameter_mappings.push_back(std::move(mapping));
512}
513
515 const std::string& param_name,
516 const std::shared_ptr<NodeNetwork>& source)
517{
518 unmap_parameter(param_name);
519
520 ParameterMapping mapping;
521 mapping.param_name = param_name;
523 mapping.param_hash = parameter_hash(param_name);
524 mapping.broadcast_source = nullptr;
525 mapping.network_source = source;
526
527 m_parameter_mappings.push_back(std::move(mapping));
528}
529
530void DuctNetwork::unmap_parameter(const std::string& param_name)
531{
532 std::erase_if(m_parameter_mappings,
533 [&](const auto& mapping) { return mapping.param_name == param_name; });
534}
535
536//-----------------------------------------------------------------------------
537// Observation
538//-----------------------------------------------------------------------------
539
540std::optional<double> DuctNetwork::get_node_output(size_t index) const
541{
542 while (m_audio_buffer_lock.test_and_set(std::memory_order_acquire)) {
543 std::this_thread::yield();
544 }
545 const std::optional<double> value = index < m_field.size()
546 ? std::optional<double> { m_field[index] }
547 : std::nullopt;
548 m_audio_buffer_lock.clear(std::memory_order_release);
549 return value;
550}
551
552std::optional<std::span<const double>> DuctNetwork::get_node_audio_buffer(size_t index) const
553{
554 if (index != 0 || m_last_audio_buffer.empty()) {
555 return std::nullopt;
556 }
557 return std::span<const double>(m_last_audio_buffer);
558}
559
560std::vector<double> DuctNetwork::pressure_field() const
561{
562 while (m_audio_buffer_lock.test_and_set(std::memory_order_acquire)) {
563 std::this_thread::yield();
564 }
565 std::vector<double> copy = m_field;
566 m_audio_buffer_lock.clear(std::memory_order_release);
567 return copy;
568}
569
570std::unordered_map<std::string, std::string> DuctNetwork::get_metadata() const
571{
572 auto metadata = NodeNetwork::get_metadata();
573
574 std::scoped_lock lock(m_producer_mutex);
575 metadata["length"] = std::to_string(m_length) + " m";
576 metadata["intervals"] = std::to_string(m_intervals);
577 metadata["courant"] = std::to_string(m_courant);
578 metadata["bandwidth"] = std::to_string(m_bandwidth) + " Hz";
579 metadata["friction"] = std::to_string(m_applied_friction) + " 1/s";
580 metadata["viscosity"] = std::to_string(m_applied_viscosity) + " m^2/s";
581 metadata["mouth"] = std::string(m_mouth->get_type_name());
582 metadata["bell"] = std::string(m_bell->get_type_name());
583 metadata["output"] = std::string(Reflect::enum_to_string(m_output.load(std::memory_order_relaxed)));
584 return metadata;
585}
586
587} // namespace MayaFlux::Nodes::Network
#define MF_WARN(comp, ctx,...)
One named control of a network or operator: empty, a value, or a mapped source.
Definition Control.hpp:34
bool set_wall_losses(double friction, double viscosity)
Set the wall losses by hand.
bool set_mouth(std::shared_ptr< TerminationOperator > termination)
Replace the termination at the mouth.
bool set_profile(const std::vector< double > &radii)
Replace the profile with radii sampled evenly from mouth to bell.
std::shared_ptr< Prepared > build(double length, const Profile &profile, const Losses &losses, double mouth_volume, const std::shared_ptr< TerminationOperator > &mouth, const std::shared_ptr< TerminationOperator > &bell) const
bool use_viscothermal_losses()
Take the wall losses from the duct's mean radius, fitted to the viscothermal attenuation of a tube at...
void reset() override
Return the duct to rest, installed at the next block.
std::shared_ptr< TerminationOperator > m_mouth
std::shared_ptr< Prepared > m_slot
void setup(double length, Profile profile, double sample_rate)
void publish(std::shared_ptr< Prepared > next)
void unmap_parameter(const std::string &param_name) override
Remove parameter mapping.
DuctNetwork(double length, double radius, double sample_rate=48000.0)
A cylinder.
void map_parameter(const std::string &param_name, const std::shared_ptr< Node > &source, MappingMode mode=MappingMode::BROADCAST) override
Map external node output to network parameter.
std::shared_ptr< Prepared > m_active
std::vector< double > pressure_field() const
Copy of the pressures along the duct from the last block.
Output
What the network publishes.
@ PICKUP
Pressure inside the duct at the pickup position.
@ RADIATED
Pressure radiated at one metre, from the flow out of the bell.
void process_batch(unsigned int num_samples) override
Process the network for the given number of samples.
std::optional< std::span< const double > > get_node_audio_buffer(size_t index) const override
Get output of specific internal node as audio buffer (for ONE_TO_ONE mapping).
bool set_mouth_volume(double volume)
Add air behind the mouth end, in cubic metres.
std::shared_ptr< TerminationOperator > m_bell
void apply_pickup_position(double position)
void bind(Prepared &prepared, bool keep)
void initialize() override
Called once before first process_batch().
std::shared_ptr< TerminationOperator > get_bell() const
bool set_length(double length)
Change the length in metres, keeping the profile.
void publish_block(std::span< const double > block)
std::unordered_map< std::string, std::string > get_metadata() const override
Get network metadata for debugging/visualization.
std::shared_ptr< TerminationOperator > get_mouth() const
bool set_radius(double radius)
Make the duct a cylinder of this radius in metres.
bool set_bell(std::shared_ptr< TerminationOperator > termination)
Replace the termination at the bell.
std::optional< double > get_node_output(size_t index) const override
Pressure at one point along the duct, from the last block.
std::vector< ParameterMapping > m_parameter_mappings
C & declare_controls()
Create the network's controls struct and keep it alive.
void apply_output_scale()
Apply m_output_scale to m_last_audio_buffer.
virtual void set_topology(Topology topology)
Set the network's topology.
bool is_enabled() const
Check if network is enabled.
double m_output_scale
Post-processing scalar applied to m_last_audio_buffer each batch.
void refresh_controls()
Read node sources and apply the shared scale.
std::shared_ptr< OperatorChain > m_operator_chain
std::atomic_flag m_audio_buffer_lock
Spinlock guarding m_last_audio_buffer.
void ensure_initialized()
Ensure initialize() is called exactly once.
virtual std::unordered_map< std::string, std::string > get_metadata() const
Get network metadata for debugging/visualization.
std::vector< double > m_last_audio_buffer
void set_output_mode(OutputMode mode)
Set the network's output routing mode.
@ Configuration
Configuration and parameter updates.
@ Nodes
DSP Generator and Filter Nodes, graph pipeline, node management.
constexpr uint64_t parameter_hash(std::string_view name) noexcept
Hash a parameter name once when installing a mapping.
constexpr ParameterKey parameter_key(std::string_view name) noexcept
@ CHAIN
Linear sequence: node[i] → node[i+1].
MappingMode
How one source maps to a network's elements.
@ ONE_TO_ONE
Source elements correspond to network elements.
@ BROADCAST
One source value applies to every network element.
@ AUDIO_SINK
Aggregated audio samples sent to output.
constexpr std::string_view enum_to_string(EnumType value) noexcept
Universal enum to string converter using magic_enum (original case).
Controls of a DuctNetwork, each a number or a mapped node.
std::shared_ptr< TerminationOperator > mouth
std::shared_ptr< TerminationOperator > bell
std::function< double(double)> function
constexpr bool matches(std::string_view candidate) const noexcept
A cached hash paired with its original name for collision-safe matching.