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..f7bc48faf --- /dev/null +++ b/QuickLook.Plugin/QuickLook.Plugin.VideoViewer/AudioTrack/AudioFilePlayer.cs @@ -0,0 +1,284 @@ +// 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 _stopPending; + private bool _restartPending; + 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, + }; + _output.PlaybackStopped += OnPlaybackStopped; + + try + { + _output.Init(_provider); + _output.Volume = (float)Math.Max(0d, Math.Min(1d, volume)); + } + 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; + + if (_stopPending) + { + _restartPending = true; + return; + } + } + + _output.Play(); + } + + public void Pause() + { + if (_disposed) + return; + + lock (_sync) + { + _restartPending = false; + } + + _output.Pause(); + } + + public void Seek(long ticks) + { + if (_disposed) + return; + + 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) + { + 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))); + } + } + + 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; + + 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; + + 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,145 @@ 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; + double volume = Math.Max(0d, Math.Min(1d, mediaElement.Volume)); + + mediaElement.Stop(); + + 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.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 +564,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 +585,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 +604,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 +668,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)