Skip to content

MIXER command improvements & general mixer enhancements + fixes - #2868

Merged
johnnovak merged 26 commits into
mainfrom
jn/mixer-fixes-5
Oct 25, 2023
Merged

johnnovak merged 26 commits into
mainfrom
jn/mixer-fixes-5

Conversation

@johnnovak

@johnnovak johnnovak commented Sep 15, 2023 •

Copy link
Copy Markdown
Member

Description

This is a significant rework of the command parsing, error reporting, and state handling of the MIXER command. The following bug fixes and improvements have been made:

  • Mixer channel settings now "survive" deleting then later re-creating the channel instead of simply getting the default settings when the channel is recreated. For example, if you customise the settings of the SB and OPL channels, then change sbtype to something else, the SB and OPL channels will retain their settings. Similar situation for the FSYNTH channel when setting mididevice to something else then back to fluidsynth.

  • The MIXER command no longer accepts slightly incorrect input; command parsing is now strict and we're displaying error messages for invalid commands. These messages also try to guide the user to correct their mistakes.

  • This might cause backward compatibility issues if people had slightly (or very!) incorrect MIXER command invocations in their configs, so we're also logging a warning when the MIXER command fails. That should give people a chance to correct these mistakes. Examples of invalid input that is no longer accepted:

    • MIXER ASDF R1 – Previously, the ASDF param was ignored because there is no channel with that name, so the scope stayed at "global scope" (all channels), then a global reverb setting of 1 was applied to all channels, which is super confusing.
    • MIXER SB 10 GUS – This set the SB volume to 10; now it fails because every channel name must be followed by one or more commands to remove ambiguity, and there's nothing after GUS.
    • MIXER SB 10 BLAH 4 – This set the SB channel's volume to 10 and ignored the non-existing BLAH channel; now an error is raised that BLAH is an invalid command.
    • MIXER SB ASDF – This just printed the mixer status but did not raise any errors; now it does.
    • MIXER SB R150 – This silently clamped the reverb level to 100 and set it for the SB channel; now we raise an error.
    • MIXER GUS 50 – If the GUS was not enabled, this just displayed the current mixer settings; now it prints and error saying that the GUS channel is not active.
    • There are millions of other cases that were confusing, wrong, or "technically correct" (according to the weird and overly relaxed parsing rules) but plain counterintuitive. Strict parsing and error reporting take care of all that. See the unit tests for further details and test cases.
  • MIXER command handling is now "transactional"—if there is a single error in a list of multiple commands, no command will be executed but an error for the first problem will be raised. This is just common sense and leads to less confusing behaviour overall.

  • The crossfeed config setting has been revised; now it works the same way as the chorus setting (it has light, normal and strong presets, and on defaults to normal). The previous behaviour where you could set a global crossfeed value (e.g., crossfeed = 30) was unsupportable even with a lot of special casing. It was simply impossible to make that behaviour consistent with the reverb and chorus settings—I literally rewrote it in 4-5 different ways before I settled on this solution. It just can't be done.

Other bundled changes

The number parsing string util functions have been revised to make them more generic, and the parsing is now strict. Previously, non-digit characters after digits were silently ignored; this now results in a parse error. Strict parsing is desirable as lenient parsing is a fertile breeding ground for subtle bugs and surprising behaviour (if affected the mixer commands, for example).

The flow-on effect is that the argument parsing of the MORE command is now stricter: MORE /t4x fname worked before (it set the tab size to 4 chars), but now that generates an "illegal switch" error (/t4 is the correct invocation). Other DOS commands implemented by us might be affected too.

Technical notes

I started using the std::visit and std::variant std lib features which are ideally suited for command line parsers and any kind of scenario when dealing with polymorphic command execution. I'm very cautious when adopting new C++ features, but these are so ideally suited to the task that I found them irresistible 😎 They're quite sane and low overhead, both mentally and syntax-wise.

std::variant is quite nice even in isolation; it can be used to return an "Either" or "Result" type common in functional languages that encapsulates either a "success" or an "error" result. IMO, this is the preferred alternative to the hacky old C/C++ way of providing "out" pointer arguments to return "secondary" results, such as errors.

A few nice introductory articles about using std::visit and std::variant together to implement command parsers & executors:

If everybody hates them, we can discuss finding an alternative way, but it would be a lot more complex and there would be a lot of boilerplate involved, so I'm strongly in favour of using std::visit and std::variant judiciously going forward (at least in non-performance intensive code).

Related issues

Fixes #2468
List of various issues fixed: #2468 (comment)

Manual testing

Proof of manual testing. These are end-to-end tests that exercise the whole stack; it would be difficult to create an automated test fixture/harness that wires up )just enough components_ to make this possible and would yield the same level of confidence.

These are highest-value tests, the absolutely highest value there is. Therefore, I'd like to keep them around by all means, preferably in an automated form. They are invaluable for regression testing when anyone touches the mixer the next time (some situations are complex and subtle; most people wouldn't even know what regressions to look out for... that includes me 6 months from now 😎).

Btw, one of the reasons why this PR was dragging on for so long was that redoing all this testing manually takes like 20 minutes (in a relaxed manner) and I was getting sick of it after re-doing it for the 10th time...

My low-cost solution is to write a batch file containing these commands that pipes the results to a file, then have an expected.txt that contains the expected outcome with the ANSI colour codes stripped. Then write a bash script that takes the actual output, strips the ANSI stuff out, then diffs it against expected.txt. Would do the job, but better ideas are welcome (hint: suggesting to write an actual end-to-end test harness that would take days or weeks is not a better idea 😎)

Error messages

error-messages-1

error-messages-2

error-messages-3

error-messages-4

Setting persistence

setting-persistence-1

setting-persistence-2

setting-persistence-3

MIDI stuff

midi-1

midi-2

midi-3

midi-4

Checklist

Please tick the items as you have addressed them. Don't remove items; leave the ones that are not applicable unchecked.

I have:

  • followed the project's contributing guidelines and code of conduct.
  • performed a self-review of my code.
  • commented on the particularly hard-to-understand areas of my code.
  • split my work into well-defined, bisectable commits, and I named my commits well.
  • applied the appropriate labels (bug, enhancement, refactoring, documentation, etc.)
  • checked that all my commits can be built.
  • confirmed that my code does not cause performance regressions (e.g., by running the Quake benchmark).
  • added unit tests where applicable to prove the correctness of my code and to avoid future regressions.
  • made corresponding changes to the documentation or the website according to the documentation guidelines.
  • locally verified my website or documentation changes.

@johnnovak
johnnovak force-pushed the jn/mixer-fixes-5 branch 10 times, most recently from cb9cc57 to 7fd0230 Compare September 21, 2023 03:37
@johnnovak
johnnovak force-pushed the jn/mixer-fixes-5 branch 5 times, most recently from d70b2cf to 3248752 Compare September 27, 2023 07:27
@johnnovak johnnovak changed the title DO NOT REVIEW MIXER command improvements & general mixer enhancements + fixes Sep 27, 2023
@johnnovak johnnovak added audio Audio related issues or enhancements enhancement New feature or enhancement of existing features bug Something isn't working labels Sep 27, 2023
@johnnovak johnnovak self-assigned this Sep 27, 2023
@johnnovak
johnnovak force-pushed the jn/mixer-fixes-5 branch 3 times, most recently from 17bf955 to 6be9ed7 Compare October 4, 2023 12:00
@johnnovak
johnnovak force-pushed the jn/mixer-fixes-5 branch 2 times, most recently from 22db435 to 5683b44 Compare October 6, 2023 08:58
@weirddan455

Copy link
Copy Markdown
Collaborator

I was curious about the std::variant stuff as I had never really used it. It looks like it's just a fancy tagged union and std::visit is just a fancy switch statement over the type tag.

If everybody hates them, we can discuss finding an alternative way, but it would be a lot more complex and there would be a lot of boilerplate involved, so I'm strongly in favour of using std::visit and std::variant judiciously going forward (at least in non-performance intensive code).

IMO for your use case I think it's syntactically a bit nicer to have Command be a pure virtual interface class and the different types of commands inherit from that with a virtual Execute function. That gets rid of the Executor class, and having to type out the template type of std::variant everywhere.

However, std::variant avoids having to heap allocate every Command and also avoids the virtual function overhead. So my initial assessment is the opposite. It seems a bit worse syntactically but probably has better performance.

Overall, I don't hate it. I think you could do exactly the same thing with a tagged union and a switch statement. But if you like the syntax of std::variant better then go for it.

@johnnovak

Copy link
Copy Markdown
Member Author

Thanks for the feedback @weirddan455. Just a few further comments / thoughts why I did things this particular way. I'm not "arguing" as you're already fine with this, just offering further explanations, maybe for the benefit of others too.

And my comment still stands; if everybody else than me really doesn't like this, then we're back to tagged unions / virtual functions / out vars 😄

IMO for your use case I think it's syntactically a bit nicer to have Command be a pure virtual interface class and the different types of commands inherit from that with a virtual Execute function. That gets rid of the Executor class, and having to type out the template type of std::variant everywhere.

I like the Executor class because we also need to maintain a state when executing a list of commands. Look at the private vars. Also, on a pure aesthetic level, I like the total decoupling of command data from actions in this case. In more complex cases, you could even have different execution strategies implemented in different executors (not needed here, of course; just noting it as an advantage of this approach versus virtual functions).

struct Executor {
	void operator()(const SelectChannel cmd);
	void operator()(const SetVolume cmd);
	void operator()(const SetStereoMode cmd);
	void operator()(const SetCrossfeedStrength cmd);
	void operator()(const SetReverbLevel cmd);
	void operator()(const SetChorusLevel cmd);

private:
	bool global_command = false;

	// If 'master_channel' is true, then the MASTER channel is selected,
	// otherwise 'channel' points to the selected non-master channel.
	bool master_channel = false;

	std::shared_ptr<MixerChannel> channel = {};
};

However, std::variant avoids having to heap allocate every Command and also avoids the virtual function overhead. So my initial assessment is the opposite. It seems a bit worse syntactically but probably has better performance.

Yeah, performance is absolutely a non-issue here, that wasn't even a consideration. We're only dealing with a handful (less than say 20) mixer commands on each MIXER command invocation. There are only a few (or zero) MIXER command invocations typically in the autoexec section of a config, or users execute MIXER commands manually several tens of seconds apart. No tight loops, no tens or hunders of thousands of commands being continuously evaluated, so maintainability trumps everything in this case.

However, for my OSD work, I will also need a similar command pattern, but that will need to be efficient as thousands of draw commands will be evaluated per-frame at the FPS rate. But even in that case, I'd measure the performance impact of this, but you're saying std::variant is actually preferable for performance reasons, so that's something I should remember then.

Overall, I don't hate it. I think you could do exactly the same thing with a tagged union and a switch statement.

A nice property of the Executor is that if you forget to define an operator() for a variant, then you'll get compilation errors. Even if you use a tagged union with proper enum classes, you'll only get "soft" exhaustiveness check warnings if you miss a few cases in your switch blocks I believe? Not such a big issue in this case where the variants and their executor are defined in the same file, but in bigger projects where the commands are executed in multiple ways by multiple executors in multiple places throughout the codebase, the tagged union approach can become rather brittle I think. Overall, I like hard compile-time checks whenever I can take them.

But if you like the syntax of std::variant better then go for it.

There's one more thing as well which I mentioned, namely that I like to use std::variant as a poor man's Either (or Result) type. Look at these:

std::variant<Error, std::queue<Command>> ParseCommands(...)

static std::variant<Error, Command> parse_volume_command(const std::string& s,
                                                         const std::string& channel_name)

static std::variant<Error, Command> parse_reverb_command(const std::string& s,
                                                         const std::string& channel_name)

What I'm "simulating" here is Scala's Either type which is super handy for propagating either a result of type R, or an error type E as a single self-contained unit from functions. So you define it as Either[E, R], then upstream you can make decisions whether it's a "left" or "right" outcome. Sometimes people use a renamed variant of this called Result, where the "left" side is the error type, and the "right side is the success type.

Without this, we're back to the old clunky way of using an "out type" for the actual error, something like this:

static std::option<Command> parse_volume_command(const std::string& s,
                                                         const std::string& channel_name, Error& out_error)

Sure, that works, but I find the std::variant return types nicer and more descriptive. It's a bit boilerplat-y at the call site, but not overly so:

const auto result = parse_crossfeed_command(arg, curr_channel_name);

if (auto cmd = std::get_if<Command>(&result); cmd) {
	commands.emplace(*cmd);
	++curr_channel_command_count;
} else {
	return std::get<Error>(result);
}

The clunky option with the out param would look like this. You don't need to do the std::get_if<T> and std::get<E> parts, true, but you need a mutable var for the error out var... which gets initialised with... something 😅 I kinda borderline prefer the std::variant version because it's more "correct", but like I said, if enough people hate the extra verbosity then I'm gonna revert back to the clunky out var way 😄

Error err = {};
if (auto result = parse_crossfeed_command(arg, curr_channel_name, err); result) {
	commands.emplace(*result);
	++curr_channel_command_count;
} else {
	return err;
}

@weirddan455

weirddan455 commented Oct 7, 2023 •

Copy link
Copy Markdown
Collaborator

However, for my OSD work, I will also need a similar command pattern, but that will need to be efficient as thousands of draw commands will be evaluated per-frame at the FPS rate. But even in that case, I'd measure the performance impact of this, but you're saying std::variant is actually preferable for performance reasons, so that's something I should remember then.

Yeah, measuring is the only way to be sure when it comes to performance. I could be wrong here but I think you would want to avoid doing thousands of heap allocations per frame if you can. Also, virtual functions in C++ are a bit worse than a normal function pointer because you have to take a double indirection through the vtable.

There's one more thing as well which I mentioned, namely that I like to use std::variant as a poor man's Either (or Result) type. Look at these:

I saw those for error handling. I don't love it but there's also not really a better option. I'd prefer std::optional if you only need to know success or fail but if you need to return a specific error code, it gets ugly. If you can't add a field to the return struct (which you can't really because Command is itself a typedef to std::variant), it's either out parameters or doing something like returning nullptr and setting a global errno type variable.

So std::variant might actually be the least bad option for functions that can fail with specific error codes.

An AudioFrame is 4-byte long so passing it by value is the most
efficient.
Mixer channel settings are now persisted in a map by their name whenever
a channel gets destroyed or added. This is necessary to make channel
settings "survive" removing an audio device and adding it back later, or
special scenarios such as changing the `sbtype` setting which always
deletes and immediately recreates the SB channel plus optionally the CMS
and OPL channels.
This warning is raised when the handling of two different exception
types is identical. This a fairly low value warning that doesn't
accomplish much, but it creates unnecessary warnings when we just "do
nothing" for multiple different exception types.

Details:
https://pvs-studio.com/en/docs/warnings/v2010/
- Clamping was removed as it encouraged loose parsing and error
  reporting which was a source for bugs and unexpected behaviour.

- Same goes for lenient parsing (e.g. allowing extra non-numeric
  characters after the numbers). Number parsing is now strict, no extra
  characters are allowed at the end.

- Specific functions that were not generally useful have been removed
  (e.g. 'parse_prefixed_percentage').

- Number parsing function names have been normalised for consistency.
- Rebuild the MIXER command for testability and add extensive unit
  tests.

- Make command parsing strict; previously, the mixer silently accepted
  all sort of invalid input and it wasn't clear which commands were
  applied and which were ignored.

- Mixer command invocations are now "transactional"; either all commands
  are applied (if no errors), or none at all (if there is at least one
  error).

- Display helpful error messages to guide the user to correct their
  mistakes.

- Rework the 'crossfeed' setting; now it uses preset names as the
  'chorus' setting. Setting global crossfeed via 'x<NUMBER>` has been
  deprecated as it was unsupportable in a sane and consistent way.

- Improve the help text of the MIXER command.
@johnnovak

Copy link
Copy Markdown
Member Author

It would be nice to have it rebased and conflicts solved - yesterday another batch of MIXER fixes were merged, it would be best to test both changes together.

Done.

Comment thread src/dos/program_mixer.cpp Resolved
@FeralChild64

Copy link
Copy Markdown
Contributor

I played a little with the command, just one minor remark from my side.

@johnnovak

Copy link
Copy Markdown
Member Author

Thanks @kcgen and @FeralChild64 for the review. Merge time 😎

@johnnovak
johnnovak merged commit f861d58 into main Oct 25, 2023
@kcgen

kcgen commented Oct 26, 2023

Copy link
Copy Markdown
Contributor

@johnnovak -> can you check:

lpt_dac = disney, then see if mixer disney 50 works?

Getting an 'invalid command' on my side:

2023-10-26_00-33

@johnnovak

johnnovak commented Oct 26, 2023 •

Copy link
Copy Markdown
Member Author

@johnnovak -> can you check:

lpt_dac = disney, then see if mixer disney 50 works?

Getting an 'invalid command' on my side:

2023-10-26_00-33

Confimed @kcgen, it's a bug. Started debugging it, maybe I'll have time to finish it tomorrow and raise a fix PR.

Update: It's rather subtle, please wait until I come up with a fix.

@kcgen
kcgen deleted the jn/mixer-fixes-5 branch October 27, 2023 15:02
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

audio Audio related issues or enhancements bug Something isn't working enhancement New feature or enhancement of existing features

Projects

No open projects
Status: Done

Development

Successfully merging this pull request may close these issues.

Preserve mixer settings per device when changing 'mididevice' between fluidsynth/mt-32/...

4 participants