HART  0.2.0
High level Audio Regression and Testing
Loading...
Searching...
No Matches
hart_process_audio.hpp
Go to the documentation of this file.
1#pragma once
2
3#include <algorithm> // min()
4#include <cassert>
5#include <cmath>
6#include <iomanip>
7#include <memory>
8#include <sstream>
9#include <vector>
10
12#include "dsp/hart_dsp_all.hpp"
14#include "matchers/hart_matcher.hpp"
15#include "hart_plot.hpp"
18#include "signals/hart_signals_all.hpp"
19#include "hart_utils.hpp" // make_unique()
20
21namespace hart {
22
23/// @defgroup TestRunner Test Runner
24/// @brief Runs the tests
25
26/// @brief Determines when to save a file
27/// @ingroup TestRunner
28enum class Save
29{
30 always, ///< File will be saved always, after the test is performed
31 whenFails, ///< File will be saved only when the test has failed
32 never ///< File will not be saved
33};
34
35/// @brief A DSP host used for building and running tests inside a test case
36/// @ingroup TestRunner
37template <typename SampleType>
39{
40public:
41 /// @brief Copies the DSP instance into the host
42 /// @details DSP instance will be moved into this host, and then returned by @ref process(), so you can re-use it.
43 /// @param dsp Your DSP instance.
44 template <typename DSPType>
45 AudioTestBuilder (DSPType&& dsp,
46 typename std::enable_if<
47 std::is_lvalue_reference<DSPType&&>::value &&
48 std::is_base_of<DSPBase<SampleType>, typename std::decay<DSPType>::type>::value
49 >::type* = 0)
50 : m_processor (dsp.copy())
51 {
52 }
53
54 /// @brief Moves the DSP instance into the host
55 /// @details DSP instance will be moved into this host, and then returned by @ref process(), so you can re-use it.
56 /// @param dsp Your DSP instance
57 template <typename DSPType>
58 AudioTestBuilder (DSPType&& dsp,
59 typename std::enable_if<
60 ! std::is_lvalue_reference<DSPType&&>::value &&
61 std::is_base_of<DSPBase<SampleType>, typename std::decay<DSPType>::type>::value
62 >::type* = 0)
63 : m_processor (std::forward<DSPType> (dsp).move())
64 {
65 }
66
67 /// @brief Transfers the DSP smart pointer into the host
68 /// @details Use this if your DSP does not support copying or moving. It will be owned by this host,
69 /// and then returned by @ref process(), so you can re-use it.
70 /// @param dsp A smart pointer to your DSP instance
71 AudioTestBuilder (std::unique_ptr<DSPBase<SampleType>> dsp)
72 : m_processor (std::move (dsp))
73 {
74 }
75
76 /// @brief Sets the sample rate for the test
77 /// @details All the signals, effects and sub hosts are guaranteed to be initialized to this sample rate
78 /// @param sampleRateHz Sample rate in Hz. You can use frequency-related literails from @ref Units.
79 AudioTestBuilder& withSampleRate (double sampleRateHz)
80 {
81 if (sampleRateHz <= 0)
82 HART_THROW_OR_RETURN (hart::ValueError, "Sample rate should be a positive value in Hz", *this);
83
84 if (! m_processor->supportsSampleRate (sampleRateHz))
85 HART_THROW_OR_RETURN (hart::SampleRateError, "Sample rate is not supported by the tested DSP", *this);
86
87 m_sampleRateHz = sampleRateHz;
88 return *this;
89 }
90
91 /// @brief Sets the block size for the test
92 /// @param blockSizeFrames Block size in frames (samples)
93 AudioTestBuilder& withBlockSize (size_t blockSizeFrames)
94 {
95 if (blockSizeFrames == 0)
96 HART_THROW_OR_RETURN (hart::SizeError, "Illegal block size - should be a positive value in frames (samples)", *this);
97
98 m_blockSizeFrames = blockSizeFrames;
99 return *this;
100 }
101
102 /// @brief Sets the initial param value for the tested DSP
103 /// @details It will call @ref DSP::setValue() for DSP under test
104 /// @param id Parameter ID (see @ref DSP::setValue())
105 /// @param value Value that needs to be set
106 AudioTestBuilder& withValue (int id, double value)
107 {
108 // TODO: Handle cases when processor already has an envelope for this id
109 paramValues.emplace_back (ParamValue { id, value });
110 return *this;
111 }
112
113 /// @brief Sets the total duration of the input signal to be processed
114 /// @param Duration of the signal in seconds. You can use time-related literails from @ref Units.
115 AudioTestBuilder& withDuration (double durationSeconds)
116 {
117 if (durationSeconds < 0)
118 HART_THROW_OR_RETURN(hart::ValueError, "Signal duration should be a non-negative value in Hz", *this);
119
120 m_durationSeconds = durationSeconds;
121 return *this;
122 }
123
124 /// @brief Sets the input signal for the test
125 /// @param signal Input signal, see @ref Signals
126 AudioTestBuilder& withInputSignal (const SignalBase<SampleType>& signal)
127 {
128 // TODO: Implement moving/transfering a signal instance as well
129 m_inputSignal = std::move (signal.copy());
130 return *this;
131 }
132
133 /// @brief Sets arbitrary number of input channels
134 /// @details For common mono and stereo cases, you may use dedicated methods like @ref inStereo() or
135 /// @ref withMonoInput() instead of this one for better readability.
136 /// @param numInputChannels Number of input channels
137 AudioTestBuilder& withInputChannels (size_t numInputChannels)
138 {
139 if (numInputChannels == 0)
140 HART_THROW_OR_RETURN (SizeError, "There should be at least one (mono) audio channel", *this);
141
142 if (numInputChannels > 128)
143 HART_THROW_OR_RETURN (SizeError, "The number of channels is unexpectedly large... Do people really use so many channels?", *this);
144
145 m_numInputChannels = numInputChannels;
146 return *this;
147 }
148
149 /// @brief Sets arbitrary number of output channels
150 /// @details For common mono and stereo cases, you may use dedicated methods like @ref inMono() or
151 /// @ref withStereoOutput() instead of this one for better readability.
152 /// @param numOutputChannels Number of output channels
153 AudioTestBuilder& withOutputChannels (size_t numOutputChannels)
154 {
155 if (numOutputChannels == 0)
156 HART_THROW_OR_RETURN(SizeError, "There should be at least one (mono) audio channel", *this);
157
158 if (numOutputChannels > 128)
159 HART_THROW_OR_RETURN(SizeError, "The number of channels is unexpectedly large... Do people really use so many channels?", *this);
160
161 m_numOutputChannels = numOutputChannels;
162 return *this;
163 }
164
165 /// @brief Sets number of input channels to two
167 {
168 return this->withInputChannels (2);
169 }
170
171 /// @brief Sets number of output channels to two
173 {
174 return this->withOutputChannels (2);
175 }
176
177 /// @brief Sets number of input channels to one
179 {
180 return this->withInputChannels (1);
181 }
182
183 /// @brief Sets number of output channels to one
185 {
186 return this->withOutputChannels (1);
187 }
188
189 /// @brief Sets number of input and output channels to one
191 {
192 return this->withMonoInput().withMonoOutput();
193 }
194
195 /// @brief Sets number of input and output channels to two
197 {
198 return this->withStereoInput().withStereoOutput();
199 }
200
201 /// @brief Adds an "expect" check
202 /// @param matcher Matcher to perform the check, see @ref Matchers
203 template<typename MatcherType>
204 AudioTestBuilder& expectTrue (MatcherType&& matcher)
205 {
206 addCheck (std::forward<MatcherType> (matcher), SignalAssertionLevel::expect, true);
207 return *this;
208 }
209
210 /// @brief Adds a reversed "expect" check
211 /// @param matcher Matcher to perform the check, see @ref Matchers
212 template<typename MatcherType>
213 AudioTestBuilder& expectFalse (MatcherType&& matcher)
214 {
215 addCheck (std::forward<MatcherType> (matcher), SignalAssertionLevel::expect, false);
216 return *this;
217 }
218
219 /// @brief Adds an "assert" check
220 /// @param matcher Matcher to perform the check, see @ref Matchers
221 template<typename MatcherType>
222 AudioTestBuilder& assertTrue (MatcherType&& matcher)
223 {
224 addCheck (std::forward<MatcherType> (matcher), SignalAssertionLevel::assert, true);
225 return *this;
226 }
227
228 /// @brief Adds a reversed "assert" check
229 /// @param matcher Matcher to perform the check, see @ref Matchers
230 template<typename MatcherType>
231 AudioTestBuilder& assertFalse (MatcherType&& matcher)
232 {
233 addCheck (std::forward<MatcherType> (matcher), SignalAssertionLevel::assert, false);
234 return *this;
235 }
236
237 /// @brief Enables saving output audio to a wav file
238 /// @param path File path - relative or absolute. If relative path is set, it will be appended to the provided `--data-root-path` CLI argument.
239 /// @param mode When to save, see @ref hart::Save
240 /// @param wavFormat Format of the wav file, see hart::WavFormat for supported options
241 /// @see HART_REQUIRES_DATA_PATH_ARG
242 AudioTestBuilder& saveOutputTo (const std::string& path, Save mode = Save::always, WavFormat wavFormat = WavFormat::pcm24)
243 {
244 if (path.empty())
245 return *this;
246
247 m_saveOutputPath = toAbsolutePath (path);
248 m_saveOutputMode = mode;
249 m_saveOutputWavFormat = wavFormat;
250 return *this;
251 }
252
253 /// @brief Enables saving a plot to an SVG file
254 /// @details This will plot an input and output audio as a waveform
255 /// @param path File path - relative or absolute. If relative path is set, it will be appended to the provided `--data-root-path` CLI argument.
256 /// @param mode When to save, see @ref hart::Save
257 /// @see HART_REQUIRES_DATA_PATH_ARG
258 AudioTestBuilder& savePlotTo (const std::string& path, Save mode = Save::always)
259 {
260 if (path.empty())
261 return *this;
262
263 m_savePlotPath = toAbsolutePath (path);
264 m_savePlotMode = mode;
265 return *this;
266 }
267
268 /// @brief Adds a label to the test
269 /// @details Useful when you call @ref process() multiple times in one test case - the label
270 /// will be put into test failure report to indicate exactly which test has failed.
271 /// @param testLabel Any text, to be used as a label
272 AudioTestBuilder& withLabel (const std::string& testLabel)
273 {
274 m_testLabel = testLabel;
275 return *this;
276 }
277
278 /// @brief Perfoems the test
279 /// @details Call this after setting all the test parameters
280 std::unique_ptr<DSPBase<SampleType>> process()
281 {
282 m_durationFrames = (size_t) std::round (m_sampleRateHz * m_durationSeconds);
283
284 if (m_durationFrames == 0)
285 HART_THROW_OR_RETURN (hart::SizeError, "Nothing to process", std::move (m_processor));
286
287 for (auto& check : perBlockChecks)
288 {
289 check.matcher->prepare (m_sampleRateHz, m_numOutputChannels, m_blockSizeFrames);
290 check.shouldSkip = false;
291 }
292
293 for (auto& check : fullSignalChecks)
294 {
295 check.matcher->prepare (m_sampleRateHz, m_numOutputChannels, m_blockSizeFrames);
296 check.shouldSkip = false;
297 }
298
299 // TODO: Ckeck supportsChannelLayout() here
300 m_processor->reset();
301 m_processor->prepareWithEnvelopes (m_sampleRateHz, m_numInputChannels, m_numOutputChannels, m_blockSizeFrames);
302
303 for (const ParamValue& paramValue : paramValues)
304 {
305 // TODO: Add true/false return to indicate if setting the parameter was successful
306 m_processor->setValue (paramValue.id, paramValue.value);
307 }
308
309 if (m_inputSignal == nullptr)
310 HART_THROW_OR_RETURN (hart::StateError, "No input signal - call withInputSignal() first!", std::move (m_processor));
311
312 m_inputSignal->resetWithDSPChain();
313 m_inputSignal->prepareWithDSPChain (m_sampleRateHz, m_numInputChannels, m_blockSizeFrames);
314 offsetFrames = 0;
315
316 AudioBuffer<SampleType> fullInputBuffer (m_numInputChannels);
317 AudioBuffer<SampleType> fullOutputBuffer (m_numOutputChannels);
318 bool atLeastOneCheckFailed = false;
319
320 while (offsetFrames < m_durationFrames)
321 {
322 // TODO: Do not continue if there are no checks, or all checks should skip and there's no input and output file to write
323
324 const size_t blockSizeFrames = std::min (m_blockSizeFrames, m_durationFrames - offsetFrames);
325
326 hart::AudioBuffer<SampleType> inputBlock (m_numInputChannels, blockSizeFrames);
327 hart::AudioBuffer<SampleType> outputBlock (m_numOutputChannels, blockSizeFrames);
328 m_inputSignal->renderNextBlockWithDSPChain (inputBlock);
329 m_processor->processWithEnvelopes (inputBlock, outputBlock);
330
331 const bool allChecksPassed = processChecks (perBlockChecks, outputBlock);
332 atLeastOneCheckFailed |= ! allChecksPassed;
333 fullInputBuffer.appendFrom (inputBlock);
334 fullOutputBuffer.appendFrom (outputBlock);
335
336 offsetFrames += blockSizeFrames;
337 }
338
339 const bool allChecksPassed = processChecks (fullSignalChecks, fullOutputBuffer);
340 atLeastOneCheckFailed |= ! allChecksPassed;
341
342 if (m_saveOutputMode == Save::always || (m_saveOutputMode == Save::whenFails && atLeastOneCheckFailed))
343 WavWriter<SampleType>::writeBuffer (fullOutputBuffer, m_saveOutputPath, m_sampleRateHz, m_saveOutputWavFormat);
344
345 if (m_savePlotMode == Save::always || (m_savePlotMode == Save::whenFails && atLeastOneCheckFailed))
346 plotData (fullInputBuffer, fullOutputBuffer, m_sampleRateHz, m_savePlotPath);
347
348 return std::move (m_processor);
349 }
350
351private:
352 struct ParamValue
353 {
354 int id;
355 double value;
356 };
357
358 enum class SignalAssertionLevel
359 {
360 expect,
361 assert,
362 };
363
364 struct Check
365 {
366 std::unique_ptr<MatcherBase<SampleType>> matcher;
367 SignalAssertionLevel signalAssertionLevel;
368 bool shouldSkip;
369 bool shouldPass;
370 };
371
372 std::unique_ptr<DSPBase<SampleType>> m_processor;
373 std::unique_ptr<SignalBase<SampleType>> m_inputSignal;
374 double m_sampleRateHz = (double) 44100;
375 size_t m_blockSizeFrames = 1024;
376 size_t m_numInputChannels = 1;
377 size_t m_numOutputChannels = 1;
378 std::vector<ParamValue> paramValues;
379 double m_durationSeconds = 0.1;
380 size_t m_durationFrames = static_cast<size_t> (m_durationSeconds * m_sampleRateHz);
381 size_t offsetFrames = 0;
382 std::string m_testLabel = {};
383
384 std::vector<Check> perBlockChecks;
385 std::vector<Check> fullSignalChecks;
386
387 std::string m_saveOutputPath;
388 Save m_saveOutputMode = Save::never;
389 WavFormat m_saveOutputWavFormat = WavFormat::pcm24;
390
391 std::string m_savePlotPath;
392 Save m_savePlotMode = Save::never;
393
394 template<
395 typename MatcherType,
396 typename = typename std::enable_if<
397 ! std::is_same<
398 typename std::decay<MatcherType>::type,
399 MatcherBase<SampleType>
400 >::value
401 >::type>
402 void addCheck (MatcherType&& matcher, SignalAssertionLevel assertionLevel, bool shouldPass)
403 {
404 using Derived = typename std::decay<MatcherType>::type;
405 static_assert (std::is_base_of<MatcherBase<SampleType>, Derived>::value, "matcher argument must derive from hart::Matcher");
406
407 const bool forceFullSignal = !shouldPass;
408 auto& group = (matcher.canOperatePerBlock() && !forceFullSignal)
409 ? perBlockChecks
410 : fullSignalChecks;
411
412 // TODO: emplace_back()
413 group.push_back ({
414 std::forward<MatcherType>(matcher).move(),
415 assertionLevel,
416 false,
417 shouldPass
418 });
419 }
420
421 void addCheck (const MatcherBase<SampleType>& matcher, SignalAssertionLevel assertionLevel, bool shouldPass)
422 {
423 const bool forceFullSignal = ! shouldPass;
424 auto& group = (matcher.canOperatePerBlock() && ! forceFullSignal)
425 ? perBlockChecks
426 : fullSignalChecks;
427
428 // TODO: emplace_back()
429 group.push_back({ matcher.copy(), assertionLevel, false, shouldPass });
430 }
431
432 bool processChecks (std::vector<Check>& checksGroup, AudioBuffer<SampleType>& outputBlock)
433 {
434 for (auto& check : checksGroup)
435 {
436 if (check.shouldSkip)
437 continue;
438
439 auto& assertionLevel = check.signalAssertionLevel;
440 auto& matcher = check.matcher;
441
442 const bool matchPassed = matcher->match (outputBlock);
443
444 if (matchPassed != check.shouldPass)
445 {
446 check.shouldSkip = true;
447
448 if (assertionLevel == SignalAssertionLevel::assert)
449 {
450 std::stringstream stream;
451 stream << (check.shouldPass ? "assertTrue() failed" : "assertFalse() failed");
452
453 if (! m_testLabel.empty())
454 stream << " at \"" << m_testLabel << "\"";
455
456 stream << std::endl << "Condition: " << *matcher;
457
458 if (check.shouldPass)
459 appendFailureDetails (stream, matcher->getFailureDetails(), outputBlock);
460
461 throw hart::TestAssertException (std::string (stream.str()));
462 }
463 else
464 {
465 std::stringstream stream;
466 stream << (check.shouldPass ? "expectTrue() failed" : "expectFalse() failed");
467
468 if (!m_testLabel.empty())
469 stream << " at \"" << m_testLabel << "\"";
470
471 stream << std::endl << "Condition: " << * matcher;
472
473 if (check.shouldPass)
474 appendFailureDetails (stream, matcher->getFailureDetails(), outputBlock);
475
476 hart::ExpectationFailureMessages::get().emplace_back (stream.str());
477 }
478
479 // TODO: FIXME: Do not throw indife of per-block loop if requested to write input or output to a wav file, throw after the loop instead
480 // TODO: Stop processing if expect has failed and outputting to a file wasn't requested
481 // TODO: Skip all checks if check failed, but asked to output a wav file
482 return false;
483 }
484 }
485
486 return true;
487 }
488
489 void appendFailureDetails (std::stringstream& stream, const MatcherFailureDetails& details, AudioBuffer<SampleType>& observedAudioBlock)
490 {
491 const double timestampSeconds = static_cast<double> (offsetFrames + details.frame) / m_sampleRateHz;
492 const SampleType sampleValue = observedAudioBlock[details.channel][details.frame];
493
494 stream << std::endl
495 << "Channel: " << details.channel << std::endl
496 << "Frame: " << details.frame << std::endl
497 << secPrecision << "Timestamp: " << timestampSeconds << " seconds" << std::endl
498 << linPrecision << "Sample value: " << sampleValue
499 << dbPrecision << " (" << ratioToDecibels (std::abs (sampleValue)) << " dB)" << std::endl
500 << details.description;
501 }
502};
503
504/// @brief Call this to start building your test
505/// @param dsp Instance of your DSP effect
506/// @return @ref AudioTestBuilder instance - you can chain a bunch of test parameters with it.
507/// @ingroup TestRunner
508/// @relates AudioTestBuilder
509template <typename DSPType>
510AudioTestBuilder<typename std::decay<DSPType>::type::SampleTypePublicAlias> processAudioWith (DSPType&& dsp)
511{
512 return AudioTestBuilder<typename std::decay<DSPType>::type::SampleTypePublicAlias> (std::forward<DSPType>(dsp));
513}
514
515/// @brief Call this to start building your test
516/// @details Call this for DSP objects that do not support moving or copying
517/// @param dsp Instance of your DSP effect wrapped in a smart pointer
518/// @return @ref AudioTestBuilder instance - you can chain a bunch of test parameters with it.
519/// @ingroup TestRunner
520/// @relates AudioTestBuilder
521template <typename DSPType>
522AudioTestBuilder<typename DSPType::SampleTypePublicAlias> processAudioWith (std::unique_ptr<DSPType>&& dsp)
523{
524 using SampleType = typename DSPType::SampleTypePublicAlias;
525 return AudioTestBuilder<SampleType> (std::unique_ptr<DSPBase<SampleType>> (dsp.release()));
526}
527
529{
530 using hart::processAudioWith;
531}
533{
534 using hart::processAudioWith;
535}
536
537} // namespace hart
A DSP host used for building and running tests inside a test case.
AudioTestBuilder & inMono()
Sets number of input and output channels to one.
AudioTestBuilder & withLabel(const std::string &testLabel)
Adds a label to the test.
AudioTestBuilder(DSPType &&dsp, typename std::enable_if< std::is_lvalue_reference< DSPType && >::value &&std::is_base_of< DSPBase< SampleType >, typename std::decay< DSPType >::type >::value >::type *=0)
Copies the DSP instance into the host.
AudioTestBuilder & withDuration(double durationSeconds)
Sets the total duration of the input signal to be processed.
AudioTestBuilder & withStereoInput()
Sets number of input channels to two.
AudioTestBuilder & expectFalse(MatcherType &&matcher)
Adds a reversed "expect" check.
AudioTestBuilder & assertFalse(MatcherType &&matcher)
Adds a reversed "assert" check.
AudioTestBuilder & withInputChannels(size_t numInputChannels)
Sets arbitrary number of input channels.
AudioTestBuilder(DSPType &&dsp, typename std::enable_if< ! std::is_lvalue_reference< DSPType && >::value &&std::is_base_of< DSPBase< SampleType >, typename std::decay< DSPType >::type >::value >::type *=0)
Moves the DSP instance into the host.
AudioTestBuilder(std::unique_ptr< DSPBase< SampleType > > dsp)
Transfers the DSP smart pointer into the host.
AudioTestBuilder & expectTrue(MatcherType &&matcher)
Adds an "expect" check.
AudioTestBuilder & withSampleRate(double sampleRateHz)
Sets the sample rate for the test.
AudioTestBuilder & savePlotTo(const std::string &path, Save mode=Save::always)
Enables saving a plot to an SVG file.
AudioTestBuilder & withMonoOutput()
Sets number of output channels to one.
AudioTestBuilder & assertTrue(MatcherType &&matcher)
Adds an "assert" check.
AudioTestBuilder & withValue(int id, double value)
Sets the initial param value for the tested DSP.
AudioTestBuilder & saveOutputTo(const std::string &path, Save mode=Save::always, WavFormat wavFormat=WavFormat::pcm24)
Enables saving output audio to a wav file.
AudioTestBuilder & withInputSignal(const SignalBase< SampleType > &signal)
Sets the input signal for the test.
AudioTestBuilder & withMonoInput()
Sets number of input channels to one.
AudioTestBuilder & withStereoOutput()
Sets number of output channels to two.
AudioTestBuilder & inStereo()
Sets number of input and output channels to two.
AudioTestBuilder & withOutputChannels(size_t numOutputChannels)
Sets arbitrary number of output channels.
std::unique_ptr< DSPBase< SampleType > > process()
Perfoems the test.
AudioTestBuilder & withBlockSize(size_t blockSizeFrames)
Sets the block size for the test.
Polymorphic base for all DSP.
Definition hart_dsp.hpp:32
static std::vector< std::string > & get()
Polymorphic base for all matchers.
Polymorphic base for all signals.
std::ostream & linPrecision(std::ostream &stream)
Sets number of decimal places for linear (sample) values.
std::ostream & secPrecision(std::ostream &stream)
Sets number of decimal places for values in seconds.
std::ostream & dbPrecision(std::ostream &stream)
Sets number of decimal places for values in decibels.
Save
Determines when to save a file.
AudioTestBuilder< typename std::decay< DSPType >::type::SampleTypePublicAlias > processAudioWith(DSPType &&dsp)
Call this to start building your test.
AudioTestBuilder< typename DSPType::SampleTypePublicAlias > processAudioWith(std::unique_ptr< DSPType > &&dsp)
Call this to start building your test.
@ whenFails
File will be saved only when the test has failed.
@ never
File will not be saved.
@ always
File will be saved always, after the test is performed.
static std::string toAbsolutePath(const std::string &path)
Converts path to absolute, if it's relative.
#define HART_THROW_OR_RETURN(ExceptionType, message, returnValue)
size_t channel
Index of channel at which the failure was detected.
std::string description
Readable description of why the match has failed.
size_t frame
Index of frame at which the match has failed.