-
Notifications
You must be signed in to change notification settings - Fork 45
Expand file tree
/
Copy pathUSharpVideoPlayer.cs
More file actions
1583 lines (1281 loc) · 52.2 KB
/
USharpVideoPlayer.cs
File metadata and controls
1583 lines (1281 loc) · 52.2 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
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#define USE_SERVER_TIME_MS // Uses GetServerTimeMilliseconds instead of the server datetime which in theory is less reliable
using JetBrains.Annotations;
using UdonSharp;
using UnityEngine;
using VRC.SDK3.Components.Video;
using VRC.SDKBase;
namespace UdonSharp.Video
{
[AddComponentMenu("Udon Sharp/Video/USharp Video Player")]
[UdonBehaviourSyncMode(BehaviourSyncMode.Manual)]
public class USharpVideoPlayer : UdonSharpBehaviour
{
// Video player references
private VideoPlayerManager _videoPlayerManager;
[Tooltip("Whether to allow video seeking with the progress bar on the video")]
[PublicAPI]
public bool allowSeeking = true;
[Tooltip("If enabled defaults to unlocked so anyone can put in a URL")]
[SerializeField]
private bool defaultUnlocked = true;
[Tooltip("If enabled allows the instance creator to always control the video player regardless of if they are master or not")]
[PublicAPI]
public bool allowInstanceCreatorControl = true;
[Tooltip("How often the video player should check if it is more than Sync Threshold out of sync with the video time")]
[PublicAPI]
public float syncFrequency = 8.0f;
[Tooltip("How many seconds desynced from the owner the client needs to be to trigger a resync")]
[PublicAPI]
public float syncThreshold = 0.85f;
[Range(0f, 1f)]
[Tooltip("The default volume for the volume slider on the video player")]
[SerializeField]
private float defaultVolume = 0.5f;
#pragma warning disable CS0414
[Tooltip("The max range of the audio sources on this video player")]
[SerializeField]
private float audioRange = 40f;
#pragma warning restore CS0414
/// <summary>
/// Local offset from the network time to sync the video
/// Can be used for things like making a video player sync up with someone singing
/// </summary>
[PublicAPI, System.NonSerialized]
public float localSyncOffset;
[Tooltip("List of urls to play automatically when the world is loaded until someone puts in another URL")]
public VRCUrl[] playlist = new VRCUrl[0];
[Tooltip("Should default to the stream player? This is usually used when you want to put a live stream in the default playlist.")]
[SerializeField]
private bool defaultStreamMode;
[Tooltip("If the default playlist should loop")]
[PublicAPI]
public bool loopPlaylist;
[Tooltip("If the default playlist should be shuffled upon world load")]
public bool shufflePlaylist;
/// <summary>
/// The URL that we should currently be playing and that other people are playing
/// </summary>
[UdonSynced]
private VRCUrl _syncedURL = VRCUrl.Empty;
/// <summary>
/// The video sequence identifier, gets incremented whenever a new video is put in. Used to determine in combination with _currentVideoIdx if we need to load the new URL
/// </summary>
[UdonSynced]
private int _syncedVideoIdx;
private int _currentVideoIdx;
/// <summary>
/// If we're locked so only the master may put in URLs
/// </summary>
[UdonSynced]
private bool _isMasterOnly = true;
[UdonSynced]
private int _nextPlaylistIndex;
#if USE_SERVER_TIME_MS
[UdonSynced]
private int _networkTimeVideoStart;
private int _localNetworkTimeStart;
#else
[UdonSynced]
private double _videoStartNetworkTime;
private double _localVideoStartTime;
[UdonSynced]
private long _networkTimeStart;
private System.DateTime _localNetworkTimeStart;
#endif
[UdonSynced]
private bool _ownerPlaying;
[UdonSynced]
private bool _ownerPaused;
private bool _locallyPaused;
[UdonSynced]
private bool _loopVideo;
private bool _localLoopVideo;
[UdonSynced]
private int _shuffleSeed;
// The last unpaused time in the video
private float _lastVideoTime;
VideoControlHandler[] _registeredControlHandlers;
VideoScreenHandler[] _registeredScreenHandlers;
UdonSharpBehaviour[] _registeredCallbackReceivers;
// Video loading state
const int MAX_RETRY_COUNT = 4;
const float DEFAULT_RETRY_TIMEOUT = 35.0f;
const float RATE_LIMIT_RETRY_TIMEOUT = 5.5f;
const float VIDEO_ERROR_RETRY_TIMEOUT = 5f;
const float PLAYLIST_ERROR_RETRY_COUNT = 4;
private bool _loadingVideo;
private float _currentLoadingTime; // Counts down to 0 while loading
private int _currentRetryCount;
private float _videoTargetStartTime;
private int _playlistErrorCount;
private bool _waitForSync;
// Player mode tracking
const int PLAYER_MODE_UNITY = 0;
const int PLAYER_MODE_AVPRO = 1;
[UdonSynced]
private int currentPlayerMode = PLAYER_MODE_UNITY;
private int _localPlayerMode = PLAYER_MODE_UNITY;
private bool _videoSync = true;
private bool _ranInit;
private void Start()
{
if (_ranInit)
return;
_ranInit = true;
_videoPlayerManager = GetVideoManager();
_videoPlayerManager.Start();
if (_registeredControlHandlers == null)
_registeredControlHandlers = new VideoControlHandler[0];
if (_registeredCallbackReceivers == null)
_registeredCallbackReceivers = new UdonSharpBehaviour[0];
if (Networking.IsOwner(gameObject))
{
if (defaultUnlocked)
_isMasterOnly = false;
if (defaultStreamMode)
{
SetPlayerMode(PLAYER_MODE_AVPRO);
_nextPlaylistIndex = 0; // SetPlayerMode sets this to -1, but we want to be able to keep it intact so reset to 0
}
_shuffleSeed = Random.Range(0, 10000);
}
_lastMasterLocked = _isMasterOnly;
SetUILocked(_isMasterOnly);
#if !USE_SERVER_TIME_MS
_networkTimeStart = Networking.GetNetworkDateTime().Ticks;
_localNetworkTimeStart = new System.DateTime(_networkTimeStart, System.DateTimeKind.Utc);
#endif
PlayNextVideoFromPlaylist();
SetVolume(defaultVolume);
// Serialize the default setup state from the master once regardless of if a video has played
QueueSerialize();
LogMessage("USharpVideo v1.0.1 Initialized");
}
public override void OnVideoReady()
{
ResetVideoLoad();
_playlistErrorCount = 0;
if (IsUsingAVProPlayer())
{
float duration = _videoPlayerManager.GetDuration();
if (duration == float.MaxValue || float.IsInfinity(duration) || IsRTSPStream())
_videoSync = false;
else
_videoSync = true;
}
else
_videoSync = true;
if (_videoSync)
{
if (Networking.IsOwner(gameObject))
{
_waitForSync = false;
_videoPlayerManager.Play();
}
else
{
if (_ownerPlaying)
{
_waitForSync = false;
_locallyPaused = false;
_videoPlayerManager.Play();
SyncVideo();
}
else
{
#if USE_SERVER_TIME_MS
if (_networkTimeVideoStart == 0)
#else
if (_videoStartNetworkTime == 0f || _videoStartNetworkTime > GetNetworkTime() - _videoPlayerManager.GetDuration()) // Todo: remove the 0f check and see how this actually gets set to 0 while the owner is playing
#endif
{
_waitForSync = true;
SetStatusText("Waiting for owner sync...");
}
else
{
_waitForSync = false;
SyncVideo();
SetStatusText("");
#if USE_SERVER_TIME_MS
LogMessage($"Loaded into world with complete video, duration: {_videoPlayerManager.GetDuration()}, start net time: {_networkTimeVideoStart}");
#else
LogMessage($"Loaded into world with complete video, duration: {_videoPlayerManager.GetDuration()}, start net time: {_videoStartNetworkTime}, subtracted net time {GetNetworkTime() - _videoPlayerManager.GetDuration()}");
#endif
}
}
}
}
else // Live streams should start asap
{
_waitForSync = false;
_videoPlayerManager.Play();
}
}
public override void OnVideoStart()
{
if (Networking.IsOwner(gameObject))
{
SetPausedInternal(false, false);
#if USE_SERVER_TIME_MS
_networkTimeVideoStart = Networking.GetServerTimeInMilliseconds() - (int)(_videoTargetStartTime * 1000f);
#else
_videoStartNetworkTime = GetNetworkTime() - _videoTargetStartTime;
#endif
if (IsInVideoMode())
{
_videoPlayerManager.SetTime(_videoTargetStartTime);
}
_ownerPlaying = true;
QueueSerialize();
LogMessage($"Started video: {_syncedURL}");
}
else if (!_ownerPlaying) // Watchers pause and wait for sync from owner
{
_videoPlayerManager.Pause();
_waitForSync = true;
}
else
{
SetPausedInternal(_ownerPaused, false);
SyncVideo();
LogMessage($"Started video: {_syncedURL}");
}
SetStatusText("");
_videoTargetStartTime = 0f;
SetUIPaused(_locallyPaused);
UpdateRenderTexture();
SendCallback("OnUSharpVideoPlay");
}
private bool IsRTSPStream()
{
string urlStr = _syncedURL.ToString();
return IsUsingAVProPlayer() &&
_videoPlayerManager.GetDuration() == 0f &&
IsRTSPURL(urlStr);
}
private bool IsRTSPURL(string urlStr)
{
return urlStr.StartsWith("rtsp://", System.StringComparison.OrdinalIgnoreCase) ||
urlStr.StartsWith("rtmp://", System.StringComparison.OrdinalIgnoreCase) || // RTMP isn't really supported in VRC's context and it's probably never going to be, but we'll just be safe here
urlStr.StartsWith("rtspt://", System.StringComparison.OrdinalIgnoreCase) || // rtsp over TCP
urlStr.StartsWith("rtspu://", System.StringComparison.OrdinalIgnoreCase); // rtsp over UDP
}
public override void OnVideoEnd()
{
// VRC falsely throws OnVideoEnd instantly on RTSP streams since they report 0 length
if (IsRTSPStream())
return;
if (Networking.IsOwner(gameObject))
{
_ownerPlaying = false;
_ownerPaused = _locallyPaused = false;
SetStatusText("");
SetUIPaused(false);
PlayNextVideoFromPlaylist();
QueueSerialize();
}
SendCallback("OnUSharpVideoEnd");
UpdateRenderTexture();
}
// Workaround for bug that needs to be addressed in U# where calling built in methods with parameters will get the parameters overwritten when called from other UdonBehaviours
public void _OnVideoErrorCallback(VideoError videoError)
{
OnVideoError(videoError);
}
public override void OnVideoError(VideoError videoError)
{
if (videoError == VideoError.RateLimited)
{
SetStatusText("Rate limited, retrying...");
LogWarning("Rate limited, retrying...");
_currentLoadingTime = RATE_LIMIT_RETRY_TIMEOUT;
return;
}
if (videoError == VideoError.PlayerError)
{
SetStatusText("Video error, retrying...");
LogError("Video player error when trying to load " + _syncedURL);
_loadingVideo = true; // Apparently OnVideoReady gets fired erroneously??
_currentLoadingTime = VIDEO_ERROR_RETRY_TIMEOUT;
return;
}
ResetVideoLoad();
_videoTargetStartTime = 0f;
_videoPlayerManager.Stop();
LogError($"Video '{_syncedURL}' failed to play with error {videoError}");
switch (videoError)
{
case VideoError.InvalidURL:
SetStatusText("Invalid URL");
break;
case VideoError.AccessDenied:
SetStatusText("Video blocked, enable untrusted URLs");
break;
default:
SetStatusText("Failed to load video");
break;
}
++_playlistErrorCount;
PlayNextVideoFromPlaylist();
SendCallback("OnUSharpVideoError");
}
public override void OnVideoPause() { }
public override void OnVideoPlay() { }
public override void OnVideoLoop()
{
#if USE_SERVER_TIME_MS
_localNetworkTimeStart = _networkTimeVideoStart = Networking.GetServerTimeInMilliseconds();
#else
_localVideoStartTime = _videoStartNetworkTime = GetNetworkTime();
#endif
QueueSerialize();
}
private float _lastCurrentTime;
private void Update()
{
if (_loadingVideo)
UpdateVideoLoad();
if (_locallyPaused)
{
if (IsInVideoMode())
{
// Keep the target time the same while paused
#if USE_SERVER_TIME_MS
_networkTimeVideoStart = Networking.GetServerTimeInMilliseconds() - (int)(_videoPlayerManager.GetTime() * 1000f);
#else
_videoStartNetworkTime = GetNetworkTime() - _videoPlayerManager.GetTime();
#endif
}
}
else
_lastCurrentTime = _videoPlayerManager.GetTime();
if (Networking.IsOwner(gameObject) || !_waitForSync)
{
SyncVideoIfTime();
}
else if (_ownerPlaying)
{
_videoPlayerManager.Play();
LogMessage($"Started video: {_syncedURL}");
_waitForSync = false;
SyncVideo();
}
UpdateRenderTexture(); // Needed because AVPro can swap textures whenever
}
/// <summary>
/// Uncomment this to prevent people from taking ownership of the video player when they shouldn't be able to
/// </summary>
//public override bool OnOwnershipRequest(VRCPlayerApi requestingPlayer, VRCPlayerApi requestedOwner)
//{
// return !_isMasterOnly || IsPrivlegedUser(requestedOwner);
//}
private bool _lastMasterLocked;
public override void OnDeserialization()
{
if (Networking.IsOwner(gameObject))
return;
#if !USE_SERVER_TIME_MS
_localNetworkTimeStart = new System.DateTime(_networkTimeStart, System.DateTimeKind.Utc);
#endif
SetPausedInternal(_ownerPaused, false);
SetLoopingInternal(_loopVideo);
if (_localPlayerMode != currentPlayerMode)
SetPlayerMode(currentPlayerMode);
if (_isMasterOnly != _lastMasterLocked)
SetLockedInternal(_isMasterOnly);
if (!_ownerPlaying && _videoPlayerManager.IsPlaying())
_videoPlayerManager.Stop();
if (_currentVideoIdx != _syncedVideoIdx)
{
_currentVideoIdx = _syncedVideoIdx;
_videoPlayerManager.Stop();
StartVideoLoad(_syncedURL);
#if USE_SERVER_TIME_MS
_localNetworkTimeStart = _networkTimeVideoStart;
#else
_localVideoStartTime = _videoStartNetworkTime;
#endif
LogMessage("Playing synced " + _syncedURL);
}
#if USE_SERVER_TIME_MS
else if (_networkTimeVideoStart != _localNetworkTimeStart) // Detect seeks
{
_localNetworkTimeStart = _networkTimeVideoStart;
#else
else if (_videoStartNetworkTime != _localVideoStartTime) // Detect seeks
{
_localVideoStartTime = _videoStartNetworkTime;
#endif
SyncVideo();
}
if (!_locallyPaused && IsInVideoMode())
{
float duration = GetVideoManager().GetDuration();
// If the owner did a seek on the video after it finished, we need to start playing it again
#if USE_SERVER_TIME_MS
if ((Networking.GetServerTimeInMilliseconds() - _networkTimeVideoStart) / 1000f < duration - 3f)
#else
if (GetNetworkTime() - _videoStartNetworkTime < duration - 3f)
#endif
_videoPlayerManager.Play();
}
SendCallback("OnUSharpVideoDeserialization");
}
public override void OnOwnershipTransferred(VRCPlayerApi player)
{
SendUIOwnerUpdate();
SendCallback("OnUSharpVideoOwnershipChange");
}
// Supposedly there's some case where late joiners don't receive data, so do a serialization just in case here.
public override void OnPlayerJoined(VRCPlayerApi player)
{
if (!player.isLocal)
QueueSerialize();
}
/// <summary>
/// Stops playback of the video completely and clears data
/// </summary>
[PublicAPI]
public void StopVideo()
{
if (!Networking.IsOwner(gameObject))
return;
#if USE_SERVER_TIME_MS
_networkTimeVideoStart = 0;
#else
_videoStartNetworkTime = 0f;
#endif
_ownerPlaying = false;
_locallyPaused = _ownerPaused = false;
_videoTargetStartTime = 0f;
_lastCurrentTime = 0f;
_videoPlayerManager.Stop();
SetUIPaused(false);
ResetVideoLoad();
QueueSerialize();
SendCallback("OnUSharpVideoStop");
}
/// <summary>
/// Play a video with the specified URL, only works if the player is allowed to use the video player
/// </summary>
/// <param name="url"></param>
[PublicAPI]
public void PlayVideo(VRCUrl url)
{
PlayVideoInternal(url, true);
}
/// <summary>
/// Returns the URL that the video player currently has loaded
/// </summary>
/// <returns></returns>
[PublicAPI]
public VRCUrl GetCurrentURL() => _syncedURL;
private void PlayVideoInternal(VRCUrl url, bool stopPlaylist)
{
if (!CanControlVideoPlayer())
return;
string urlStr = url.Get();
if (!ValidateURL(urlStr))
return;
bool wasOwner = Networking.IsOwner(gameObject);
TakeOwnership();
if (stopPlaylist)
_nextPlaylistIndex = -1;
StopVideo();
_syncedURL = url;
if (wasOwner)
++_syncedVideoIdx;
else // Add two to avoid having conflicts where the old owner increases the count
_syncedVideoIdx += 2;
_currentVideoIdx = _syncedVideoIdx;
StartVideoLoad(url);
_ownerPlaying = false;
#if USE_SERVER_TIME_MS
_networkTimeVideoStart = 0;
#endif
_videoTargetStartTime = GetVideoStartTime(urlStr);
QueueSerialize();
SendCallback("OnUSharpVideoLoadStart");
}
private void ResetVideoLoad()
{
_loadingVideo = false;
_currentRetryCount = 0;
_currentLoadingTime = DEFAULT_RETRY_TIMEOUT;
}
private void UpdateVideoLoad()
{
//if (_loadingVideo) // Checked in caller now since it's cheaper
{
_currentLoadingTime -= Time.deltaTime;
if (_currentLoadingTime <= 0f)
{
_currentLoadingTime = DEFAULT_RETRY_TIMEOUT;
if (++_currentRetryCount > MAX_RETRY_COUNT)
{
OnVideoError(VideoError.Unknown);
}
else
{
LogMessage("Retrying load");
SetStatusText("Retrying load...");
_videoPlayerManager.LoadURL(_syncedURL);
}
}
}
}
private float _lastSyncTime;
private void SyncVideoIfTime()
{
float timeSinceStartup = Time.realtimeSinceStartup;
if (timeSinceStartup - _lastSyncTime > syncFrequency)
{
_lastSyncTime = timeSinceStartup;
SyncVideo();
}
}
/// <summary>
/// Syncs the video time if it's too far diverged from the network time
/// </summary>
[PublicAPI]
public void SyncVideo()
{
if (IsInVideoMode())
{
#if USE_SERVER_TIME_MS
float offsetTime = Mathf.Clamp((Networking.GetServerTimeInMilliseconds() - _networkTimeVideoStart) / 1000f + localSyncOffset, 0f, _videoPlayerManager.GetDuration());
#else
float offsetTime = Mathf.Clamp((float)(GetNetworkTime() - _videoStartNetworkTime) + localSyncOffset, 0f, _videoPlayerManager.GetDuration());
#endif
if (Mathf.Abs(_videoPlayerManager.GetTime() - offsetTime) > syncThreshold)
{
_videoPlayerManager.SetTime(offsetTime);
LogMessage($"Syncing video to {offsetTime:N2}");
}
}
}
/// <summary>
/// Syncs the video time regardless of how far diverged it is from the network time, can be used as a less aggressive audio resync in some cases
/// </summary>
[PublicAPI]
public void ForceSyncVideo()
{
if (IsInVideoMode())
{
#if USE_SERVER_TIME_MS
float offsetTime = Mathf.Clamp((Networking.GetServerTimeInMilliseconds() - _networkTimeVideoStart) / 1000f + localSyncOffset, 0f, _videoPlayerManager.GetDuration());
#else
float offsetTime = Mathf.Clamp((float)(GetNetworkTime() - _videoStartNetworkTime) + localSyncOffset, 0f, _videoPlayerManager.GetDuration());
#endif
float syncNudgeTime = Mathf.Max(0f, offsetTime - 1f);
_videoPlayerManager.SetTime(syncNudgeTime); // Seek to slightly earlier before syncing to the real time to get the video player to jump cleanly
_videoPlayerManager.SetTime(offsetTime);
LogMessage($"Syncing video to {offsetTime:N2}");
}
}
private void StartVideoLoad(VRCUrl url)
{
#if UNITY_EDITOR
LogMessage($"Started video load for URL: {url}");
#else
LogMessage($"Started video load for URL: {url}, requested by {Networking.GetOwner(gameObject).displayName}");
#endif
SetStatusText("Loading video...");
ResetVideoLoad();
_loadingVideo = true;
_videoPlayerManager.LoadURL(url);
AddUIUrlHistory(url);
}
private void SetPausedInternal(bool paused, bool updatePauseTime)
{
if (Networking.IsOwner(gameObject))
_ownerPaused = paused;
if (_locallyPaused != paused)
{
_locallyPaused = paused;
if (IsInVideoMode())
{
if (_ownerPaused)
_videoPlayerManager.Pause();
else
{
_videoPlayerManager.Play();
if (updatePauseTime)
_videoTargetStartTime = _lastCurrentTime;
}
}
else
{
if (_ownerPaused)
_videoPlayerManager.Stop();
else
StartVideoLoad(_syncedURL);
}
SetUIPaused(paused);
if (_locallyPaused)
SendCallback("OnUSharpVideoPause");
else
SendCallback("OnUSharpVideoUnpause");
}
QueueRateLimitedSerialize();
}
/// <summary>
/// Pauses the video if we have control of the video player.
/// </summary>
/// <param name="paused"></param>
[PublicAPI]
public void SetPaused(bool paused)
{
if (Networking.IsOwner(gameObject))
SetPausedInternal(paused, true);
}
[PublicAPI]
public bool IsPaused()
{
return _ownerPaused;
}
private void SetLoopingInternal(bool loop)
{
if (loop == _localLoopVideo)
return;
_loopVideo = _localLoopVideo = loop;
_videoPlayerManager.SetLooping(loop);
SetUILooping(loop);
QueueRateLimitedSerialize();
}
/// <summary>
/// Sets whether the currently playing video should loop and restart once it ends.
/// </summary>
/// <param name="loop"></param>
[PublicAPI]
public void SetLooping(bool loop)
{
if (Networking.IsOwner(gameObject))
SetLoopingInternal(loop);
}
[PublicAPI]
public bool IsLooping()
{
return _localLoopVideo;
}
[PublicAPI]
public float GetVolume() => _videoPlayerManager.GetVolume();
/// <summary>
/// Sets the audio source volume for the audio sources used by this video player.
/// </summary>
/// <param name="volume"></param>
[PublicAPI]
public void SetVolume(float volume)
{
volume = Mathf.Clamp01(volume);
if (volume == _videoPlayerManager.GetVolume())
return;
_videoPlayerManager.SetVolume(volume);
SetUIVolume(volume);
}
[PublicAPI]
public bool IsMuted() => _videoPlayerManager.IsMuted();
/// <summary>
/// Mutes audio from this video player
/// </summary>
/// <param name="muted"></param>
[PublicAPI]
public void SetMuted(bool muted)
{
_videoPlayerManager.SetMuted(muted);
SetUIMuted(muted);
}
private bool _delayedSyncAllowed = true;
private int _finalSyncCounter;
/// <summary>
/// Takes a float in the range 0 to 1 and seeks the video to that % through the time
/// Is intended to be used with progress bar-type-things
/// </summary>
/// <param name="progress"></param>
[PublicAPI]
public void SeekTo(float progress)
{
if (!allowSeeking || !Networking.IsOwner(gameObject))
return;
float newTargetTime = _videoPlayerManager.GetDuration() * progress;
_lastVideoTime = newTargetTime;
_lastCurrentTime = newTargetTime;
#if USE_SERVER_TIME_MS
_localNetworkTimeStart = _networkTimeVideoStart = Networking.GetServerTimeInMilliseconds() - (int)(newTargetTime * 1000f);
#else
_videoStartNetworkTime = GetNetworkTime() - newTargetTime;
_localVideoStartTime = _videoStartNetworkTime;
#endif
if (!_locallyPaused && !GetVideoManager().IsPlaying())
GetVideoManager().Play();
SyncVideo();
QueueRateLimitedSerialize();
}
/// <summary>
/// Used on things that are easily spammable to prevent flooding the network unintentionally.
/// Will allow 1 sync every half second and then will send a final sync to propagate the final changed values of things at the end
/// </summary>
private void QueueRateLimitedSerialize()
{
//QueueSerialize(); // Debugging line :D this serialization method can potentially hide some issues so we want to disable it sometimes and verify stuff works right
if (_delayedSyncAllowed)
{
QueueSerialize();
_delayedSyncAllowed = false;
SendCustomEventDelayedSeconds(nameof(_UnlockDelayedSync), 0.5f);
}
++_finalSyncCounter;
SendCustomEventDelayedSeconds(nameof(_SendFinalSync), 0.8f);
}
public void _UnlockDelayedSync()
{
_delayedSyncAllowed = true;
}
// Handles running a final sync after doing a QueueRateLimitedSerialize, so that the final changes of the seek time get propagated
public void _SendFinalSync()
{
if (--_finalSyncCounter == 0)
QueueSerialize();
}
/// <summary>
/// Determines if the local player can control this video player. This means the player is either the master, the instance creator, or the video player is unlocked.
/// </summary>
/// <returns></returns>
[PublicAPI]
public bool CanControlVideoPlayer()
{
return !_isMasterOnly || IsPrivilegedUser(Networking.LocalPlayer);
}
/// <summary>
/// If the given player is allowed to take important actions on this video player such as changing the video or locking the video player.
/// This is what you would extend if you want to add an access control list or something similar.
/// </summary>
/// <param name="player"></param>
/// <returns></returns>
[PublicAPI]
public bool IsPrivilegedUser(VRCPlayerApi player)
{
#if UNITY_EDITOR
if (player == null)
return true;
#endif
return player.isMaster || (allowInstanceCreatorControl && player.isInstanceOwner);
}
/// <summary>
/// Takes ownership of the video player if allowed
/// </summary>
[PublicAPI]
public void TakeOwnership()
{
if (Networking.IsOwner(gameObject))
return;
if (CanControlVideoPlayer())
Networking.SetOwner(Networking.LocalPlayer, gameObject);
}
[PublicAPI]
public void QueueSerialize()
{
if (!Networking.IsOwner(gameObject))
return;
RequestSerialization();
}
private bool _shuffled;
/// <summary>
/// Plays the next video from the video player's built-in playlist
/// </summary>
[PublicAPI]
public void PlayNextVideoFromPlaylist()
{
if (_nextPlaylistIndex == -1 || playlist.Length == 0 || !Networking.IsOwner(gameObject))
return;
if (loopPlaylist && _playlistErrorCount > PLAYLIST_ERROR_RETRY_COUNT)
{
LogError("Maximum number of retries for playlist video looping hit. Stopping playlist playback.");
_nextPlaylistIndex = -1;
return;
}
if (shufflePlaylist && !_shuffled)
{
Random.InitState(_shuffleSeed);
for (int i = 0; i < playlist.Length - 1; ++i)
{
int r = Random.Range(i, playlist.Length);
if (i == r) { continue; }
VRCUrl flipVal = playlist[r];
playlist[r] = playlist[i];
playlist[i] = flipVal;
}
_shuffled = true;
}
int currentIdx = _nextPlaylistIndex++;