Skip to content

9441 smoother playhead - #9613

Merged
saintmatthieu merged 20 commits into
audacity:masterfrom
saintmatthieu:9441-smoother-playhead
Oct 24, 2025
Merged

saintmatthieu merged 20 commits into
audacity:masterfrom
saintmatthieu:9441-smoother-playhead

Conversation

@saintmatthieu

@saintmatthieu saintmatthieu commented Oct 8, 2025 •

Copy link
Copy Markdown
Contributor

Resolves: #9441

  • I signed CLA
  • The title of the pull request describes an issue it addresses
  • If changes are extensive, then there is a sequence of easily reviewable commits
  • Each commit's message describes its purpose and effects
  • There are no behavior changes unnecessary for the stated purpose of the PR

Recommended:

  • Each commit compiles and runs on my machine without known undesirable changes of behavior

QA:

  • Position of cursor is well synchronized with what is played through the speakers (tip: import a rhythm track from Audacity 3)
  • Buffer length in Audio settings can be set to a very large value (e.g. 999ms) and the cursor is still well synchronized.
  • Robust when pausing/playing/pausing/... in quick successions
  • Also works for stereo meters
  • Works for different device types (MME, Wasapi, CoreAudio, etc.)
  • Autobot test cases have been run

@saintmatthieu
saintmatthieu force-pushed the 9441-smoother-playhead branch 2 times, most recently from f6fd946 to fecf23f Compare October 9, 2025 09:40
@saintmatthieu
saintmatthieu marked this pull request as ready for review October 9, 2025 09:41
@luapmartin
luapmartin self-requested a review October 9, 2025 16:20
Comment thread au3/libraries/lib-audio-io/AudioIO.h Outdated
@@ -400,6 +402,7 @@ class AUDIO_IO_API AudioIoCallback /* not final */ : public AudioIOBase
void PurgeAfterPause(unsigned long framesPerBuffer, float** sampleBuffer);

std::atomic<bool> mPurgeIsNeeded{ false };
bool mProjectSamplesReachedDeviceThread { false };

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

don't we need atomic here?

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'd tend to say it's not necessary, since there's only one writer and one reader and I can't see how the compiler could introduce any reordering when optimizing, but I'm not 100% sure. You're right, let's stay on the safe side.

constexpr size_t TimeQueueGrainSize = 2000;
// This can become a bottleneck to the update rate of the play cursor position.
// Let's set this to 10ms at 48kHz. Even at 16kHz, that'd be a refresh rate of 33fps.
constexpr size_t TimeQueueGrainSize = 480;

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

can't we set that dynamically based on sample rate? to aim for fixed time (same feel) whatever sample rate we are using ? 16ms would provide ~ 60fps and 10ms be higher than 90fps

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 looked a little bit into this. Changing this guy to a variable would require some work that I think overweights the benefits. I'd rather move on quicker to something else.

@saintmatthieu
saintmatthieu force-pushed the 9441-smoother-playhead branch 2 times, most recently from e7634f0 to e7a01e5 Compare October 13, 2025 22:10
@luapmartin

Copy link
Copy Markdown
Contributor

@saintmatthieu could you also check if this PR will influence this behaviour: #8636
it could be related with : correct position update of the playhead on stop/pause maybe we are missing an update when the steams is interrupted.

@saintmatthieu saintmatthieu self-assigned this Oct 17, 2025
@saintmatthieu
saintmatthieu force-pushed the 9441-smoother-playhead branch 3 times, most recently from d6bd609 to dab1fac Compare October 18, 2025 06:44
@luapmartin

Copy link
Copy Markdown
Contributor

I did a first pass and I still see the problems we discussed the other day about the naming.

Latency should be bufferDurationInMs or something that explain what it measure instead of what it feels like or produce to the end user in a specific use case.

also I saw lot of when that should be more descriptive of what they represent

and the globals included from framework is something we changed ?

@luapmartin

Copy link
Copy Markdown
Contributor

I will do another pass tomorrow, could you please rebase ? thanks

, frames(frm)
, nChannels(nCh)
, firstSampleTimestamp(firstTs)
, when(when_)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

this when need a bit more love, a better name is due I think, let's try asking that by using the 4 other Ws

what is it, or what is the reason to have it here?
what does it stores/represent?
why do we need it?
who responsible or using/needs it?

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.

Agreed.
PortAudio has the interesting equivalent of outputBufferDacTime. I used simply dacTime, with the context it's not hard to grasp that it's the time when the DAC starts processing the first buf sample.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

here we store the time at which we are creating that buffer + the duration of the buffer

we are neglecting the extra time that is spent to move things around and have an estimate of the time it will be played.

We still have the problem if the framesPerBuffer isn't met (in the FillOutputBuffer see toGet variable) and we have double callback the timings will be off

we will be sending twice to the input vu meters

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.

we store the time at which we are creating that buffer

I do neglect the time the execution of the entire hardware callback takes, yes, and I don't think we should worry about this. If we profile this callback's duration I guess it wouldn't take more than a ms or two, which is negligible for our purpose. We are also neglecting other things, like the time it takes for the acoustic wave to reach the user's ear, the time it takes for the screen to actually render the image Qt hands over to it, or other sources of latency on either the audio or video side of things. I think these approximations could only hurt the result very marginally and this is the best we can reasonably do anyway.

I would start being concerned if this PR has logical mistakes or approximations that could yield an error of more than 20ms. I think anything under that would be very hard for a user to distinguish.

We still have the problem if the framesPerBuffer isn't met

I responded to this, but probably you didn't have this response at the time of writing.

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.

we will be sending twice to the input vu meters

Not sure I understand: because of that len < framesPerBuffer concern you had?

namespace au::playback {
class PlaybackPositionTimer : public QQuickItem, public muse::async::Asyncable
{
muse::Inject<IPlayback> playback;

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

could you please inject and use the PlaybackState instead

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

I mean getting it from the GlobalContext

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 hadn't occurred to me. Your suggestion got me enthusiastic, but trying I realize that I also need to call updatePlaybackPosition on IPlayer anyway, so I don't think it's going to save me code in the end.

Comment thread src/playback/internal/au3/au3player.h Resolved
Comment thread src/playback/internal/au3/au3player.cpp Resolved
virtual ~IMeterSender() = default;
virtual void push(uint8_t channel, const InterleavedSampleData& sampleData, TrackId = TrackId { MASTER_TRACK_ID }) = 0;
virtual void start() = 0;
virtual void start(double sampleRate) = 0;

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

from API standpoint I don't think passing a sampleRate to start method make much sense, why not a configure or setup or like before setSampleRate then a start()/stop() method, unless I did not understood, please explain, thanks

Additional question does those timers can update to renegotiated sample rates during their usage?

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 do find some sense: "We start a new playback session, I need to know what sample rate it uses." At least then the implementation doesn't have to verify that a setup or configure method was called between the last stop and the new start.

To the additional question: sample rate doesn't change during a playout session.

@luapmartin luapmartin Oct 23, 2025 •

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

then you have to always send the sampleRate via the start method when you start/stop/start/stop... even if sampleRate hasn't changed ?

sampleRate should be sent only when first setup and when its changing so we could start/stop/start/stop ...

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.

sampleRate should be sent only when first setup and when its changing so we could start/stop/start/stop ...

Like I said, at least implementation with the current API doesn't have to verify that a setup or configure method was called between the last stop and the new start. And whether there was a sample-rate change or not between two playback sessions shouldn't be a concern. We do recalculate everything in AudioIO.cpp when opening a new stream: introducing checks whether it changed since the previous session would be unnecessarily cumbersome. I think this applies here too.

@luapmartin luapmartin Oct 23, 2025 •

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

what about setupAndStart(double sampleRate) (you can choose to have inner setup(double sampleRate) (or setSampleRate(double sampleRate)) and start() methods or not)
just making 1 step clearer the intent of this method

Comment on lines +2738 to +2744
if (n == 0) {
using namespace std::chrono;
const auto now = steady_clock::now();
const auto startTime = now + milliseconds(static_cast<int>(mHardwarePlaybackLatencyFrames * 1000.0 / mRate));
mAudioDeliveryQueue.Put({ startTime, static_cast<int>(len) });
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

startTime might not be the best describing name here, why not estimatedFirstBufferCallbackTime of something like that ?

if I understand correctly each time you fill the output buffer you try estimate when the first callback will be sending the current buffer out, producing audio output to the user right?

I think there is an issue as the toGet might be smaller than the framesPerBuffer if at leat one of the buffer in the mPlaybackBuffers doesn't have enough frame ready (see GetCommonlyReadyPlayback()) so we might have more than one callback to fill the output buffer

so maybe we should put into the mAudioDeliveryQueue only the number of frames that we were able to get from the current mPlaybackBuffers

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

actually I think that while at it a bit of cleanup would be in order for those two variables toGet and len aren't best names why not currentlyAvailableFramesAcrossBuffers and numberOfRetrievedFrames respectively or something that would explicitly let the reader understand what those two are about and how to interpret the logic involved with them

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.

if I understand correctly each time you fill the output buffer you try estimate when the first callback will be sending the current buffer out, producing audio output to the user right?

Not sure what you mean with "first callback", but beside this, yes, this is my intention: when the first of these len samples will reach DAC. In that sense, I mean "start time" as "start time of that ADC conversion".
Yesterday I replaced when with dacTime in the AudioDelivery struct and I overlooked this place.

I think there is an issue as the toGet might be smaller than the framesPerBuffer

I don't think this is a normal case: a few lines above, there is the if (len < framesPerBuffer) { condition, with the comment saying that it can only happen

  • at the end of the playback (probably then nothing any user would notice?)
  • if the audio thread is slower than the hardware thread and there are underruns. But this is the exception and there'd be audio hick-ups anyway, I don't think trying to improve the play cursor position in this case is worthwhile.

so maybe we should put into the mAudioDeliveryQueue only the number of frames that we were able to get from the current mPlaybackBuffers

Isn't len exactly this? See len = mPlaybackBuffers[n]->Get(

why not currentlyAvailableFramesAcrossBuffers and numberOfRetrievedFrames respectively

Good names, I'll address.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

thanks for renaming and all other edits, now we reach the point where I could maybe express clearer my thoughts

we have:

using namespace std::chrono;
const auto now = steady_clock::now();
const auto adcTime = now + milliseconds(static_cast<int>(mHardwarePlaybackLatencyMs));
mAudioCallbackInfoQueue.Put({ adcTime, static_cast<int>(numberOfRetrievedFrames) });

what I don't like here is that the adcTime is not always when this numberOfRetrievedFrames will be sent,

what we know for sure at that time of the callback is that the time of the callback is now() and we have sample rate X and we have numberOfRetrievedFrames, apart from that the rest is uncertain info, that's why I would prefer pack this info into a useful struct and push it to a ringbuffer and on another thread compute the timings etc. or whatever but use the thrustful data only somehow

Comment on lines 2794 to 2797
// Update the position seen by drawing code
mPlaybackSchedule.SetSequenceTime(
mPlaybackSchedule.mTimeQueue.Consumer(mMaxFramesOutput, mRate));
mPlaybackSchedule.mTimeQueue.Consumer(framesPerBuffer, mRate));
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

that make more sense indeed

only problem I see is that this is triggered by the player from a Qt trigger.

I do believe that the playback position updates should be fully isolated on the playback side (AudioIO...) and each time a new buffer is "sent" outside we should accordingly notify and we would then update the visuals accordingly knowing when the buffer has been sent out and what was it size and the sample rate is sufficient to animate a playhead

I am a bit confused as how this as become apparently so complex, sorry for not fully following the logic here but we might be overcomplicating things

@saintmatthieu saintmatthieu Oct 23, 2025 •

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.

each time a new buffer is "sent" outside we should accordingly notify and we would then update the visuals accordingly knowing when the buffer has been sent out and what was it size and the sample rate is sufficient to animate a playhead

This is the way it's currently working on master. The problem is that it conditions the visual update rate of the play cursor to the callback rate of the soundcard, making the animation everything but smooth for buffer-size settings more than 25ms (our default is 100ms at the moment).

Now a dedicated timer (obviously on the main thread) is updating the playback position at whatever rate it pleases. In turn, these updates have to call UpdateTimePosition, which very nicely abstracts away the problem of looping (work from @Paul-Licameli some years ago, I believe, thanks for that).

You expressed here that you didn't feel comfortable with Au3Player being responsible for maintaining the cursor's position. Would you feel better if the AudioEngine were making these calls? I suggested we postpone that refactoring, but I'm open to giving it a go now.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

"yes, I like UI stupid to just repaint updated states as much as possible" a kind of rule of thumb for me, let's see what we can do (we could have a call to decide if now or later (or never XD))

Comment thread au3/libraries/lib-audio-io/AudioIO.cpp Resolved
Comment thread au3/libraries/lib-audio-io/AudioIO.cpp Resolved
Comment thread au3/libraries/lib-audio-io/AudioIO.cpp Resolved
Comment thread au3/libraries/lib-audio-io/AudioIO.cpp Resolved
Comment thread au3/libraries/lib-audio-io/AudioIO.cpp Outdated
Comment on lines +3211 to +3213
const std::chrono::milliseconds hardwareLatencyMs{ static_cast<int>(mHardwarePlaybackLatencyFrames * 1000.0 / mRate) };
const auto levelDisplayTime = std::chrono::steady_clock::now() + hardwareLatencyMs;

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

mHardwarePlaybackLatencyFrames is obtained from latency in seconds we should be packing the PaStreamInfo (in a custom struct with the sent to output timestamp) as it contain the used sample rate and PA outputLatency (and input)
then we could directly use that PA info instead of calculating and re-calculating something that PA tell us directly

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

            mHardwarePlaybackLatencyFrames = lrint(outputLatency * mRate);

we might better use the stream->sampleRate when doing that to have accurate size

also the mHardwarePlaybackLatencyFrames is really only needed in the AllocateBuffers method and there we could be using the PA info struct

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.

we might better use the stream->sampleRate when doing that to have accurate size

Agreed, will address.

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.

About the outputLatency : why not, will also address.

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.

also the mHardwarePlaybackLatencyFrames is really only needed in the AllocateBuffers method and there we could be using the PA info struct

Calculated in StartPortAudioStream and then used only in AllocateBuffers, correct.
So IIUC you suggest that we make a copy of the PA info struct ? Would work as well, but this starts feeling like not-so-important refactoring.

Comment thread au3/libraries/lib-audio-io/AudioIO.h Outdated
Comment on lines +190 to +195
struct AudioDelivery {
std::chrono::steady_clock::time_point startTime;
int numSamples = 0;
};
using AudioDeliveryQueue = LockFreeQueue<AudioDelivery>;

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

please add the sample rate

also I think that this is a struct that is to be used "on a callback" right?

we might want to callback keyword somewhere to translate the fact that this is a per callback payload gathering all together

AudioDelivery is not so evocative could try AudioCallbackPayload or AudioCallbackPayloadInfo or something like that

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.

please add the sample rate

Why, if it is guaranteed to stay the same across all deliveries of one session?

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.

AudioCallbackPayloadInfo works for me.

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.

... although: Just AudioCallbackInfo would be enough, I think, and AudioCallbackPayloadInfo makes things become a bit lengthy: GetAudioCallbackPayloadInfoQueue()

Comment thread src/au3wrap/internal/au3audiometer.cpp Outdated
Comment on lines +129 to +131
m_meterUpdateTimer->start();
m_stopTimer->stop();
m_sampleRate = sampleRate;

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

maybe we should stop the stop timer first ?

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 this this wouldn't make a difference: QTimer::stop is executed synchronously (no more callback), while QTimer::start posts an event for later.
But the narrative would be clearer, so ok.

Comment thread src/au3wrap/internal/au3audiometer.h Outdated
QTimer m_meterUpdateTimer;
QTimer m_stopTimer;
const std::unique_ptr<ITimer> m_meterUpdateTimer;
const std::unique_ptr<ITimer> m_stopTimer;

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

stop timer could be renamed decay or let ring timer ? as we are using this to decay the signal activity

or rename them as running / stopping (maybe with signal or timer or acitvity in the name) or something that would let reader know those are to be used in tandem as one when updating the activity and the other one only when being stopping the activity

actually we might need a starting Activity timer too to fake signal ramping up to avoid user delay when turning on audio engine see #8917 (comment)

we could think as those timers as easeIn easeOut smoothing signal flow

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 like m_runningTimer and m_stoppingTimer :thumbs-up:

Comment on lines +1 to +21
/*
* Audacity: A Digital Audio Editor
*/
#pragma once

#include <chrono>
#include <functional>

namespace au {
class ITimer
{
public:
virtual ~ITimer() = default;

virtual void setCallback(std::function<void()>) = 0;
virtual void setInterval(const std::chrono::milliseconds&) = 0;
virtual void setSingleShot(bool) = 0;
virtual void start() = 0;
virtual void stop() = 0;
};
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

new module auaudio maybe it should be auutility right or something where a timer tool would make sense, wdyt?

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

autools
auutils

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.

Maybe. I actually was planning a follow-up commit to extract the IMeter API and implementation away from au3wrap. Then, the timer was just an internal thing and didn't need to be exposed, the only API directly under auaudio would have been iaudiometer, hence the choice of auaudio.
"audio" is very general, on the other hand, I'd be open to something more specific.

@luapmartin luapmartin left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

let's create those escalation tickets

@luapmartin

Copy link
Copy Markdown
Contributor

last added commit might be fixing : #8810

@saintmatthieu
saintmatthieu force-pushed the 9441-smoother-playhead branch from 78fa3d5 to 568e46b Compare October 24, 2025 11:35
@saintmatthieu
saintmatthieu merged commit 23a0e74 into audacity:master Oct 24, 2025
@saintmatthieu saintmatthieu mentioned this pull request Nov 3, 2025
6 of 7 tasks
saintmatthieu added a commit that referenced this pull request Nov 5, 2025
The fact that `IMeterSender` is an Au3 API has been propagating Au3
implementations and includes in Au4 modules.
Now we have an adapter that implements `IMeterSender` and whose internal
object is an Au4-only `IAudioMeter`, whose implementation is
Au3-agnostic.
To make this possible without duplicating types, `audiotypes.h` was also
migrated from `au3audio` to `auaudio`. This change has its own commit.

Follow-up on #9613

- [x] I signed [CLA](https://www.audacityteam.org/cla/)
- [x] The title of the pull request describes an issue it addresses
- [x] If changes are extensive, then there is a sequence of easily
reviewable commits
- [x] Each commit's message describes its purpose and effects
- [x] There are no behavior changes unnecessary for the stated purpose
of the PR

Recommended:
- [x] Each commit compiles and runs on my machine without known
undesirable changes of behavior

QA:

- [ ] Autobot test cases have been run
@saintmatthieu
saintmatthieu deleted the 9441-smoother-playhead branch August 28, 2026 11:11
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.

Smoother playhead Cursor visual glitch when playback is active (Windows)

2 participants