-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy pathMediaObject.cs
More file actions
739 lines (713 loc) · 38.1 KB
/
MediaObject.cs
File metadata and controls
739 lines (713 loc) · 38.1 KB
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
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
using LibVLCSharp.Shared;
using NAudio.Vorbis;
using NAudio.Wave;
using NAudio.Wave.SampleProviders;
using RoleplayingVoiceCore;
using SixLabors.ImageSharp;
using SixLabors.ImageSharp.Advanced;
using SixLabors.ImageSharp.PixelFormats;
using System.Diagnostics;
using System.IO.MemoryMappedFiles;
using System.Numerics;
using System.Runtime.InteropServices;
using VarispeedDemo.SoundTouch;
namespace RoleplayingMediaCore {
public class MediaObject : IDisposable {
private IMediaGameObject _playerObject;
private IMediaGameObject _camera;
private SoundType _soundType;
private bool _spatialAllowed;
private VolumeSampleProvider _volumeSampleProvider;
private PanningSampleProvider _panningSampleProvider;
private IWavePlayer _wavePlayer;
private LibVLC libVLC;
private MediaPlayer _vlcPlayer;
private MediaManager _parent;
private WaveStream _player;
private static MemoryMappedFile _currentMappedFile;
private static MemoryMappedViewAccessor _currentMappedViewAccessor;
public event EventHandler<MediaError> OnErrorReceived;
public event EventHandler<string> PlaybackStopped;
public event EventHandler<StreamVolumeEventArgs> StreamVolumeChanged;
private string _soundPath;
private string _libVLCPath;
private bool stopPlaybackOnMovement;
private Vector3 lastPosition;
private Vector3 lastRotation;
private const uint _width = 1280;
private const uint _height = 720;
//private int _volumeOffset = 1;
/// <summary>
/// RGBA is used, so 4 byte per pixel, or 32 bits.
/// </summary>
private const uint _bytePerPixel = 4;
/// <summary>
/// the number of bytes per "line"
/// For performance reasons inside the core of VLC, it must be aligned to multiples of 32.
/// </summary>
private uint _pitch;
/// <summary>
/// The number of lines in the buffer.
/// For performance reasons inside the core of VLC, it must be aligned to multiples of 32.
/// </summary>
private uint _lines;
private float volumePercentage = 1;
private LoopStream _loopStream;
private float _baseVolume = 1;
private MeteringSampleProvider _meteringSampleProvider;
private bool _vlcWasAbleToStart;
private float _volumeOffset;
private bool _disposed;
public MediaObject(MediaManager parent, IMediaGameObject playerObject, IMediaGameObject camera,
SoundType soundType, string soundPath, string libVLCPath, bool spatialAllowed) {
_playerObject = playerObject;
_soundPath = soundPath;
_camera = camera;
_libVLCPath = libVLCPath;
_parent = parent;
this._soundType = soundType;
_spatialAllowed = spatialAllowed;
_pitch = Align(_width * _bytePerPixel);
_lines = Align(_height);
_parent.OnCleanupTime += _parent_OnCleanupTime;
}
private void _parent_OnCleanupTime(object? sender, EventArgs e) {
Invalidated = true;
}
private static uint Align(uint size) {
if (size % 32 == 0) {
return size;
}
return ((size / 32) + 1) * 32; // Align on the next multiple of 32
}
private void SoundLoopCheck() {
Task.Run(async () => {
try {
Thread.Sleep(500);
lastPosition = _playerObject.Position;
lastRotation = _playerObject.Rotation;
Thread.Sleep(500);
while (true) {
if (_playerObject != null && _wavePlayer != null && _volumeSampleProvider != null) {
float distance = Vector3.Distance(lastPosition, _playerObject.Position);
float rotationDistance = Vector3.Distance(lastRotation, _playerObject.Rotation);
if ((distance > 0.01f && _soundType == SoundType.Loop) ||
((distance < 0.3f && rotationDistance < 2f) && _soundType == SoundType.LoopWhileMoving) || _playerObject.Invalid || Invalidated || _parent.Invalidated) {
Invalidated = true;
Stop();
break;
}
}
if (_soundType == SoundType.LoopWhileMoving) {
lastPosition = _playerObject.Position;
lastRotation = _playerObject.Rotation;
}
Thread.Sleep(200);
}
} catch (Exception e) { OnErrorReceived?.Invoke(this, new MediaError() { Exception = e }); }
});
}
private void MountLoopCheck() {
Task.Run(async () => {
try {
Thread.Sleep(500);
lastPosition = _playerObject.Position;
Thread.Sleep(500);
while (_playerObject != null && _wavePlayer != null && _volumeSampleProvider != null) {
if (_playerObject != null && _wavePlayer != null && _volumeSampleProvider != null) {
float distance = Vector3.Distance(lastPosition, _playerObject.Position);
if ((distance > 0.01f && _soundType == SoundType.LoopUntilStopped)) {
volumePercentage = Math.Clamp(volumePercentage + 0.1f, 0, 0.8f);
} else {
volumePercentage = Math.Clamp(volumePercentage - 0.1f, 0.2f, 0.8f);
}
}
if (_volumeSampleProvider != null) {
_volumeSampleProvider.Volume = (_volumeOffset * _baseVolume) * volumePercentage;
}
lastPosition = _playerObject.Position;
Thread.Sleep(200);
}
} catch (Exception e) { OnErrorReceived?.Invoke(this, new MediaError() { Exception = e }); }
});
}
private void DonePlayingCheck() {
Stopwatch stopwatch = new Stopwatch();
Task.Run(async () => {
try {
Thread.Sleep(300);
long lastPosition = _player?.Position ?? 0;
while (true) {
var player = _player;
if (player == null) {
break;
}
if (player.Position > player.Length * 0.985f) {
if (!stopwatch.IsRunning) {
stopwatch.Start();
}
if (stopwatch.ElapsedMilliseconds > 100) {
Thread.Sleep(100);
_wavePlayer?.Stop();
break;
}
} else {
stopwatch.Reset();
}
lastPosition = player.Position;
Thread.Sleep(100);
}
} catch (Exception e) { OnErrorReceived?.Invoke(this, new MediaError() { Exception = e }); }
});
}
public IMediaGameObject CharacterObject { get => _playerObject; set => _playerObject = value; }
public float Volume {
get {
if (_volumeSampleProvider != null) {
return _volumeSampleProvider.Volume;
}
try {
if (_vlcPlayer != null) {
return _vlcPlayer.Volume;
}
} catch { }
return 0;
}
set {
if (_volumeSampleProvider != null) {
_baseVolume = value;
_volumeSampleProvider.Volume = (_volumeOffset * value) * volumePercentage;
}
if (_vlcPlayer != null) {
try {
int newValue = (int)(value * 100f);
if (newValue != _vlcPlayer.Volume) {
_baseVolume = newValue;
_vlcPlayer.Volume = (int)((float)newValue * volumePercentage);
}
} catch (Exception e) { OnErrorReceived?.Invoke(this, new MediaError() { Exception = e }); }
}
}
}
public PlaybackState PlaybackState {
get {
if (_wavePlayer != null) {
try {
return _wavePlayer.PlaybackState;
} catch {
return PlaybackState.Stopped;
}
} else if (_vlcPlayer != null) {
try {
return _vlcPlayer.IsPlaying ? PlaybackState.Playing : PlaybackState.Stopped;
} catch {
return PlaybackState.Stopped;
}
} else {
return PlaybackState.Stopped;
}
}
}
public SoundType SoundType { get => _soundType; set => _soundType = value; }
public bool StopPlaybackOnMovement { get => stopPlaybackOnMovement; set => stopPlaybackOnMovement = value; }
public string SoundPath { get => _soundPath; set => _soundPath = value; }
public float Pan {
get {
if (_panningSampleProvider == null) {
return 0;
} else {
return _panningSampleProvider.Pan;
}
}
set {
if (_panningSampleProvider != null) {
_panningSampleProvider.Pan = value;
}
}
}
public IMediaGameObject Camera { get => _camera; set => _camera = value; }
public bool Invalidated { get; internal set; }
public bool SpatialAllowed { get => _spatialAllowed; set => _spatialAllowed = value; }
public MediaManager Parent { get => _parent; set => _parent = value; }
public void EndLooping() {
if (_loopStream != null) {
try {
_loopStream.EnableLooping = false;
_loopStream?.Dispose();
} catch {
}
}
}
public void Stop() {
Volume = 0;
EndLooping();
if (_wavePlayer != null) {
try {
if (_wavePlayer != null) {
try {
_wavePlayer?.Stop();
_wavePlayer?.Dispose();
} catch {
PlaybackStopped?.Invoke(this, "OK");
}
}
} catch (Exception e) {
OnErrorReceived?.Invoke(this, new MediaError() { Exception = e });
PlaybackStopped?.Invoke(this, "OK");
}
_wavePlayer = null;
} else {
PlaybackStopped?.Invoke(this, "OK");
}
if (_vlcPlayer != null) {
try {
_vlcPlayer?.Stop();
} catch (Exception e) { OnErrorReceived?.Invoke(this, new MediaError() { Exception = e }); }
}
try { _player?.Dispose(); } catch { }
_player = null;
Volume = 0;
Invalidated = true;
}
public void LoopEarly() {
_loopStream?.LoopEarly();
}
public async void Play(WaveStream soundPath, float volume, int delay, bool useSmbPitch,
AudioOutputType audioPlayerType, float pitch = 0, bool lowPerformanceMode = false, float speed = 1, float volumeOffset = 1) {
_volumeOffset = volumeOffset;
if (!Invalidated) {
try {
if (PlaybackState == PlaybackState.Stopped) {
_player = soundPath;
WaveStream desiredStream = _player;
if (_soundType != SoundType.MainPlayerTts &&
_soundType != SoundType.OtherPlayerTts &&
_soundType != SoundType.LoopWhileMoving &&
_soundType != SoundType.Livestream &&
_soundType != SoundType.MainPlayerCombat &&
_soundType != SoundType.OtherPlayerCombat &&
_soundType != SoundType.NPC &&
_player.TotalTime.TotalSeconds > 13) {
_soundType = SoundType.Loop;
}
volumePercentage = 0.7f;
if (delay > 0) {
Thread.Sleep(delay);
}
switch (audioPlayerType) {
case AudioOutputType.WaveOut:
var waveOut = new WaveOutEvent();
if (_parent.AudioOutputDeviceIndex >= -1 && _parent.AudioOutputDeviceIndex < NAudio.Wave.WaveOut.DeviceCount) {
waveOut.DeviceNumber = _parent.AudioOutputDeviceIndex;
}
_wavePlayer = waveOut;
break;
case AudioOutputType.DirectSound:
_wavePlayer = new DirectSoundOut();
break;
case AudioOutputType.Wasapi:
_wavePlayer = new WasapiOut();
break;
}
if (_soundType == SoundType.Loop || _soundType == SoundType.LoopWhileMoving) {
if (_soundType != SoundType.MainPlayerCombat && _soundType != SoundType.OtherPlayerCombat) {
if (delay > 0) {
Thread.Sleep(delay);
}
}
}
if (_soundType == SoundType.Loop || _soundType == SoundType.LoopWhileMoving) {
if (_soundType != SoundType.MainPlayerCombat && _soundType != SoundType.OtherPlayerCombat) {
SoundLoopCheck();
}
_loopStream = new LoopStream(_player) { EnableLooping = true, Parent = this };
desiredStream = _loopStream;
}
float distance = Vector3.Distance(_camera.Position, CharacterObject.Position);
float newVolume = _parent.CalculateObjectVolume(_playerObject.Name, this);
ISampleProvider sampleProvider = null;
if (!lowPerformanceMode || _soundType != SoundType.MainPlayerCombat && _soundType
!= SoundType.MainPlayerTts && _soundType != SoundType.NPC) {
if (desiredStream != null) {
_meteringSampleProvider = new MeteringSampleProvider(desiredStream.ToSampleProvider());
_meteringSampleProvider.StreamVolume += _meteringSampleProvider_StreamVolume;
_volumeSampleProvider = new VolumeSampleProvider(_meteringSampleProvider);
_volumeSampleProvider.Volume = _volumeOffset * volume;
_panningSampleProvider = new PanningSampleProvider(
_player.WaveFormat.Channels == 1 ? _volumeSampleProvider : _volumeSampleProvider.ToMono());
Vector3 dir = CharacterObject.Position - _camera.Position;
float direction = AngleDir(_camera.Forward, dir, _camera.Top);
_panningSampleProvider.Pan = Math.Clamp(direction / 3, -1, 1);
if (pitch != 1) {
ISampleProvider newSampleProvider = null;
if (!useSmbPitch) {
var pitchSample = new VarispeedSampleProvider(_panningSampleProvider, 100, new SoundTouchProfile(false, true));
pitchSample.PlaybackRate = pitch;
newSampleProvider = pitchSample;
} else {
var pitchSample = new SmbPitchShiftingSampleProvider(_panningSampleProvider);
pitchSample.PitchFactor = pitch;
newSampleProvider = pitchSample;
}
sampleProvider = newSampleProvider;
} else {
sampleProvider = _panningSampleProvider;
}
}
} else {
_meteringSampleProvider = new MeteringSampleProvider(desiredStream.ToSampleProvider());
_meteringSampleProvider.StreamVolume += _meteringSampleProvider_StreamVolume;
if (pitch != 1) {
ISampleProvider newSampleProvider = null;
if (!useSmbPitch) {
var pitchSample = new VarispeedSampleProvider(_meteringSampleProvider, 100, new SoundTouchProfile(false, true));
pitchSample.PlaybackRate = pitch;
newSampleProvider = pitchSample;
} else {
var pitchSample = new SmbPitchShiftingSampleProvider(_meteringSampleProvider);
pitchSample.PitchFactor = pitch;
newSampleProvider = pitchSample;
}
_volumeSampleProvider = new VolumeSampleProvider(newSampleProvider);
_volumeSampleProvider.Volume = _volumeOffset * volume;
sampleProvider = _volumeSampleProvider;
} else {
_volumeSampleProvider = new VolumeSampleProvider(_meteringSampleProvider);
_volumeSampleProvider.Volume = _volumeOffset * volume;
sampleProvider = _volumeSampleProvider;
}
}
if (Math.Abs(speed - 1.0f) > 0.0001f) {
if (sampleProvider != null) {
var playbackSpeed = new VarispeedSampleProvider(sampleProvider, 100, new SoundTouchProfile(true, true));
playbackSpeed.PlaybackRate = speed;
sampleProvider = playbackSpeed;
}
}
if (_wavePlayer != null && sampleProvider != null) {
try {
_wavePlayer?.Init(sampleProvider);
if (_soundType == SoundType.Loop ||
_soundType == SoundType.MainPlayerVoice ||
_soundType == SoundType.OtherPlayer) {
} else {
_player.Position = 0;
}
if (_soundType == SoundType.MainPlayerCombat ||
_soundType == SoundType.OtherPlayerCombat) {
if (_wavePlayer != null) {
try {
var waveOutEvent = _wavePlayer as WaveOutEvent;
if (waveOutEvent != null) {
waveOutEvent.DesiredLatency = 50;
}
} catch {
}
}
}
_wavePlayer.PlaybackStopped += delegate {
if (PlaybackStopped != null) {
try {
PlaybackStopped?.Invoke(this, "OK");
} catch (Exception e) { OnErrorReceived?.Invoke(this, new MediaError() { Exception = e }); }
}
};
_wavePlayer?.Play();
DonePlayingCheck();
} catch (Exception e) {
OnErrorReceived?.Invoke(this, new MediaError() { Exception = e });
PlaybackStopped?.Invoke(this, "ERR");
}
}
}
} catch (Exception e) { OnErrorReceived?.Invoke(this, new MediaError() { Exception = e }); }
}
}
//private void NPCDoneTalking() {
// Task.Run(async () => {
// try {
// int lastPosition =
// Thread.Sleep(500);
// while (true) {
// if (_playerObject != null && _wavePlayer != null && _volumeSampleProvider != null) {
// float distance = Vector3.Distance(lastPosition, _playerObject.Position);
// if () {
// _wavePlayer?.Stop();
// break;
// }
// }
// if (_soundType == SoundType.LoopWhileMoving) {
// lastPosition = _playerObject.Position;
// }
// Thread.Sleep(200);
// }
// } catch (Exception e) { OnErrorReceived?.Invoke(this, new MediaError() { Exception = e }); }
// });
//}
private void _meteringSampleProvider_StreamVolume(object? sender, StreamVolumeEventArgs e) {
StreamVolumeChanged?.Invoke(sender, e);
}
public async void Play(string mediaPath, float volume, int delay, TimeSpan skipAhead,
AudioOutputType audioPlayerType, bool lowPerformanceMode = false, int volumeOffset = 0) {
_volumeOffset = volumeOffset;
await Task.Run(async delegate {
try {
Stopwatch latencyTimer = Stopwatch.StartNew();
if (!string.IsNullOrEmpty(mediaPath) && PlaybackState == PlaybackState.Stopped) {
if (!mediaPath.StartsWith("http") && !mediaPath.StartsWith("rtmp") && !mediaPath.EndsWith(".mp4") && !mediaPath.EndsWith(".avi") &&
(audioPlayerType != AudioOutputType.VLCExperimental || _soundType != SoundType.NPC)) {
_player = mediaPath.EndsWith(".ogg") ?
new VorbisWaveReader(mediaPath) : new MediaFoundationReader(mediaPath);
WaveStream desiredStream = _player;
if (_soundType != SoundType.MainPlayerTts &&
_soundType != SoundType.OtherPlayerTts &&
_soundType != SoundType.LoopWhileMoving &&
_soundType != SoundType.Livestream &&
_soundType != SoundType.MainPlayerCombat &&
_soundType != SoundType.OtherPlayerCombat &&
_soundType != SoundType.NPC &&
_soundType != SoundType.LoopUntilStopped &&
_soundType != SoundType.PlayWhileMoving &&
_player.TotalTime.TotalSeconds > 13) {
_soundType = SoundType.Loop;
}
switch (audioPlayerType) {
case AudioOutputType.VLCExperimental:
case AudioOutputType.WaveOut:
var waveOut = new WaveOutEvent();
if (_parent.AudioOutputDeviceIndex >= -1 && _parent.AudioOutputDeviceIndex < NAudio.Wave.WaveOut.DeviceCount) {
waveOut.DeviceNumber = _parent.AudioOutputDeviceIndex;
}
_wavePlayer = waveOut;
break;
case AudioOutputType.DirectSound:
_wavePlayer = new DirectSoundOut();
break;
case AudioOutputType.Wasapi:
_wavePlayer = new WasapiOut();
break;
}
if (_soundType != SoundType.MainPlayerCombat && _soundType != SoundType.OtherPlayerCombat) {
if (delay > 0) {
Thread.Sleep(delay);
}
}
if (_soundType == SoundType.Loop || _soundType == SoundType.LoopWhileMoving || _soundType == SoundType.PlayWhileMoving) {
if (_soundType != SoundType.MainPlayerCombat && _soundType != SoundType.OtherPlayerCombat && _soundType != SoundType.ChatSound) {
SoundLoopCheck();
}
// if (_soundType != SoundType.PlayWhileMoving) {
_loopStream = new LoopStream(_player) { EnableLooping = true, Parent = this };
desiredStream = _loopStream;
//}
} else if (_soundType == SoundType.LoopUntilStopped) {
_loopStream = new LoopStream(_player) { EnableLooping = true, Parent = this };
desiredStream = _loopStream;
}
float distance = Vector3.Distance(_camera.Position, CharacterObject.Position);
float newVolume = _parent.CalculateObjectVolume(_playerObject.Name, this);
ISampleProvider sampleProvider = null;
if (!lowPerformanceMode || _soundType != SoundType.MainPlayerCombat && _soundType != SoundType.MainPlayerTts && _soundType != SoundType.ChatSound) {
_meteringSampleProvider = new MeteringSampleProvider(desiredStream.ToSampleProvider());
_meteringSampleProvider.StreamVolume += _meteringSampleProvider_StreamVolume;
_volumeSampleProvider = new VolumeSampleProvider(_meteringSampleProvider);
_baseVolume = volume;
if (_soundType != SoundType.LoopUntilStopped) {
_volumeSampleProvider.Volume = (_volumeOffset * volume) * volumePercentage;
} else {
volumePercentage = 0;
_volumeSampleProvider.Volume = 0;
}
if (_spatialAllowed)
{
_panningSampleProvider = new PanningSampleProvider(
_player.WaveFormat.Channels == 1 ? _volumeSampleProvider : _volumeSampleProvider.ToMono());
Vector3 dir = CharacterObject.Position - _camera.Position;
float direction = AngleDir(_camera.Forward, dir, _camera.Top);
_panningSampleProvider.Pan = Math.Clamp(direction / 3, -1, 1);
sampleProvider = _panningSampleProvider;
}
else
{
sampleProvider = _volumeSampleProvider;
}
} else {
_meteringSampleProvider = new MeteringSampleProvider(desiredStream.ToSampleProvider());
_meteringSampleProvider.StreamVolume += _meteringSampleProvider_StreamVolume;
_volumeSampleProvider = new VolumeSampleProvider(_meteringSampleProvider);
_baseVolume = volume;
if (_soundType != SoundType.LoopUntilStopped) {
_volumeSampleProvider.Volume = (_volumeOffset * volume) * volumePercentage;
} else {
volumePercentage = 0;
_volumeSampleProvider.Volume = 0;
}
Pan = 0;
sampleProvider = _volumeSampleProvider;
}
if (_wavePlayer != null) {
try {
try {
_wavePlayer?.Init(sampleProvider);
} catch {
}
if (_soundType == SoundType.Loop ||
_soundType == SoundType.MainPlayerVoice ||
_soundType == SoundType.OtherPlayer) {
_player.CurrentTime = skipAhead;
if (_player.TotalTime.TotalSeconds > 13) {
_player.CurrentTime += latencyTimer.Elapsed;
}
} else {
_player.Position = 0;
}
if (_soundType == SoundType.MainPlayerCombat ||
_soundType == SoundType.OtherPlayerCombat) {
try {
var waveOutEvent = _wavePlayer as WaveOutEvent;
if (waveOutEvent != null) {
waveOutEvent.DesiredLatency = 50;
}
} catch {
}
}
_wavePlayer.PlaybackStopped += delegate {
PlaybackStopped?.Invoke(this, "OK");
};
if (_wavePlayer != null) {
_wavePlayer?.Play();
}
if (_soundType == SoundType.LoopUntilStopped) {
MountLoopCheck();
}
} catch (Exception e) {
OnErrorReceived?.Invoke(this, new MediaError() { Exception = e });
PlaybackStopped?.Invoke(this, "ERR");
}
}
} else {
try {
_parent.LastFrame = new byte[0];
string location = _libVLCPath + @"\libvlc\win-x64";
Core.Initialize(location);
libVLC = new LibVLC("--vout", "none");
var media = new Media(libVLC, mediaPath, mediaPath.StartsWith("http") || mediaPath.StartsWith("rtmp")
? FromType.FromLocation : FromType.FromPath);
await media.Parse(mediaPath.StartsWith("http") || mediaPath.StartsWith("rtmp")
? MediaParseOptions.ParseNetwork : MediaParseOptions.ParseLocal);
_vlcPlayer = new MediaPlayer(media);
_vlcPlayer.SetAudioOutput("waveout");
//var processingCancellationTokenSource = new CancellationTokenSource();
//_vlcPlayer.Stopped += (s, e) => processingCancellationTokenSource.CancelAfter(1);
_vlcPlayer.Stopped += delegate { _parent.LastFrame = new byte[0]; };
if (mediaPath.StartsWith("http") || mediaPath.StartsWith("rtmp") || mediaPath.EndsWith(".mp4") || mediaPath.EndsWith(".avi")) {
_vlcPlayer.SetVideoFormat("RV32", _width, _height, _pitch);
_vlcPlayer.SetVideoCallbacks(Lock, null, Display);
}
_baseVolume = volume;
Volume = volume;
_vlcPlayer.Play();
_vlcWasAbleToStart = true;
} catch (Exception e) {
OnErrorReceived?.Invoke(this, new MediaError() { Exception = e });
PlaybackStopped?.Invoke(this, "OK");
}
}
}
} catch (Exception e) {
OnErrorReceived?.Invoke(this, new MediaError() { Exception = e });
PlaybackStopped?.Invoke(this, "ERR");
}
});
}
public async void ChangeVideoStream(string soundPath, float width) {
try {
if (_vlcWasAbleToStart) {
var media = new Media(libVLC, soundPath, soundPath.StartsWith("http") || soundPath.StartsWith("rtmp")
? FromType.FromLocation : FromType.FromPath);
await media.Parse(soundPath.StartsWith("http") || soundPath.StartsWith("rtmp")
? MediaParseOptions.ParseNetwork : MediaParseOptions.ParseLocal);
_vlcPlayer.Media = media;
_vlcPlayer.Play();
}
} catch (Exception e) { OnErrorReceived?.Invoke(this, new MediaError() { Exception = e }); }
}
public static float AngleDir(Vector3 fwd, Vector3 targetDir, Vector3 up) {
Vector3 perp = Vector3.Cross(fwd, targetDir);
float dir = Vector3.Dot(perp, up);
return dir;
}
private IntPtr Lock(IntPtr opaque, IntPtr planes) {
try {
_currentMappedFile = MemoryMappedFile.CreateNew(null, _pitch * _lines);
_currentMappedViewAccessor = _currentMappedFile.CreateViewAccessor();
Marshal.WriteIntPtr(planes, _currentMappedViewAccessor.SafeMemoryMappedViewHandle.DangerousGetHandle());
return IntPtr.Zero;
} catch {
return IntPtr.Zero;
}
}
public void ResetVolume() {
if (_wavePlayer != null) {
_wavePlayer.Volume = 1;
}
}
private void Display(IntPtr opaque, IntPtr picture) {
if (!Invalidated) {
try {
using (var image = new Image<Bgra32>((int)(_pitch / _bytePerPixel), (int)_lines))
using (var sourceStream = _currentMappedFile.CreateViewStream()) {
var mg = image.GetPixelMemoryGroup();
for (int i = 0; i < mg.Count; i++) {
sourceStream.Read(MemoryMarshal.AsBytes(mg[i].Span));
}
lock (_parent.LastFrame) {
MemoryStream stream = new MemoryStream();
image.SaveAsJpeg(stream);
stream.Flush();
stream.Position = 0;
_parent.LastFrame = stream.ToArray();
}
}
_currentMappedViewAccessor.Dispose();
_currentMappedFile.Dispose();
_currentMappedFile = null;
_currentMappedViewAccessor = null;
} catch (Exception e) { OnErrorReceived?.Invoke(this, new MediaError() { Exception = e }); }
} else {
try {
_vlcPlayer.Stop();
} catch (Exception e) { OnErrorReceived?.Invoke(this, new MediaError() { Exception = e }); }
}
}
public void Dispose() {
if (_disposed) {
return;
}
_disposed = true;
_parent.OnCleanupTime -= _parent_OnCleanupTime;
Stop();
Volume = 0;
try { _vlcPlayer?.Dispose(); } catch { }
_vlcPlayer = null;
try { libVLC?.Dispose(); } catch { }
libVLC = null;
}
}
public enum SoundType {
MainPlayerTts,
MainPlayerVoice,
OtherPlayerTts,
OtherPlayer,
Emote,
Loop,
LoopWhileMoving,
Livestream,
MainPlayerCombat,
OtherPlayerCombat,
NPC,
ChatSound,
LoopUntilStopped,
PlayWhileMoving
}
}