-
Notifications
You must be signed in to change notification settings - Fork 1.1k
/
Copy pathViewerPanel.xaml.cs
427 lines (362 loc) · 13 KB
/
ViewerPanel.xaml.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
// Copyright © 2017 Paddy Xu
//
// 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 <http://www.gnu.org/licenses/>.
extern alias MediaInfoWrapper;
using MediaInfoWrapper::MediaInfo;
using QuickLook.Common.Annotations;
using QuickLook.Common.Helpers;
using QuickLook.Common.Plugin;
using QuickLook.Plugin.VideoViewer.AudioTrack;
using QuickLook.Plugin.VideoViewer.Extensions;
using QuickLook.Plugin.VideoViewer.LyricTrack;
using System;
using System.ComponentModel;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Media.Imaging;
using System.Windows.Threading;
using UtfUnknown;
using WPFMediaKit.DirectShow.Controls;
using WPFMediaKit.DirectShow.MediaPlayers;
namespace QuickLook.Plugin.VideoViewer;
/// <summary>
/// Interaction logic for UserControl1.xaml
/// </summary>
public partial class ViewerPanel : UserControl, IDisposable, INotifyPropertyChanged
{
private readonly ContextObject _context;
private BitmapSource _coverArt;
private DispatcherTimer _lyricTimer;
private LrcLine[] _lyricLines;
private MidiPlayer _midiPlayer;
private bool _hasVideo;
private bool _isPlaying;
private bool _wasPlaying;
private bool _shouldLoop;
public ViewerPanel(ContextObject context)
{
InitializeComponent();
LoadAndInsertGlassLayer();
// apply global theme
Resources.MergedDictionaries[0].MergedDictionaries.Clear();
_context = context;
mediaElement.MediaUriPlayer.LAVFilterDirectory =
IntPtr.Size == 8 ? "LAVFilters-x64\\" : "LAVFilters-x86\\";
//ShowViedoControlContainer(null, null);
viewerPanel.PreviewMouseMove += ShowViedoControlContainer;
mediaElement.MediaUriPlayer.PlayerStateChanged += PlayerStateChanged;
mediaElement.MediaOpened += MediaOpened;
mediaElement.MediaEnded += MediaEnded;
mediaElement.MediaFailed += MediaFailed;
ShouldLoop = SettingHelper.Get("ShouldLoop", false, "QuickLook.Plugin.VideoViewer");
buttonPlayPause.Click += TogglePlayPause;
buttonLoop.Click += ToggleShouldLoop;
buttonTime.Click += (sender, e) => buttonTime.Tag = (string)buttonTime.Tag == "Time" ? "Length" : "Time";
buttonMute.Click += (sender, e) => volumeSliderLayer.Visibility = Visibility.Visible;
volumeSliderLayer.MouseDown += (sender, e) => volumeSliderLayer.Visibility = Visibility.Collapsed;
sliderProgress.PreviewMouseDown += (sender, e) =>
{
_wasPlaying = mediaElement.IsPlaying;
mediaElement.Pause();
};
sliderProgress.PreviewMouseUp += (sender, e) =>
{
if (_wasPlaying) mediaElement.Play();
};
PreviewMouseWheel += (sender, e) => ChangeVolume((double)e.Delta / 120 * 0.04);
}
private partial void LoadAndInsertGlassLayer();
public bool HasVideo
{
get => _hasVideo;
private set
{
if (value == _hasVideo) return;
_hasVideo = value;
OnPropertyChanged();
}
}
public bool IsPlaying
{
get => _isPlaying;
private set
{
if (value == _isPlaying) return;
_isPlaying = value;
OnPropertyChanged();
}
}
public bool ShouldLoop
{
get => _shouldLoop;
private set
{
if (value == _shouldLoop) return;
_shouldLoop = value;
OnPropertyChanged();
if (!IsPlaying)
{
IsPlaying = true;
mediaElement.Play();
}
}
}
public BitmapSource CoverArt
{
get => _coverArt;
private set
{
if (ReferenceEquals(value, _coverArt)) return;
if (value == null) return;
_coverArt = value;
OnPropertyChanged();
}
}
public void Dispose()
{
// old plugin use an int-typed "Volume" config key ranged from 0 to 100. Let's use a new one here.
SettingHelper.Set("VolumeDouble", LinearVolume, "QuickLook.Plugin.VideoViewer");
SettingHelper.Set("ShouldLoop", ShouldLoop, "QuickLook.Plugin.VideoViewer");
try
{
mediaElement?.Close();
Task.Run(() =>
{
mediaElement?.MediaUriPlayer.Dispose();
mediaElement = null;
});
}
catch (Exception e)
{
Debug.WriteLine(e);
}
_lyricTimer?.Stop();
_lyricTimer = null;
_lyricLines = null;
_midiPlayer?.Dispose();
_midiPlayer = null;
}
public event PropertyChangedEventHandler PropertyChanged;
private void MediaOpened(object o, RoutedEventArgs args)
{
if (mediaElement == null)
return;
HasVideo = mediaElement.HasVideo;
_context.IsBusy = false;
}
private void MediaFailed(object sender, MediaFailedEventArgs e)
{
((MediaUriElement)sender).Dispatcher.BeginInvoke(new Action(() =>
{
_context.ViewerContent =
new Label { Content = e.Exception, VerticalAlignment = VerticalAlignment.Center };
_context.IsBusy = false;
}));
}
private void MediaEnded(object sender, RoutedEventArgs e)
{
if (mediaElement == null)
return;
mediaElement.MediaPosition = 0;
if (ShouldLoop)
{
IsPlaying = true;
mediaElement.Play();
}
else
{
IsPlaying = false;
mediaElement.Pause();
}
}
private void ShowViedoControlContainer(object sender, MouseEventArgs e)
{
var show = (Storyboard)videoControlContainer.FindResource("ShowControlStoryboard");
if (videoControlContainer.Opacity == 0 || videoControlContainer.Opacity == 1)
show.Begin();
}
private void AutoHideViedoControlContainer(object sender, EventArgs e)
{
if (!HasVideo)
return;
if (videoControlContainer.IsMouseOver)
return;
var hide = (Storyboard)videoControlContainer.FindResource("HideControlStoryboard");
hide.Begin();
}
private void PlayerStateChanged(PlayerState oldState, PlayerState newState)
{
switch (newState)
{
case PlayerState.Playing:
IsPlaying = true;
break;
case PlayerState.Paused:
case PlayerState.Stopped:
case PlayerState.Closed:
IsPlaying = false;
break;
}
}
private void UpdateMeta(string path, MediaInfoLib info)
{
if (HasVideo)
return;
try
{
if (info == null)
throw new NullReferenceException();
var title = info.Get(StreamKind.General, 0, "Title");
var artist = info.Get(StreamKind.General, 0, "Performer");
var album = info.Get(StreamKind.General, 0, "Album");
metaTitle.Text = !string.IsNullOrWhiteSpace(title) ? title : Path.GetFileName(path);
metaArtists.Text = artist;
metaAlbum.Text = album;
var coverData = info.Get(StreamKind.General, 0, "Cover_Data");
if (!string.IsNullOrEmpty(coverData))
{
var coverBytes = Convert.FromBase64String
(
coverData.Contains(' ') // MediaInfo may will return multiple covers
? coverData.Split(" / ")[0] // Get the first cover only
: coverData
);
using var ms = new MemoryStream(coverBytes);
CoverArt = BitmapFrame.Create(ms, BitmapCreateOptions.None, BitmapCacheOption.OnLoad);
}
}
catch (Exception)
{
metaTitle.Text = Path.GetFileName(path);
metaArtists.Text = metaAlbum.Text = string.Empty;
}
metaArtists.Visibility = string.IsNullOrEmpty(metaArtists.Text)
? Visibility.Collapsed
: Visibility.Visible;
metaAlbum.Visibility = string.IsNullOrEmpty(metaAlbum.Text)
? Visibility.Collapsed
: Visibility.Visible;
var lyricPath = Path.ChangeExtension(path, ".lrc");
if (File.Exists(lyricPath))
{
var buffer = File.ReadAllBytes(lyricPath);
var encoding = CharsetDetector.DetectFromBytes(buffer).Detected?.Encoding ?? Encoding.Default;
_lyricLines = LrcHelper.ParseText(encoding.GetString(buffer)).ToArray();
_lyricTimer = new DispatcherTimer { Interval = TimeSpan.FromMilliseconds(100) };
_lyricTimer.Tick += (sender, e) =>
{
if (_lyricLines != null && _lyricLines.Length != 0)
{
var lyric = LrcHelper.GetNearestLrc(_lyricLines, new TimeSpan(mediaElement.MediaPosition));
metaLyric.Text = lyric?.LrcText?.Trim();
}
else
{
metaLyric.Text = null;
metaLyric.Visibility = Visibility.Collapsed;
}
};
_lyricTimer.Start();
metaLyric.Visibility = Visibility.Visible;
}
else
{
metaLyric.Visibility = Visibility.Collapsed;
}
}
// Newer .net has Math.Clamp
private T Clamp<T>(T val, T min, T max) where T : IComparable<T>
{
if (val.CompareTo(min) < 0) return min;
else if (val.CompareTo(max) > 0) return max;
else return val;
}
// A change in amplitude by a factor of 10 corresponds to a 20 dB change
private const double DecibelAmplitudeMult = 20.0;
public double LinearVolume
{
// mediaElement.Volume returns [0,1] where 0 = -100db, 1 = 0db
// Decibel is logarithmic. See amplitude table https://en.wikipedia.org/wiki/Decibel
get
{
var dbVol = 100.0 * (mediaElement.Volume - 1.0);
var linearVol = Math.Pow(10, dbVol / DecibelAmplitudeMult);
return linearVol;
}
set
{
var linearVol = Clamp(value, 0.00001, 1.0);
var dbVol = DecibelAmplitudeMult * Math.Log10(linearVol);
mediaElement.Volume = dbVol / 100.0 + 1.0;
OnPropertyChanged();
}
}
private void ChangeVolume(double delta)
{
LinearVolume = LinearVolume + delta; // setter will clamp
}
private void TogglePlayPause(object sender, EventArgs e)
{
if (mediaElement.IsPlaying)
mediaElement.Pause();
else
mediaElement.Play();
}
private void ToggleShouldLoop(object sender, EventArgs e)
{
ShouldLoop = !ShouldLoop;
}
public void LoadAndPlay(string path, MediaInfoLib info)
{
// Detect whether it is other playback formats
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
}
}
UpdateMeta(path, info);
// detect rotation
double.TryParse(info?.Get(StreamKind.Video, 0, "Rotation"), out var rotation);
// Correct rotation: on some machine the value "90" becomes "90000" by some reason
if (rotation > 360)
rotation /= 1e3;
if (Math.Abs(rotation) > 0.1)
mediaElement.LayoutTransform = new RotateTransform(rotation, 0.5, 0.5);
mediaElement.Source = new Uri(path);
// old plugin use an int-typed "Volume" config key ranged from 0 to 100. Let's use a new one here.
LinearVolume = SettingHelper.Get("VolumeDouble", 1d, "QuickLook.Plugin.VideoViewer");
mediaElement.Play();
}
[NotifyPropertyChangedInvocator]
protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
}