-
Notifications
You must be signed in to change notification settings - Fork 1.9k
Expand file tree
/
Copy pathVideoPlayer2.tsx
More file actions
649 lines (579 loc) · 20 KB
/
VideoPlayer2.tsx
File metadata and controls
649 lines (579 loc) · 20 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
'use client';
import React, { useEffect, useRef, FunctionComponent, useState } from 'react';
import videojs from 'video.js';
import Player from 'video.js/dist/types/player';
import Hammer from 'hammerjs';
import 'video.js/dist/video-js.css';
import 'videojs-contrib-eme';
import 'videojs-mobile-ui/dist/videojs-mobile-ui.css';
import 'videojs-seek-buttons/dist/videojs-seek-buttons.css';
import 'videojs-mobile-ui';
import 'videojs-sprite-thumbnails';
import 'videojs-seek-buttons';
import { handleMarkAsCompleted } from '@/lib/utils';
import { useSearchParams } from 'next/navigation';
import './QualitySelectorControllBar';
import { YoutubeRenderer } from './YoutubeRenderer';
import { toast } from 'sonner';
import { createRoot } from 'react-dom/client';
import { PictureInPicture2 } from 'lucide-react';
import { AppxVideoPlayer } from './AppxVideoPlayer';
import { getVideoFromIndexedDB, decryptBlob } from '@/lib/offlineVideo';
// todo correct types
interface VideoPlayerProps {
setQuality: React.Dispatch<React.SetStateAction<string>>;
options: any;
onReady?: (player: Player) => void;
subtitles?: string;
contentId: number;
appxVideoId?: string;
appxCourseId?: string;
onVideoEnd: () => void;
}
interface TransformState {
scale: number;
lastScale: number;
translateX: number;
translateY: number;
lastPanX: number;
lastPanY: number;
}
interface ZoomIndicator extends HTMLDivElement {
timeoutId?: ReturnType<typeof setTimeout>;
}
const PLAYBACK_RATES: number[] = [0.5, 1, 1.25, 1.5, 1.75, 2];
const VOLUME_LEVELS: number[] = [0, 0.2, 0.4, 0.6, 0.8, 1.0];
export const VideoPlayer: FunctionComponent<VideoPlayerProps> = ({
setQuality,
options,
contentId,
onReady,
onVideoEnd,
appxVideoId,
appxCourseId,
}) => {
const videoRef = useRef<HTMLDivElement>(null);
const playerRef = useRef<Player | null>(null);
const [player, setPlayer] = useState<any>(null);
const [offlineUrl, setOfflineUrl] = useState<string | null>(null);
const searchParams = useSearchParams();
const vidUrl = offlineUrl || options.sources[0].src;
const togglePictureInPicture = async () => {
try {
if (document.pictureInPictureElement) {
await document.exitPictureInPicture();
} else if (document.pictureInPictureEnabled && playerRef.current) {
playerRef.current.requestPictureInPicture();
}
} catch (error) {
// Ignore specific errors that might occur during normal operation
if (
error instanceof Error &&
error.name !== 'NotAllowedError' &&
error.name !== 'NotSupportedError'
) {
console.error('Failed to toggle Picture-in-Picture mode:', error);
toast.error('Failed to toggle Picture-in-Picture mode.');
}
}
};
const PipButton = () => (
<button
onClick={togglePictureInPicture}
className="flex items-center justify-center text-white focus:outline-none focus:ring-2 focus:ring-primary focus:ring-offset-2 dark:focus:ring-offset-gray-800"
type="button"
title="Picture-in-Picture"
>
<span className="absolute inset-0 rounded bg-black bg-opacity-50 opacity-0 transition-opacity duration-200 group-hover:opacity-100"></span>
<PictureInPicture2 className="relative z-10 h-5 w-5" />
<span className="sr-only">Picture-in-Picture</span>
</button>
);
const createPipButton = (player: Player) => {
const pipButtonContainer = (player as any).controlBar.addChild('button', {
clickHandler: (event: any) => {
event.preventDefault();
event.stopPropagation();
togglePictureInPicture();
},
});
const root = createRoot(pipButtonContainer.el());
root.render(<PipButton />);
return pipButtonContainer;
};
const setupZoomFeatures = (player: any) => {
if (typeof window === 'undefined' || typeof document === 'undefined') return;
const videoEl = player.el().querySelector('video');
const container = player.el();
const transformState: TransformState = {
scale: 1,
lastScale: 1,
translateX: 0,
translateY: 0,
lastPanX: 0,
lastPanY: 0
};
// Zoom indicator
const zoomIndicator = document.createElement('div') as ZoomIndicator;
zoomIndicator.className = 'vjs-zoom-level';
container.appendChild(zoomIndicator);
// Optimized boundary calculation with memoization
const calculateBoundaries = (() => {
let lastDimensions: { width: number; height: number };
return () => {
const containerRect = container.getBoundingClientRect();
const videoAspect = videoEl.videoWidth / videoEl.videoHeight;
// returning cached values if dimensions haven't changed
if (lastDimensions?.width === containerRect.width &&
lastDimensions?.height === containerRect.height) {
return lastDimensions;
}
const containerAspect = containerRect.width / containerRect.height;
let actualWidth = containerRect.width;
let actualHeight = containerRect.height;
actualWidth = containerAspect > videoAspect
? actualHeight * videoAspect
: actualWidth;
actualHeight = containerAspect > videoAspect
? actualHeight
: actualWidth / videoAspect;
lastDimensions = {
width: actualWidth,
height: actualHeight
};
return lastDimensions;
};
})();
// Unified gesture handler
const handleGestureControl = (e: HammerInput) => {
const target = e.srcEvent.target as HTMLElement;
const isControlBar = target.closest('.vjs-control-bar');
if (!isControlBar && player.isFullscreen()) {
e.srcEvent.preventDefault();
e.srcEvent.stopPropagation();
}
};
// Configuring Hammer with proper types
const hammer = new Hammer.Manager(container, {
touchAction: 'none',
inputClass: Hammer.TouchInput
});
hammer.add(new Hammer.Pinch());
hammer.add(new Hammer.Pan({
threshold: 0,
direction: Hammer.DIRECTION_ALL
}));
// Optimized transform update with boundary enforcement
const updateTransform = () => {
const boundaries = calculateBoundaries();
const maxX = (boundaries.width * (transformState.scale - 1)) / 2;
const maxY = (boundaries.height * (transformState.scale - 1)) / 2;
transformState.translateX = Math.min(Math.max(
transformState.translateX,
-maxX
), maxX);
transformState.translateY = Math.min(Math.max(
transformState.translateY,
-maxY
), maxY);
videoEl.style.transform = `
scale(${transformState.scale})
translate3d(
${transformState.translateX / transformState.scale}px,
${transformState.translateY / transformState.scale}px,
0
)`;
};
// Unified pinch handler
hammer.on('pinchstart pinchmove', (e) => {
handleGestureControl(e);
if (!player.isFullscreen()) return;
if (e.type === 'pinchstart') {
transformState.lastScale = transformState.scale;
videoEl.classList.add('zoomed');
return;
}
transformState.scale = Math.min(
Math.max(transformState.lastScale * e.scale, 1),
3
);
updateTransform();
showZoomLevel();
});
// Unified pan handler
hammer.on('panstart panmove', (e) => {
handleGestureControl(e);
if (transformState.scale <= 1) return;
if (e.type === 'panstart') {
transformState.lastPanX = e.center.x;
transformState.lastPanY = e.center.y;
videoEl.style.transition = 'none';
return;
}
const deltaX = e.center.x - transformState.lastPanX;
const deltaY = e.center.y - transformState.lastPanY;
transformState.translateX += deltaX;
transformState.translateY += deltaY;
transformState.lastPanX = e.center.x;
transformState.lastPanY = e.center.y;
updateTransform();
});
// Optimized zoom indicator
const showZoomLevel = () => {
zoomIndicator.textContent = `${transformState.scale.toFixed(1)}x`;
zoomIndicator.style.opacity = '1';
if (zoomIndicator.timeoutId) clearTimeout(zoomIndicator.timeoutId);
zoomIndicator.timeoutId = setTimeout(() => {
zoomIndicator.style.opacity = '0';
}, 1000);
};
// Reset handler with animation frame
const resetZoom = () => {
transformState.scale = 1;
transformState.translateX = 0;
transformState.translateY = 0;
requestAnimationFrame(() => {
videoEl.style.transition = 'transform 0.3s ease-out';
updateTransform();
videoEl.classList.remove('zoomed');
});
};
// Adding resize observer for responsive boundaries
const resizeObserver = new ResizeObserver(() => {
if (player.isFullscreen()) updateTransform();
});
resizeObserver.observe(container);
// Reset zoom when exiting fullscreen
player.on('fullscreenchange', () => {
if (!player.isFullscreen()) {
resetZoom();
}
});
// Cleanup function
const cleanup = () => {
resizeObserver.disconnect();
hammer.destroy();
if (zoomIndicator.timeoutId) clearTimeout(zoomIndicator.timeoutId);
container.removeChild(zoomIndicator);
resetZoom();
};
player.on('dispose', cleanup);
return cleanup;
};
useEffect(() => {
if (!player) return;
const savedCaptionSetting = localStorage.getItem('captionSetting');
const tracks = player.textTracks();
if (savedCaptionSetting && player) {
for (let i = 0; i < tracks.length; i++) {
const track = tracks[i];
if (track) {
track.mode =
savedCaptionSetting === 'showing' ? 'showing' : 'disabled';
}
}
}
const handleTrackChange = () => {
for (let i = 0; i < tracks.length; i++) {
const track = tracks[i];
if (track.kind === 'subtitles' && track.language === 'en') {
track.addEventListener('modechange', () => {
localStorage.setItem('captionSetting', track.mode);
});
}
}
};
handleTrackChange();
return () => {
for (let i = 0; i < tracks.length; i++) {
const track = tracks[i];
track.removeEventListener('modechange', handleTrackChange);
}
};
}, [player]);
useEffect(() => {
const t = searchParams.get('timestamp');
if (contentId && player && !t) {
fetch(`/api/course/videoProgress?contentId=${contentId}`).then(
async (res) => {
const json = await res.json();
player.currentTime(json.progress || 0);
},
);
}
}, [contentId, player]);
useEffect(() => {
if (!player) {
return;
}
let volumeSetTimeout: ReturnType<typeof setInterval> | null = null;
const handleKeyPress = (event: KeyboardEvent) => {
const isShiftPressed = event.shiftKey;
const isModifierPressed = event.metaKey || event.ctrlKey || event.altKey;
const activeElement = document.activeElement;
const tracks: TextTrackList = player.textTracks();
if (
activeElement?.tagName.toLowerCase() === 'input' ||
activeElement?.tagName.toLowerCase() === 'textarea' ||
isModifierPressed
) {
return; // Do nothing if the active element is an input or textarea
}
if (event.code === 'KeyT') {
player.playbackRate(2);
}
if (isShiftPressed) {
const currentIndexPeriod: number = PLAYBACK_RATES.indexOf(
player.playbackRate(),
);
const newIndexPeriod: number =
currentIndexPeriod !== PLAYBACK_RATES.length - 1
? currentIndexPeriod + 1
: currentIndexPeriod;
const currentIndexComma = PLAYBACK_RATES.indexOf(player.playbackRate());
const newIndexComma =
currentIndexComma !== 0 ? currentIndexComma - 1 : currentIndexComma;
const currentIndexUp = VOLUME_LEVELS.indexOf(player.volume());
const newIndexUp =
currentIndexUp !== VOLUME_LEVELS.length - 1
? currentIndexUp + 1
: currentIndexUp;
const currentIndexDown = VOLUME_LEVELS.indexOf(player.volume());
const newIndexDown =
currentIndexDown !== 0 ? currentIndexDown - 1 : currentIndexDown;
switch (event.code) {
case 'Period': // Increase playback speed
player.playbackRate(PLAYBACK_RATES[newIndexPeriod]);
event.stopPropagation();
break;
case 'Comma': // Decrease playback speed
player.playbackRate(PLAYBACK_RATES[newIndexComma]);
event.stopPropagation();
break;
case 'ArrowUp': // Increase volume
videoRef.current?.children[0].children[6].children[3].classList.add(
'vjs-hover',
);
if (volumeSetTimeout !== null) clearTimeout(volumeSetTimeout);
volumeSetTimeout = setTimeout(() => {
videoRef.current?.children[0].children[6].children[3].classList.remove(
'vjs-hover',
);
}, 1000);
player.volume(VOLUME_LEVELS[newIndexUp]);
event.stopPropagation();
break;
case 'ArrowDown': // Decrease volume
videoRef.current?.children[0].children[6].children[3].classList.add(
'vjs-hover',
);
if (volumeSetTimeout !== null) clearTimeout(volumeSetTimeout);
volumeSetTimeout = setTimeout(() => {
videoRef.current?.children[0].children[6].children[3].classList.remove(
'vjs-hover',
);
}, 1000);
player.volume(VOLUME_LEVELS[newIndexDown]);
event.stopPropagation();
break;
}
return;
}
switch (event.code) {
case 'Space': // Space bar for play/pause
if (player.paused()) {
player.play();
event.stopPropagation();
} else {
player.pause();
event.stopPropagation();
}
event.preventDefault();
break;
case 'ArrowRight': // Right arrow for seeking forward 5 seconds
player.currentTime(player.currentTime() + 5);
event.stopPropagation();
break;
case 'ArrowLeft': // Left arrow for seeking backward 5 seconds
player.currentTime(player.currentTime() - 5);
event.stopPropagation();
break;
case 'ArrowUp': // Arrow up for increasing volume
event.preventDefault();
player.volume(player.volume() + 0.1);
event.stopPropagation();
break;
case 'ArrowDown': // Arow dowwn for decreasing volume
event.preventDefault();
player.volume(player.volume() - 0.1);
event.stopPropagation();
break;
case 'KeyF': // F key for fullscreen
if (player.isFullscreen_) document.exitFullscreen();
else player.requestFullscreen();
event.stopPropagation();
break;
case 'KeyR': // 'R' key to restart playback from the beginning
player.currentTime(0);
event.stopPropagation();
break;
case 'KeyM': // 'M' key to toggle mute/unmute
if (player.volume() === 0) {
player.volume(1);
} else {
player.volume(0);
}
event.stopPropagation();
break;
case 'KeyK': // 'K' key for play/pause toggle
if (player.paused()) {
player.play();
} else {
player.pause();
}
event.stopPropagation();
break;
case 'KeyJ': // 'J' key for seeking backward 10 seconds multiplied by the playback rate
player.currentTime(player.currentTime() - 10 * player.playbackRate());
event.stopPropagation();
break;
case 'KeyL': // 'L' key for seeking forward 10 seconds multiplied by the playback rate
player.currentTime(player.currentTime() + 10 * player.playbackRate());
event.stopPropagation();
break;
case 'KeyP': // 'P' key to toggle picture-in-picture(pip) mode
togglePictureInPicture();
event.stopPropagation();
break;
case 'KeyC':
for (let i = 0; i < tracks.length; i++) {
const track = tracks[i];
if (track.kind === 'subtitles' && track.language === 'en') {
if (track.mode === 'disabled') track.mode = 'showing';
else track.mode = 'disabled';
}
}
event.stopPropagation();
break;
case 'Digit1':
player.currentTime(player.duration() * 0.1);
event.stopPropagation();
break;
case 'Digit2':
player.currentTime(player.duration() * 0.2);
event.stopPropagation();
break;
case 'Digit3':
player.currentTime(player.duration() * 0.3);
event.stopPropagation();
break;
case 'Digit4':
player.currentTime(player.duration() * 0.4);
event.stopPropagation();
break;
case 'Digit5':
player.currentTime(player.duration() * 0.5);
event.stopPropagation();
break;
case 'Digit6':
player.currentTime(player.duration() * 0.6);
event.stopPropagation();
break;
case 'Digit7':
player.currentTime(player.duration() * 0.7);
event.stopPropagation();
break;
case 'Digit8':
player.currentTime(player.duration() * 0.8);
event.stopPropagation();
break;
case 'Digit9':
player.currentTime(player.duration() * 0.9);
event.stopPropagation();
break;
case 'Digit0':
player.currentTime(0);
event.stopPropagation();
break;
}
};
const handleKeyUp = (event: any) => {
if (event.code === 'KeyT') {
player.playbackRate(1);
}
};
document.addEventListener('keydown', handleKeyPress, { capture: true });
document.addEventListener('keyup', handleKeyUp);
// Cleanup function
return () => {
document.removeEventListener('keydown', handleKeyPress);
};
}, [player]);
useEffect(() => {
if (!player) {
return;
}
let interval = 0;
const handleVideoProgress = () => {
if (!player) {
return;
}
interval = window.setInterval(
async () => {
if (!player) {
return;
}
//@ts-ignore
if (player?.paused()) {
return;
}
const currentTime = player.currentTime();
if (contentId) {
await fetch('/api/course/videoProgress', {
method: 'POST',
body: JSON.stringify({
contentId,
progress: currentTime,
}),
headers: {
'Content-Type': 'application/json',
},
});
}
},
1000,
);
};
handleVideoProgress();
return () => {
if (interval) {
clearInterval(interval);
}
};
}, [player, contentId]);
useEffect(() => {
(async () => {
const offline = await getVideoFromIndexedDB(contentId);
if (offline) {
const blob = await decryptBlob(offline.encrypted, offline.iv);
const url = URL.createObjectURL(blob);
setOfflineUrl(url);
}
})();
}, [contentId]);
const isYoutubeUrl = (url: string) => {
const regex = /^https:\/\/www\.youtube\.com\/embed\/[a-zA-Z0-9_-]+/;
return regex.test(url);
};
if (isYoutubeUrl(vidUrl)) return <YoutubeRenderer url={vidUrl} />;
if (appxVideoId && typeof window !== 'undefined' && appxCourseId)
return <AppxVideoPlayer courseId={appxCourseId} videoId={appxVideoId} />;
return (
<div
data-vjs-player
style={{ maxWidth: '1350px', margin: '0 auto', width: '100%' }}
>
<div ref={videoRef} style={{ width: '100%', height: 'auto' }} />
</div>
);
};