ALSA: usb-audio: Refactoring delay account code
The PCM delay accounting in USB-audio driver is a bit complex to
follow, and this is an attempt to improve the readability and provide
some potential fix.
Basically, the PCM position delay is calculated from two factors: the
in-flight data on URBs and the USB frame counter. For the playback
stream, we advance the hwptr already at submitting URBs. Those
"in-flight" data amount is now tracked, and this is used as the base
value for the PCM delay correction. The in-flight data is decreased
again at URB completion in return. For the capture stream, OTOH,
there is no in-flight data, hence the delay base is zero.
The USB frame counter is used in addition for correcting the current
position. The reference frame counter is updated at each submission
and receiving time, and the difference from the current counter value
is taken into account.
In this patch, each in-flight data bytes is recorded in the new
snd_usb_ctx.queued field, and the total in-flight amount is tracked in
snd_usb_substream.inflight_bytes field, as the replacement of
last_delay field.
Note that updating the hwptr after URB completion doesn't work for
PulseAudio who tries to scratch the buffer on the fly; USB-audio is
basically a double-buffer implementation, hence the scratching the
buffer can't work for the already submitted data. So we always update
hwptr beforehand. It's not ideal, but the delay account should give
enough correctness.
Link: https://lore.kernel.org/r/20210601162457.4877-4-tiwai@suse.de
Signed-off-by: Takashi Iwai <tiwai@suse.de>