Skip to content

filter/StartDelayFilter: New filter plugin - #2609

Open
borine wants to merge 2 commits into
MusicPlayerDaemon:masterfrom
borine:filter-startdelay
Open

borine wants to merge 2 commits into
MusicPlayerDaemon:masterfrom
borine:filter-startdelay

Conversation

@borine

@borine borine commented Oct 30, 2026

Copy link
Copy Markdown
Contributor

A filter to insert a short prelude of silence or low-level noise at the start of a stream.

Some devices drop samples at the start of playback as they perform a handshake protocol or power up idle circuits; and some require some non-zero samples before they begin their handshake. This issue is known to affect some HDMI devices, for example.

Use this filter to ensure the samples dropped are not part of the first song.

Closes #2588
Closes #1312

@MaxKellermann

Copy link
Copy Markdown
Member

Automated Claude review follows (not verified by me, I don't have time right now - but apparently you don't have access to LLM reviews):

Bugs

  1. Reset() leaves initial_data behind, so stale audio is replayed after a seek or skip.
  • FilterPCM() keeps a reference to the caller's buffer (initial_data = src) and returns it later from ReadMore(). Reset() only resets delay_bytes_read, and
    only when on_seek is set; initial_data is never cleared.
  • Sequence:
    a. The whole delay is emitted.
    b. The player cancels (seek, stop, another song) before ReadMore() has returned initial_data.
    c. The next FilterPCM() returns the new data.
    d. The following ReadMore() then returns the old chunk's data, after AudioOutputSource::Cancel() has already released that chunk.
  • With the defaults, 1000 ms at 48 kHz/16-bit/stereo is 192000 bytes, less than the 300 KiB buffer. So the entire delay is a single chunk, and any seek or
    skip during the first second hits this.
  • I confirmed it with a small harness: after Reset(), ReadMore() returns chunk 1's (overwritten) bytes after chunk 2.
  • Fix: clear initial_data in Reset(), unconditionally.
  1. DSD with noise_level > 0 gets no delay at all.
  • PreparedStartDelayFilter::Open() falls back to NullFilter when the format can't have noise and level > 0.
  • The documentation says DSD gets silence instead. Using level = 0 for DSD (instead of NullFilter) would match the docs.
  1. on_seek isn't really "on seek". Filter::Reset() is called from AudioOutputSource::Cancel(), which happens on seek, stop, and switching songs (e.g. play
    N), not only on seek. The option name and documentation should say so, or the option should be renamed.

  2. The filter relies on its input staying valid until ReadMore() returns empty.

  • That's true with today's callers (AudioOutputSource keeps the chunk, and TwoFilters drains the second filter's ReadMore() before touching the first).
  • But the Filter API in Filter.hxx doesn't promise it.
  • Either document this guarantee in Filter.hxx (it's a reasonable rule) or don't depend on it.

Smaller issues

  • Configuration: delay_ms should use MPD's duration syntax via ConfigBlock::GetDuration() (e.g. delay "1 s"), like other options.
  • Memory: each filter instance holds a fixed std::array of about 300 KiB, even for silence or short delays. It could be sized as min(delay_bytes, cap) and
    allocated dynamically.
  • Comments that don't match the code:
    • The 8-bit noise amplitude is 1/128 = −42.1 dBFS, not −48.1.
    • The noise isn't "a square wave of randomly varying wavelength"; the sign is random for every frame.
    • The S24 sign-extension | ~0xffffff is redundant, since -amplitude is already sign-extended.
    • CreateNoise()'s doc comment describes a format parameter that doesn't exist.
  • Style:
    • Use #pragma once instead of the old include guard.
    • Use MPD's constructor initializer-list indentation.
    • Add the missing , and includes, and remove the unused .
    • initial_data() doesn't need explicit initialization, and the UNDEFINED check in FormatSupported() can't trigger.
  • Missing: a NEWS line, and a test, e.g. with test/run_filter or a small gtest like my harness.

Design question for the author

The delay is tied to the filter being reopened (AudioOutputSource::Open(), on output open or format change) and optionally to Reset(), not to the audio
device actually being opened. Mostly they coincide. But the real problem, the device dropping samples while it starts up, would be matched more directly by
an output-level option that sends silence right after opening the PCM device, e.g. in the ALSA output.

@borine

borine commented Nov 2, 2026

Copy link
Copy Markdown
Contributor Author

Thanks for posting the Clause review, it was very helpful.

Commit ebe10e4 fixes the bugs and implements most of the suggestions reported in the Claude review, with the exception of the following items:

copying the src data in FilterPCM()
This can be implemented easily using AllocatedBuffer, but it seems wasteful of resources when this is not (currently) necessary. Before making this change I would
like your personal opinion on whether it is the intent of the Filter interface that this data should be copied?

config ConfigBlock::GetDuration()
The GetDuration method only handles integer values in seconds.
StartDelayFilter requires sub-second resolution for its delay, and I think using an integer value in milliseconds is the most convenient syntax from a user's point of view. I think that extending the ConfigBlock interface to handle durations expressed as milliseconds is orthogonal to this feature request and if deemed necessary belongs in a separate PR.

"Add the missing , and includes, and remove the unused ."
I have no idea what that means. I have revised the #include directives, guided by iwyu.

Missing test
This feature can be tested with run_filter; what is required to be added to the PR to satisfy this request?

"design question for the author"
I chose to implement this feature as a filter in order that a user can choose to use it with any audio output type, wherever they find it to be helpful.

There is a patch by @jkhabe included in #2588 (comment) which implements a start delay directly in the ALSA output plugin. So if you prefer that approach I will close this PR and perhaps @jkhabe or any other interested party will create a new PR based on that.

@MaxKellermann

Copy link
Copy Markdown
Member

Commit ebe10e4 fixes the bugs and implements most of the suggestions reported in the Claude review, with the exception of the following items:

I prefer amending the existing commit and force-pushing the PR branch. Tools like stgit can help with that. I want a PR branch to have properly separated commits, one commit for each aspect that gets changed. For a new plugin, that's just one commit, but if you need to do refactoring (e.g. sub-second support for ParseDuration()), make that a separate commit. But don't push fixup commits for unmerged commits.

copying the src data in FilterPCM() This can be implemented easily using AllocatedBuffer, but it seems wasteful of resources when this is not (currently) necessary. Before making this change I would like your personal opinion on whether it is the intent of the Filter interface that this data should be copied?

No, it should be zero-copy as much as possible.

config ConfigBlock::GetDuration() The GetDuration method only handles integer values in seconds. StartDelayFilter requires sub-second resolution for its delay, and I think using an integer value in milliseconds is the most convenient syntax from a user's point of view. I think that extending the ConfigBlock interface to handle durations expressed as milliseconds is orthogonal to this feature request and if deemed necessary belongs in a separate PR.

That would be a very useful feature to have, and indeed there's a TODO comment for exactly that. You can do this within this PR as a separate commit.

"Add the missing , and includes, and remove the unused ." I have no idea what that means. I have revised the #include directives, guided by iwyu.

GitHub ate these XML tags when I copy'n'pasted it here:

    - Add the missing <climits>, <cstdint> and <span> includes, and remove the unused <memory>.

Missing test This feature can be tested with run_filter; what is required to be added to the PR to satisfy this request?

Currently, there are no automated unit tests for filter plugins, but it would be good to have one. LLMs like to ask for unit tests when you ask them for a code review, and of course it's a good idea, but I'd accept a PR even if there's no unit test (as long as my own filter plugins don't lead by example).

"design question for the author" I chose to implement this feature as a filter in order that a user can choose to use it with any audio output type, wherever they find it to be helpful.

There is a patch by @jkhabe included in #2588 (comment) which implements a start delay directly in the ALSA output plugin. So if you prefer that approach I will close this PR and perhaps @jkhabe or any other interested party will create a new PR based on that.

I, too, found this comment hard to understand, so I asked Claude for a clarification; but first on your question where to put it: I think your idea to implement a filter plugin is good. It's abstract code that can be used in all plugins. The biggest problem here is that MPD's filters are difficult for users to configure. The configuration syntax is cumbersome, and I never put any effort in simplifying it.
You may be hitting limitations on the filter API, which Claude found as well, so here's the reply Claude gave me, which I did not fully read, just meat-proxying over to you:


The comment is about when the PR's silence gets inserted, compared with when it is actually needed.

What the device needs. An HDMI receiver or DAC drops samples when the audio stream starts from the device's point of view. In ALSA terms, that's the first
data written after:

  • the PCM device is opened;
  • snd_pcm_drop() stops the stream, which MPD's AlsaOutput::Cancel() does on seek, stop and song skips;
  • resuming from snd_pcm_pause(), if the receiver went idle while paused.

What the PR's filter reacts to. A filter can't see the device. It only sees its own lifetime:

  • Opening: AudioOutputSource::Open() opens the filter whenever the output's source is opened, and also whenever the input audio format changes between songs.
  • Resetting: Reset() is called from AudioOutputSource::Cancel() (seek, stop, skip). This only inserts silence when on_seek is set.

So the filter infers "the stream (re)started" from these events, and they don't always match the device:

  1. Silence where none is needed. With a fixed output format such as format "48000:16:2", a song change from 44.1 kHz/16-bit to 96 kHz/24-bit changes the
    input format. AudioOutputSource::Open() then closes and reopens the filter, so the StartDelay filter inserts its full delay again (one second by default).
    But the device stays open, because InternalOpen2() only reopens it when the filter's output format changes, and here that format is fixed. The result is
    a one-second gap between two songs that should play gaplessly.
  2. No silence where it is needed. Resuming after a pause via snd_pcm_pause() reopens neither the device nor the filter, so the filter does nothing even if
    the receiver needs a new handshake. With on_seek no (the default), the same happens on seek, even though ALSA really did stop and restart the stream with
    snd_pcm_drop().
  3. Where they do match: at first playback, and after stop/play or a pause on a device that can't pause. In those cases InternalClose() closes both the device
    and the source, so both are reopened together. That's the case the PR was written for, which is why I wrote "mostly they coincide".

What I suggested instead. The output plugin knows exactly when it opens the device, drops the stream or resumes from pause. An ALSA output option, e.g.
start_silence "1 s", could write silence (or low-level noise) at exactly those moments, before the first real data. That gives silence precisely when the
device restarts, never between gapless songs, and no on_seek guessing. The ALSA plugin already has most of what this needs:

  • a period-sized silence buffer, which it writes on underruns;
  • the mirror-image option stop_dsd_silence ("play some silence before closing the output in DSD mode").

It would also be configured where it belongs, in the audio_output block, instead of a separate filter block plus filters in each output.

The trade-off: a filter works with every output plugin, while an output option would have to be added per plugin. Hence my question to the author: if #1312
and #2588 are only about ALSA/HDMI, the output option is the more precise fix. If other outputs (PipeWire, PulseAudio, WASAPI) show the same problem, there's
an argument for the generic filter, but then the format-change gap (case 1) and the pause case (case 2) should at least be documented.

@borine
borine force-pushed the filter-startdelay branch from ebe10e4 to 8b29d6a Compare November 3, 2026 11:20

@MaxKellermann MaxKellermann left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

First (human) look at the code.

Comment thread doc/plugins.rst Outdated
Comment on lines +981 to +983
If this option is set to *no* in combination with **always_on**
set to *yes* then the ALSA device remains opened (but not
running) after playback stops.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Changes to ALSA documentation doesn't belong in this commit

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

oops - this change wasn't meant for this branch. Will be removed in the next push.

Comment thread doc/plugins.rst Outdated
Comment on lines +1513 to +1514
* - **delay_ms MS**
- The delay time in milliseconds. The default delay is 1000 ms.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Should be delay "1000ms", as suggested by Claude.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This is on my todo list, I see it as a separate mini-project and will look at it when the other problems here have all been fixed.

Comment thread doc/plugins.rst Outdated
- Sets the loudness of the noise inserted during the delay, in
the range [0 - 255]. A value of 1 generates noise at -90.3 dBFS,
and 255 generates noise at -42.1 dBFS. Use the value 0 for
silence. The default value is 0. This option is ignored for DSD

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This seemingly arbitrary range confuses me. Why 255 and why does 255 mean -42.1 dBFS? Why does 1 mean -90.3 dBFS?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The range is arbitrary. There is no data available to indicate "correct" , "normal" or even "typical" values to be used here. The choice of [0-255] is simply so that the value fits in 8 bits. The mapping from "level" to dBFS is also arbitrary. Experiments with a small sample of affected systems indicated that approx -90dBFS was inaudible but effective at waking the device, so that guided the choice of lower bound. The actual values used are simply the result of using a simple bit-shift to convert "level" to amplitude. The algorithm and the documentation can all be changed if you have any thoughts on a more "logical" approach.

Comment thread doc/plugins.rst Outdated
silence. The default value is 0. This option is ignored for DSD
streams.
* - **on_reset yes|no**
- When yes, also delay the start when the filter is reset.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

A start cannot be delayed if nothing is started. This wording is confusing.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I will try to find better wording to describe this option in the next push.

Comment thread src/filter/plugins/StartDelayFilter.cxx Outdated
#include <utility>

/* To limit resource usage, the maximum delay buffer size is set to 300 KiB */
static constexpr std::size_t DELAY_BUFFER_MAX_SIZE = 300 * 1024;

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

= 300_KiB; is simpler and you don't need to repeat it in the comment.
see util/ByteSizes.hxx.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

changed in my next push

Comment thread src/filter/plugins/StartDelayFilter.cxx Outdated
if (level > 0)
CreateNoise(buffer_frames, level);
else
PcmSilence({ delay_buffer.data(), delay_buffer.size() }, format.format);

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

{ delay_buffer.data(), delay_buffer.size() } -> delay_buffer
Why so complicated?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Changed in the next push

Comment thread src/filter/plugins/StartDelayFilter.cxx Outdated
const bool negative = rng & 0x10000;

/* write the sample value to the byte array */
switch (out_audio_format.format) {

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Having the switch statement inside the loop will be very slow because it prevents both compiler and CPU from doing any optimizations.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I've rewritten the CreateNoise function using templates and std::range::generate() which should resolve this issue. I am currently testing this change and will push when finished.

Comment thread src/filter/plugins/StartDelayFilter.cxx Outdated
switch (out_audio_format.format) {
case SampleFormat::S8: {
const std::int8_t val = negative ? -amplitude : amplitude;
std::memcpy(dest, &val, sizeof(val));

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Invoking memcpy() for each single byte is also pretty slow...

Comment thread src/filter/plugins/StartDelayFilter.hxx Outdated
AllocatedArray<std::byte> delay_buffer;
std::span<const std::byte> initial_data;
std::size_t delay_bytes_read;
bool on_reset;

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Make fields const that will never be modified

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

done in the next push

Comment thread src/filter/plugins/StartDelayFilter.cxx Outdated
{
auto next_chunk_size = std::min(delay_bytes - delay_bytes_read, delay_buffer.size());
delay_bytes_read += next_chunk_size;
return std::span{delay_buffer.data(), next_chunk_size};

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

std::span{delay_buffer}.first(next_chunk_size) is simpler and more robust.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

done in the next push

@borine
borine force-pushed the filter-startdelay branch 2 times, most recently from 1296b8d to 0187149 Compare November 7, 2026 14:39
@borine

borine commented Nov 7, 2026

Copy link
Copy Markdown
Contributor Author

Changes in today's push:

  • Rename "delay_ms" as "delay"
  • Use FromBytesFloor() to cast the noise buffer span.

Issues still outstanding

  1. config time unit suffixes
    Needs proper specification. There are other sub-second settings such as:
    * sndio output buffer_time (milliseconds)
    * alsa output buffer_time (microseconds)
    * ffmpeg decoder analyzeduration (microseconds)

    None of those require the user to specify units, and none of them use
    `ConfigBlock::GetDuration()" to read the value from the config file. So
    why "should" the startdelay filter option be any different? Claude gives no
    rationale for that assertion.

    If support for time unit specification in the config file is required, then
    surely it needs to be done consistently across all affected settings. It is
    better done as a distinct PR where the requirements can be discussed.

  2. noise level
    Perhaps I should just remove the dBFS values from the documentation ?

@jkhabe

jkhabe commented Nov 7, 2026

Copy link
Copy Markdown

Considering that one of the primary purposes of this filter is to produce an inaudible signal that wakes sleeping audio hardware, I feel that documenting its amplitude is particularly relevant.

Personally, I think a comment along these lines of would be informative and useful to users:

noise_level: Noise amplitude from 0 (silence) to 255. A value of 1 corresponds to approximately −90.3 dBFS peak amplitude for 16-bit and higher PCM formats.

I'm still following your progress on this, and I appreciate all the work you're putting into it!

borine and others added 2 commits November 27, 2026 15:00
A filter to insert a short prelude of silence or low-level noise
at the start of a stream.

Some devices drop samples at the start of playback as they perform
a handshake protocol or power up idle circuits; and some require
some non-zero samples before they begin their handshake. This issue
is known to affect some HDMI devices, for example.

Use this filter to ensure the samples dropped are not part of the
first song.

Closes MusicPlayerDaemon#2588
Closes MusicPlayerDaemon#1312

Co-authored-by: @jkhabe <jkhaberland@gmail.com>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

ALSA/HDMI: beginning of manually started tracks clipped when PCM leaves RUNNING state Add Delay/Silence at Start of Tracks

3 participants