From c0995612bab5d88e3d8865270f810da5d25a748d Mon Sep 17 00:00:00 2001 From: Henglie Date: Thu, 12 Nov 2026 16:27:41 +0800 Subject: [PATCH 1/2] Fix silent gaps when looping audio previews Restarting the DirectShow graph from MediaEnded leaves a 100-250 ms silent gap at each loop. For audio-only files with looping enabled, play an NAudio MediaFoundationReader through a sample-accurate looping wave provider instead, so the next iteration starts without reopening or seeking the graph. Keep the DirectShow path for video and for audio formats that Media Foundation cannot decode. If looping is enabled during playback, switch to the NAudio player at the current position. Fixes #2021 --- .../AudioTrack/AudioFilePlayer.cs | 233 ++++++++++++++++ .../QuickLook.Plugin.VideoViewer.csproj | 1 + .../ViewerPanel.xaml | 10 +- .../ViewerPanel.xaml.cs | 253 +++++++++++++++++- 4 files changed, 481 insertions(+), 16 deletions(-) create mode 100644 QuickLook.Plugin/QuickLook.Plugin.VideoViewer/AudioTrack/AudioFilePlayer.cs diff --git a/QuickLook.Plugin/QuickLook.Plugin.VideoViewer/AudioTrack/AudioFilePlayer.cs b/QuickLook.Plugin/QuickLook.Plugin.VideoViewer/AudioTrack/AudioFilePlayer.cs new file mode 100644 index 000000000..6583b6a13 --- /dev/null +++ b/QuickLook.Plugin/QuickLook.Plugin.VideoViewer/AudioTrack/AudioFilePlayer.cs @@ -0,0 +1,233 @@ +// Copyright © 2017-2026 QL-Win Contributors +// +// This file is part of QuickLook program. +// +// This program is free software: you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. +// +// You should have received a copy of the GNU General Public License +// along with this program. If not, see . + +using NAudio.Wave; +using System; +using System.Diagnostics; + +namespace QuickLook.Plugin.VideoViewer.AudioTrack; + +internal sealed class AudioFilePlayer : IDisposable +{ + private readonly object _sync = new(); + private readonly MediaFoundationReader _reader; + private readonly LoopingWaveProvider _provider; + private readonly WaveOutEvent _output; + private readonly long _durationTicks; + private volatile bool _suppressEnded; + private bool _disposed; + + private AudioFilePlayer(string path, bool loop, double volume) + { + _reader = new MediaFoundationReader(path); + _durationTicks = _reader.TotalTime.Ticks; + _provider = new LoopingWaveProvider(_reader, _sync) { Loop = loop }; + _output = new WaveOutEvent + { + DesiredLatency = 100, + NumberOfBuffers = 3, + Volume = (float)Math.Max(0d, Math.Min(1d, volume)), + }; + _output.PlaybackStopped += OnPlaybackStopped; + + try + { + _output.Init(_provider); + } + catch + { + _output.PlaybackStopped -= OnPlaybackStopped; + _output.Dispose(); + _reader.Dispose(); + throw; + } + } + + public static AudioFilePlayer TryCreate(string path, bool loop, double volume) + { + try + { + return new AudioFilePlayer(path, loop, volume); + } + catch (Exception e) + { + Debug.WriteLine(e); + return null; + } + } + + public event EventHandler PlaybackEnded; + + public long DurationTicks => _durationTicks; + + public long PositionTicks + { + get + { + lock (_sync) + { + return _reader.CurrentTime.Ticks; + } + } + } + + public bool IsPlaying => !_disposed && _output.PlaybackState == PlaybackState.Playing; + + public bool Loop + { + get => _provider.Loop; + set => _provider.Loop = value; + } + + public double Volume + { + get => _output.Volume; + set => _output.Volume = (float)Math.Max(0d, Math.Min(1d, value)); + } + + public void Play() + { + if (_disposed) + return; + + lock (_sync) + { + if (_durationTicks > 0 && _reader.CurrentTime >= _reader.TotalTime) + _reader.CurrentTime = TimeSpan.Zero; + } + + _output.Play(); + } + + public void Pause() + { + if (!_disposed) + _output.Pause(); + } + + public void Seek(long ticks) + { + if (_disposed) + return; + + bool wasPlaying = IsPlaying; + if (wasPlaying) + { + _suppressEnded = true; + _output.Stop(); + } + + lock (_sync) + { + _reader.CurrentTime = TimeSpan.FromTicks(Math.Max(0L, Math.Min(ticks, _durationTicks))); + } + + if (wasPlaying) + _output.Play(); + } + + public void Dispose() + { + if (_disposed) + return; + + _disposed = true; + _output.PlaybackStopped -= OnPlaybackStopped; + _output.Stop(); + _output.Dispose(); + + lock (_sync) + { + _reader.Dispose(); + } + } + + private void OnPlaybackStopped(object sender, StoppedEventArgs e) + { + if (_disposed) + return; + + if (_suppressEnded) + { + _suppressEnded = false; + return; + } + + if (_provider.Loop) + return; + + if (e.Exception != null) + Debug.WriteLine(e.Exception); + + if (PositionTicks < _durationTicks - TimeSpan.TicksPerMillisecond * 200) + return; + + PlaybackEnded?.Invoke(this, EventArgs.Empty); + } + + private sealed class LoopingWaveProvider : IWaveProvider + { + private readonly WaveStream _source; + private readonly object _sync; + private volatile bool _loop; + + public LoopingWaveProvider(WaveStream source, object sync) + { + _source = source; + _sync = sync; + } + + public WaveFormat WaveFormat => _source.WaveFormat; + + public bool Loop + { + get => _loop; + set => _loop = value; + } + + public int Read(byte[] buffer, int offset, int count) + { + int total = 0; + + while (total < count) + { + int read; + + lock (_sync) + { + read = _source.Read(buffer, offset + total, count - total); + + if (read == 0 && _loop) + { + if (_source.Position == 0) + break; + + _source.Position = 0; + continue; + } + } + + if (read == 0) + break; + + total += read; + } + + return total; + } + } +} diff --git a/QuickLook.Plugin/QuickLook.Plugin.VideoViewer/QuickLook.Plugin.VideoViewer.csproj b/QuickLook.Plugin/QuickLook.Plugin.VideoViewer/QuickLook.Plugin.VideoViewer.csproj index 2d56451b6..c8fb3f137 100644 --- a/QuickLook.Plugin/QuickLook.Plugin.VideoViewer/QuickLook.Plugin.VideoViewer.csproj +++ b/QuickLook.Plugin/QuickLook.Plugin.VideoViewer/QuickLook.Plugin.VideoViewer.csproj @@ -67,6 +67,7 @@ + diff --git a/QuickLook.Plugin/QuickLook.Plugin.VideoViewer/ViewerPanel.xaml b/QuickLook.Plugin/QuickLook.Plugin.VideoViewer/ViewerPanel.xaml index c7aa2c371..246687ac1 100644 --- a/QuickLook.Plugin/QuickLook.Plugin.VideoViewer/ViewerPanel.xaml +++ b/QuickLook.Plugin/QuickLook.Plugin.VideoViewer/ViewerPanel.xaml @@ -105,7 +105,7 @@ Padding="3" FontSize="14" Foreground="{DynamicResource WindowTextForeground}" - Text="{Binding ElementName=mediaElement, Path=MediaDuration, Converter={StaticResource TimeTickToShortStringConverter}}" + Text="{Binding ElementName=viewerPanel, Path=MediaDuration, Converter={StaticResource TimeTickToShortStringConverter}}" TextTrimming="CharacterEllipsis" /> - + - + @@ -249,10 +249,10 @@ + Value="{Binding MediaPosition, ElementName=viewerPanel}" /> volumeSliderLayer.Visibility = Visibility.Visible; volumeSliderLayer.MouseDown += (_, _) => volumeSliderLayer.Visibility = Visibility.Collapsed; + _positionTimer = new DispatcherTimer { Interval = TimeSpan.FromMilliseconds(100) }; + _positionTimer.Tick += (_, _) => UpdatePlaybackState(); + _positionTimer.Start(); + sliderProgress.PreviewMouseDown += (_, e) => { - _wasPlaying = mediaElement.IsPlaying; - mediaElement.Pause(); + _isSeeking = true; + _wasPlaying = IsPlaying; + PausePlayback(); }; sliderProgress.PreviewMouseUp += (_, _) => { - if (_wasPlaying) mediaElement.Play(); + _isSeeking = false; + if (_wasPlaying) ResumePlayback(); }; PreviewMouseWheel += (_, e) => ChangeVolume(e.Delta / 120d * 0.04d); @@ -143,6 +157,35 @@ private set { if (value == _shouldLoop) return; _shouldLoop = value; + if (_audioPlayer != null) + _audioPlayer.Loop = value; + else if (value) + TryStartAudioPlayer(); + OnPropertyChanged(); + } + } + + public long MediaPosition + { + get => _mediaPosition; + set + { + if (value == _mediaPosition) return; + _mediaPosition = value; + OnPropertyChanged(); + + if (!_updatingPosition) + Seek(value); + } + } + + public long MediaDuration + { + get => _mediaDuration; + private set + { + if (value == _mediaDuration) return; + _mediaDuration = value; OnPropertyChanged(); } } @@ -177,6 +220,11 @@ public void Dispose() SettingHelper.Set("ShouldLoop", ShouldLoop, "QuickLook.Plugin.VideoViewer"); SettingHelper.Set("UseHardwareAcceleration", UseHardwareAcceleration, "QuickLook.Plugin.VideoViewer"); + _positionTimer?.Stop(); + _positionTimer = null; + _audioPlayer?.Dispose(); + _audioPlayer = null; + try { mediaElement?.Close(); @@ -220,6 +268,7 @@ private void MediaOpened(object o, RoutedEventArgs args) return; HasVideo = mediaElement.HasVideo; + SetMediaDuration(mediaElement.MediaDuration); _context.IsBusy = false; } @@ -240,10 +289,11 @@ private void MediaFailed(object sender, MediaFailedEventArgs e) private void MediaEnded(object sender, RoutedEventArgs e) { - if (mediaElement == null) + if (mediaElement == null || _audioPlayer != null || _audioPlayerStarting) return; mediaElement.MediaPosition = 0L; + SetMediaPosition(0L); if (ShouldLoop) { IsPlaying = true; @@ -280,6 +330,9 @@ private void AutoHideViedoControlContainer(object sender, EventArgs e) private void PlayerStateChanged(PlayerState oldState, PlayerState newState) { + if (_audioPlayer != null) + return; + switch (newState) { case PlayerState.Playing: @@ -294,6 +347,146 @@ private void PlayerStateChanged(PlayerState oldState, PlayerState newState) } } + private void UpdatePlaybackState() + { + if (_isSeeking) + return; + + if (_audioPlayer != null) + { + SetMediaPosition(_audioPlayer.PositionTicks); + SetMediaDuration(_audioPlayer.DurationTicks); + IsPlaying = _audioPlayer.IsPlaying; + } + else if (mediaElement != null) + { + SetMediaPosition(mediaElement.MediaPosition); + SetMediaDuration(mediaElement.MediaDuration); + } + } + + private void SetMediaPosition(long value) + { + if (value == _mediaPosition) + return; + + _updatingPosition = true; + MediaPosition = value; + _updatingPosition = false; + } + + private void SetMediaDuration(long value) + { + if (value > 0) + MediaDuration = value; + } + + private void Seek(long position) + { + if (_audioPlayer != null) + _audioPlayer.Seek(position); + else if (mediaElement?.Source != null) + mediaElement.MediaPosition = position; + } + + private void PausePlayback() + { + if (_audioPlayer != null) + _audioPlayer.Pause(); + else + mediaElement.Pause(); + } + + private void ResumePlayback() + { + if (_audioPlayer != null) + _audioPlayer.Play(); + else + mediaElement.Play(); + } + + private void AudioPlaybackEnded(object sender, EventArgs e) + { + Dispatcher.BeginInvoke(new Action(() => + { + if (_audioPlayer == null) + return; + + SetMediaPosition(0L); + IsPlaying = false; + })); + } + + private void TryStartAudioPlayer() + { + if (!_audioOnly || _audioPlayer != null || _midiPlayer != null || HasVideo || mediaElement?.Source == null) + return; + + _audioPlayerStarting = true; + bool wasPlaying = false; + long position = 0L; + + try + { + position = mediaElement.MediaDuration > 0 ? mediaElement.MediaPosition : _mediaPosition; + wasPlaying = mediaElement.IsPlaying; + + mediaElement.Stop(); + + double volume = Math.Max(0d, Math.Min(1d, SettingHelper.Get("VolumeDouble", 1d, "QuickLook.Plugin.VideoViewer"))); + var audioPlayer = AudioFilePlayer.TryCreate(mediaElement.Source.LocalPath, true, volume); + + if (audioPlayer == null) + { + mediaElement.MediaPosition = position; + if (wasPlaying) + mediaElement.Play(); + else + mediaElement.Pause(); + return; + } + + _audioPlayer = audioPlayer; + _audioPlayer.PlaybackEnded += AudioPlaybackEnded; + _audioPlayer.Seek(position); + SetMediaDuration(_audioPlayer.DurationTicks); + SetMediaPosition(position); + + if (wasPlaying) + { + var startTimer = new DispatcherTimer { Interval = TimeSpan.FromMilliseconds(200) }; + startTimer.Tick += (_, _) => + { + startTimer.Stop(); + + if (_audioPlayer != audioPlayer) + return; + + audioPlayer.Seek(position); + audioPlayer.Play(); + IsPlaying = true; + }; + startTimer.Start(); + } + } + catch (Exception e) + { + Debug.WriteLine(e); + _audioPlayer?.Dispose(); + _audioPlayer = null; + mediaElement.MediaPosition = position; + + if (wasPlaying) + mediaElement.Play(); + else + mediaElement.Pause(); + } + finally + { + _audioPlayerStarting = false; + } + } + private void UpdateMeta(string path, MediaInfoNative info) { if (HasVideo) @@ -372,7 +565,7 @@ private void UpdateMeta(string path, MediaInfoNative info) { if (_lyricLines != null && _lyricLines.Length != 0) { - var lyric = LrcHelper.GetNearestLrc(_lyricLines, new TimeSpan(mediaElement.MediaPosition)); + var lyric = LrcHelper.GetNearestLrc(_lyricLines, new TimeSpan(MediaPosition)); metaLyric.Text = lyric?.LrcText?.Trim(); } else @@ -393,10 +586,14 @@ private void UpdateMeta(string path, MediaInfoNative info) public double LinearVolume { - get => mediaElement.Volume; + get => _audioPlayer?.Volume ?? mediaElement?.Volume ?? 0d; set { - mediaElement.Volume = value; + if (_audioPlayer != null) + _audioPlayer.Volume = value; + else if (mediaElement != null) + mediaElement.Volume = value; + OnPropertyChanged(); } } @@ -408,10 +605,21 @@ private void ChangeVolume(double delta) private void TogglePlayPause(object sender, EventArgs e) { - if (mediaElement.IsPlaying) + if (_audioPlayer != null) + { + if (_audioPlayer.IsPlaying) + _audioPlayer.Pause(); + else + _audioPlayer.Play(); + } + else if (mediaElement.IsPlaying) + { mediaElement.Pause(); + } else + { mediaElement.Play(); + } } private void ToggleShouldLoop(object sender, EventArgs e) @@ -461,21 +669,44 @@ private void HardwareAccelerationModeChanged(bool enable) /// public void LoadAndPlay(string path, MediaInfoNative info) { + bool hasVideo = !string.IsNullOrWhiteSpace(info?.Get(StreamKind.Video, 0, "Format")); + string audioCodec = info?.Get(StreamKind.Audio, 0, "Format"); + bool hasAudio = !string.IsNullOrWhiteSpace(audioCodec); + _audioOnly = false; + // Detect whether it is other playback formats - if (!HasVideo) + if (!hasVideo) { - string audioCodec = info?.Get(StreamKind.Audio, 0, "Format"); - if (audioCodec?.Equals("MIDI", StringComparison.OrdinalIgnoreCase) ?? false) { _midiPlayer = new MidiPlayer(this, _context); _midiPlayer.LoadAndPlay(path); return; // Midi player will handle the playback at all } + + _audioOnly = hasAudio; } UpdateMeta(path, info); + if (_audioOnly && ShouldLoop) + { + double volume = Math.Max(0d, Math.Min(1d, SettingHelper.Get("VolumeDouble", 1d, "QuickLook.Plugin.VideoViewer"))); + var audioPlayer = AudioFilePlayer.TryCreate(path, ShouldLoop, volume); + + if (audioPlayer != null) + { + _audioPlayer = audioPlayer; + _audioPlayer.PlaybackEnded += AudioPlaybackEnded; + SetMediaDuration(_audioPlayer.DurationTicks); + SetMediaPosition(0L); + IsPlaying = true; + _context.IsBusy = false; + _audioPlayer.Play(); + return; + } + } + // detect rotation _ = double.TryParse(info?.Get(StreamKind.Video, 0, "Rotation"), NumberStyles.Float, CultureInfo.InvariantCulture, out var rotation); if (Math.Abs(rotation) > 0.1d) From 6f69bd2cfe0a0017ee65b53c515f6da936da9c33 Mon Sep 17 00:00:00 2001 From: Henglie Date: Fri, 13 Nov 2026 20:43:32 +0800 Subject: [PATCH 2/2] Address review feedback on seamless audio loop --- .../AudioTrack/AudioFilePlayer.cs | 71 ++++++++++++++++--- .../ViewerPanel.xaml.cs | 3 +- 2 files changed, 62 insertions(+), 12 deletions(-) diff --git a/QuickLook.Plugin/QuickLook.Plugin.VideoViewer/AudioTrack/AudioFilePlayer.cs b/QuickLook.Plugin/QuickLook.Plugin.VideoViewer/AudioTrack/AudioFilePlayer.cs index 6583b6a13..f7bc48faf 100644 --- a/QuickLook.Plugin/QuickLook.Plugin.VideoViewer/AudioTrack/AudioFilePlayer.cs +++ b/QuickLook.Plugin/QuickLook.Plugin.VideoViewer/AudioTrack/AudioFilePlayer.cs @@ -29,6 +29,8 @@ internal sealed class AudioFilePlayer : IDisposable private readonly WaveOutEvent _output; private readonly long _durationTicks; private volatile bool _suppressEnded; + private bool _stopPending; + private bool _restartPending; private bool _disposed; private AudioFilePlayer(string path, bool loop, double volume) @@ -40,13 +42,13 @@ private AudioFilePlayer(string path, bool loop, double volume) { DesiredLatency = 100, NumberOfBuffers = 3, - Volume = (float)Math.Max(0d, Math.Min(1d, volume)), }; _output.PlaybackStopped += OnPlaybackStopped; try { _output.Init(_provider); + _output.Volume = (float)Math.Max(0d, Math.Min(1d, volume)); } catch { @@ -108,6 +110,12 @@ public void Play() { if (_durationTicks > 0 && _reader.CurrentTime >= _reader.TotalTime) _reader.CurrentTime = TimeSpan.Zero; + + if (_stopPending) + { + _restartPending = true; + return; + } } _output.Play(); @@ -115,8 +123,15 @@ public void Play() public void Pause() { - if (!_disposed) - _output.Pause(); + if (_disposed) + return; + + lock (_sync) + { + _restartPending = false; + } + + _output.Pause(); } public void Seek(long ticks) @@ -124,20 +139,39 @@ public void Seek(long ticks) if (_disposed) return; - bool wasPlaying = IsPlaying; - if (wasPlaying) + PlaybackState state = _output.PlaybackState; + if (state == PlaybackState.Playing) + { + lock (_sync) + { + _reader.CurrentTime = TimeSpan.FromTicks(Math.Max(0L, Math.Min(ticks, _durationTicks))); + _suppressEnded = true; + _stopPending = true; + _restartPending = true; + } + + _output.Stop(); + return; + } + + if (state == PlaybackState.Paused) { - _suppressEnded = true; + lock (_sync) + { + _reader.CurrentTime = TimeSpan.FromTicks(Math.Max(0L, Math.Min(ticks, _durationTicks))); + _suppressEnded = true; + _stopPending = true; + _restartPending = false; + } + _output.Stop(); + return; } lock (_sync) { _reader.CurrentTime = TimeSpan.FromTicks(Math.Max(0L, Math.Min(ticks, _durationTicks))); } - - if (wasPlaying) - _output.Play(); } public void Dispose() @@ -161,12 +195,29 @@ private void OnPlaybackStopped(object sender, StoppedEventArgs e) if (_disposed) return; - if (_suppressEnded) + bool suppress; + bool restart; + + lock (_sync) { + suppress = _suppressEnded; + restart = _restartPending; _suppressEnded = false; + _stopPending = false; + _restartPending = false; + } + + // The playback worker has exited by the time this event is raised, so the + // restart no longer races the old worker over the same buffers. + if (restart) + { + _output.Play(); return; } + if (suppress) + return; + if (_provider.Loop) return; diff --git a/QuickLook.Plugin/QuickLook.Plugin.VideoViewer/ViewerPanel.xaml.cs b/QuickLook.Plugin/QuickLook.Plugin.VideoViewer/ViewerPanel.xaml.cs index 130be852b..f8715e02b 100644 --- a/QuickLook.Plugin/QuickLook.Plugin.VideoViewer/ViewerPanel.xaml.cs +++ b/QuickLook.Plugin/QuickLook.Plugin.VideoViewer/ViewerPanel.xaml.cs @@ -430,10 +430,10 @@ private void TryStartAudioPlayer() { position = mediaElement.MediaDuration > 0 ? mediaElement.MediaPosition : _mediaPosition; wasPlaying = mediaElement.IsPlaying; + double volume = Math.Max(0d, Math.Min(1d, mediaElement.Volume)); mediaElement.Stop(); - double volume = Math.Max(0d, Math.Min(1d, SettingHelper.Get("VolumeDouble", 1d, "QuickLook.Plugin.VideoViewer"))); var audioPlayer = AudioFilePlayer.TryCreate(mediaElement.Source.LocalPath, true, volume); if (audioPlayer == null) @@ -462,7 +462,6 @@ private void TryStartAudioPlayer() if (_audioPlayer != audioPlayer) return; - audioPlayer.Seek(position); audioPlayer.Play(); IsPlaying = true; };