@cntrl-site/sdk-nextjs 0.24.2 → 0.26.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,211 @@
1
+ import UAParser from 'ua-parser-js';
2
+ import videoDecoder from './VideoDecoder';
3
+
4
+ interface ScrollVideoOptions {
5
+ src: string;
6
+ videoContainer: HTMLElement | string;
7
+ }
8
+
9
+ export class ScrollPlaybackVideoManager {
10
+ private container?: HTMLElement;
11
+ private video?: HTMLVideoElement;
12
+ private isSafari?: boolean;
13
+ private currentTime = 0;
14
+ private targetTime = 0;
15
+ private canvas: HTMLCanvasElement | null = null;
16
+ private context: CanvasRenderingContext2D | null = null;
17
+ private frames: ImageBitmap[] = [];
18
+ private frameRate = 0;
19
+ private transitioning = false;
20
+ private debug: boolean = false;
21
+ private frameThreshold: number = 0;
22
+ private transitionSpeed: number = 10;
23
+ private useWebCodecs: boolean = true;
24
+ private resizeObserver: ResizeObserver;
25
+
26
+ constructor(options: ScrollVideoOptions) {
27
+ this.resizeObserver = new ResizeObserver(() => {
28
+ this.resize();
29
+ });
30
+ const {
31
+ src,
32
+ videoContainer
33
+ } = options;
34
+ if (typeof document !== 'object') {
35
+ console.error('ScrollVideo must be initiated in a DOM context');
36
+ return;
37
+ }
38
+ if (!videoContainer) {
39
+ console.error('scrollVideoContainer must be a valid DOM object');
40
+ return;
41
+ }
42
+ if (!src) {
43
+ console.error('Must provide valid video src to ScrollVideo');
44
+ return;
45
+ }
46
+
47
+ this.container = typeof videoContainer === 'string' ? document.getElementById(videoContainer)! : videoContainer;
48
+ this.resizeObserver.observe(this.container);
49
+ this.video = document.createElement('video');
50
+ this.video.src = src;
51
+ this.video.preload = 'auto';
52
+ this.video.tabIndex = 0;
53
+ this.video.playsInline = true;
54
+ this.video.muted = true;
55
+ this.video.pause();
56
+ this.video.load();
57
+ this.container.appendChild(this.video);
58
+ const browserEngine = new UAParser().getEngine();
59
+ this.isSafari = browserEngine.name === 'WebKit';
60
+ if (this.debug && this.isSafari) console.info('Safari browser detected');
61
+ this.video.addEventListener('loadedmetadata', () => this.setTargetTimePercent(0, true), { once: true });
62
+ this.video.addEventListener('progress', this.resize);
63
+ this.decodeVideo();
64
+ }
65
+
66
+ private setCoverStyle(el: any) {
67
+ if (el && this.container) {
68
+ el.style.position = 'absolute';
69
+ el.style.top = '50%';
70
+ el.style.left = '50%';
71
+ el.style.transform = 'translate(-50%, -50%)';
72
+ const { width: containerWidth, height: containerHeight } = this.container.getBoundingClientRect();
73
+ const width = el.videoWidth || el.width;
74
+ const height = el.videoHeight || el.height;
75
+ if (containerWidth / containerHeight > width / height) {
76
+ el.style.width = '100%';
77
+ el.style.height = 'auto';
78
+ } else {
79
+ el.style.height = '100%';
80
+ el.style.width = 'auto';
81
+ }
82
+ }
83
+ }
84
+
85
+ private resize = () => {
86
+ if (this.debug) console.info('ScrollVideo resizing...');
87
+ if (this.canvas) {
88
+ this.setCoverStyle(this.canvas);
89
+ } else if (this.video) {
90
+ this.setCoverStyle(this.video);
91
+ }
92
+ this.paintCanvasFrame(Math.floor(this.currentTime * this.frameRate));
93
+ };
94
+
95
+ private decodeVideo = () => {
96
+ if (!this.video) return;
97
+ if (this.useWebCodecs && this.video.src) {
98
+ videoDecoder(this.video.src, (frame: ImageBitmap) => {
99
+ this.frames.push(frame);
100
+ },
101
+ this.debug,
102
+ ).then(() => {
103
+ if (!this.video || !this.container) return
104
+ if (this.frames.length === 0) {
105
+ if (this.debug) console.error('No frames were received from webCodecs');
106
+ return;
107
+ }
108
+ this.frameRate = this.frames.length / this.video.duration;
109
+ if (this.debug) console.info('Received', this.frames.length, 'frames');
110
+ this.canvas = document.createElement('canvas');
111
+ this.context = this.canvas.getContext('2d')!;
112
+ this.video.style.display = 'none';
113
+ this.container.appendChild(this.canvas);
114
+ this.paintCanvasFrame(Math.floor(this.currentTime * this.frameRate));
115
+ }).catch(() => {
116
+ if (this.debug) console.error('Error encountered while decoding video');
117
+ this.frames = [];
118
+ this.video!.load();
119
+ });
120
+ }
121
+ }
122
+
123
+ private paintCanvasFrame(frameNum: number) {
124
+ if (this.canvas) {
125
+ const frameIdx = Math.min(frameNum, this.frames.length - 1);
126
+ const currFrame = this.frames[frameIdx];
127
+ if (currFrame && this.container) {
128
+ if (this.debug) console.info('Painting frame', frameIdx);
129
+ this.canvas.width = currFrame.width;
130
+ this.canvas.height = currFrame.height;
131
+ const { width, height } = this.container.getBoundingClientRect();
132
+ this.resetCanvasDimensions(width, height, currFrame.width, currFrame.height);
133
+ this.context!.drawImage(currFrame, 0, 0, currFrame.width, currFrame.height);
134
+ }
135
+ }
136
+ }
137
+
138
+ private transitionToTargetTime(jump: boolean) {
139
+ if (!this.video) return;
140
+ if (this.debug) console.info('Transitioning targetTime:', this.targetTime, 'currentTime:', this.currentTime);
141
+ if (isNaN(this.targetTime) || Math.abs(this.currentTime - this.targetTime) < this.frameThreshold) {
142
+ this.video.pause();
143
+ this.transitioning = false;
144
+ return;
145
+ }
146
+ // Make sure we don't go out of time bounds
147
+ if (this.targetTime > this.video.duration) {
148
+ this.targetTime = this.video.duration;
149
+ }
150
+ if (this.targetTime < 0) {
151
+ this.targetTime = 0;
152
+ }
153
+ // How far forward we need to transition
154
+ const transitionForward = this.targetTime - this.currentTime;
155
+ if (this.canvas) {
156
+ // Update currentTime and paint the closest frame
157
+ this.currentTime += transitionForward / (256 / this.transitionSpeed);
158
+ // If jump, we go directly to the frame
159
+ if (jump) { this.currentTime = this.targetTime }
160
+ this.paintCanvasFrame(Math.floor(this.currentTime * this.frameRate));
161
+ } else if (jump || this.isSafari || this.targetTime - this.currentTime < 0) {
162
+ this.video.pause();
163
+ this.currentTime += transitionForward / (64 / this.transitionSpeed);
164
+ // If jump, we go directly to the frame
165
+ if (jump) { this.currentTime = this.targetTime;}
166
+ this.video.currentTime = this.currentTime;
167
+ } else {
168
+ // Otherwise, we play the video and adjust the playbackRate to get a smoother
169
+ // animation effect.
170
+ const playbackRate = Math.max(Math.min(transitionForward * 4, this.transitionSpeed, 16), 1);
171
+ if (this.debug) console.info('ScrollVideo playbackRate:', playbackRate);
172
+ if (!isNaN(playbackRate)) {
173
+ this.video.playbackRate = playbackRate;
174
+ this.video.play();
175
+ }
176
+ this.currentTime = this.video.currentTime;
177
+ }
178
+ if (typeof requestAnimationFrame === 'function') {
179
+ requestAnimationFrame(() => this.transitionToTargetTime(jump));
180
+ }
181
+ }
182
+
183
+ private resetCanvasDimensions(w: number, h: number, frameW: number, frameH: number) {
184
+ if (!this.canvas) return;
185
+ if (w / h > frameW / frameH) {
186
+ this.canvas.style.width = '100%';
187
+ this.canvas.style.height = 'auto';
188
+ } else {
189
+ this.canvas.style.height = '100%';
190
+ this.canvas.style.width = 'auto';
191
+ }
192
+ }
193
+
194
+ setTargetTimePercent(setPercentage: number, jump: boolean = true): void {
195
+ if (!this.video) return;
196
+ this.targetTime = Math.max(Math.min(setPercentage, 1), 0)
197
+ * (this.frames.length && this.frameRate ? this.frames.length / this.frameRate : this.video.duration);
198
+ if (!jump && Math.abs(this.currentTime - this.targetTime) < this.frameThreshold) return;
199
+ if (!jump && this.transitioning) return;
200
+ if (!this.canvas && !this.video.paused) this.video.play();
201
+ this.transitioning = true;
202
+ this.transitionToTargetTime(jump);
203
+ }
204
+
205
+ destroy(): void {
206
+ this.resizeObserver.unobserve(this.container!);
207
+ this.video?.removeEventListener('progress', this.resize);
208
+ if (this.debug) console.info('Destroying ScrollVideo');
209
+ if (this.container) this.container.innerHTML = '';
210
+ }
211
+ }
@@ -0,0 +1,174 @@
1
+ // @ts-ignore
2
+ import * as MP4Box from 'mp4box';
3
+
4
+ export class Writer {
5
+ private data: Uint8Array;
6
+ private idx: number;
7
+ private size: number;
8
+
9
+ constructor(size: number) {
10
+ this.data = new Uint8Array(size);
11
+ this.idx = 0;
12
+ this.size = size;
13
+ }
14
+
15
+ getData() {
16
+ if (this.idx !== this.size) throw new Error('Mismatch between size reserved and sized used');
17
+ return this.data.slice(0, this.idx);
18
+ }
19
+
20
+ writeUint8(value: number) {
21
+ this.data.set([value], this.idx);
22
+ this.idx += 1;
23
+ }
24
+
25
+ writeUint16(value: number) {
26
+ const arr = new Uint16Array(1);
27
+ arr[0] = value;
28
+ const buffer = new Uint8Array(arr.buffer);
29
+ this.data.set([buffer[1], buffer[0]], this.idx);
30
+ this.idx += 2;
31
+ }
32
+
33
+ writeUint8Array(value: Uint8Array) {
34
+ this.data.set(value, this.idx);
35
+ this.idx += value.length;
36
+ }
37
+ }
38
+
39
+ interface AVCCBox {
40
+ configurationVersion: number;
41
+ AVCProfileIndication: number;
42
+ profile_compatibility: number;
43
+ AVCLevelIndication: number;
44
+ lengthSizeMinusOne: number;
45
+ nb_SPS_nalus: number;
46
+ SPS: { length: number; nalu: Uint8Array }[];
47
+ nb_PPS_nalus: number;
48
+ PPS: { length: number; nalu: Uint8Array }[];
49
+ }
50
+
51
+ const getExtradata = (avccBox: AVCCBox) => {
52
+ let i;
53
+ let size = 7;
54
+ for (i = 0; i < avccBox.SPS.length; i += 1) {
55
+ // nalu length is encoded as a uint16.
56
+ size += 2 + avccBox.SPS[i].length;
57
+ }
58
+ for (i = 0; i < avccBox.PPS.length; i += 1) {
59
+ // nalu length is encoded as a uint16.
60
+ size += 2 + avccBox.PPS[i].length;
61
+ }
62
+ const writer = new Writer(size);
63
+ writer.writeUint8(avccBox.configurationVersion);
64
+ writer.writeUint8(avccBox.AVCProfileIndication);
65
+ writer.writeUint8(avccBox.profile_compatibility);
66
+ writer.writeUint8(avccBox.AVCLevelIndication);
67
+ writer.writeUint8(avccBox.lengthSizeMinusOne + (63 << 2));
68
+ writer.writeUint8(avccBox.nb_SPS_nalus + (7 << 5));
69
+ for (i = 0; i < avccBox.SPS.length; i += 1) {
70
+ writer.writeUint16(avccBox.SPS[i].length);
71
+ writer.writeUint8Array(avccBox.SPS[i].nalu);
72
+ }
73
+ writer.writeUint8(avccBox.nb_PPS_nalus);
74
+ for (i = 0; i < avccBox.PPS.length; i += 1) {
75
+ writer.writeUint16(avccBox.PPS[i].length);
76
+ writer.writeUint8Array(avccBox.PPS[i].nalu);
77
+ }
78
+ return writer.getData();
79
+ };
80
+
81
+ const decodeVideo = (
82
+ src: string,
83
+ emitFrame: (bitmap: ImageBitmap) => void,
84
+ { VideoDecoder, EncodedVideoChunk, debug }: any
85
+ ): Promise<void> =>
86
+ new Promise((resolve, reject) => {
87
+ if (debug) console.info('Decoding video from', src);
88
+ try {
89
+ const mp4boxfile = MP4Box.createFile();
90
+ let codec;
91
+ const decoder = new VideoDecoder({
92
+ output: (frame: VideoFrame) => {
93
+ console.log(frame);
94
+ createImageBitmap(frame, { resizeQuality: 'low' }).then((bitmap) => {
95
+ emitFrame(bitmap);
96
+ frame.close();
97
+ if (decoder.decodeQueueSize <= 0) {
98
+ setTimeout(() => {
99
+ if (decoder.state !== 'closed') {
100
+ decoder.close();
101
+ resolve();
102
+ }
103
+ }, 500);
104
+ }
105
+ });
106
+ },
107
+ error: (e: any) => {
108
+ console.error(e);
109
+ reject(e);
110
+ },
111
+ });
112
+
113
+ mp4boxfile.onReady = (info: any) => {
114
+ if (info && info.videoTracks && info.videoTracks[0]) {
115
+ [{ codec }] = info.videoTracks;
116
+ if (debug) console.info('Video with codec:', codec);
117
+ const avccBox = mp4boxfile.moov.traks[0].mdia.minf.stbl.stsd.entries[0].avcC;
118
+ const extradata = getExtradata(avccBox);
119
+ decoder.configure({ codec, description: extradata });
120
+ mp4boxfile.setExtractionOptions(info.videoTracks[0].id);
121
+ mp4boxfile.start();
122
+ } else reject(new Error('URL provided is not a valid mp4 video file.'));
123
+ };
124
+
125
+ mp4boxfile.onSamples = (track_id: number, ref: any, samples: any[]) => {
126
+ for (let i = 0; i < samples.length; i += 1) {
127
+ const sample = samples[i];
128
+ const type = sample.is_sync ? 'key' : 'delta';
129
+ const chunk = new EncodedVideoChunk({
130
+ type,
131
+ timestamp: sample.cts,
132
+ duration: sample.duration,
133
+ data: sample.data,
134
+ });
135
+ decoder.decode(chunk);
136
+ }
137
+ };
138
+
139
+ fetch(src).then((res) => {
140
+ const reader = res.body!.getReader();
141
+ let offset = 0;
142
+ //@ts-ignore
143
+ function appendBuffers({ done, value }: any) {
144
+ if (done) {
145
+ mp4boxfile.flush();
146
+ return null;
147
+ }
148
+ const buf = value.buffer;
149
+ buf.fileStart = offset;
150
+ offset += buf.byteLength;
151
+ mp4boxfile.appendBuffer(buf);
152
+ return reader.read().then(appendBuffers);
153
+ }
154
+ return reader.read().then(appendBuffers);
155
+ });
156
+ } catch (e) {
157
+ reject(e);
158
+ }
159
+ });
160
+
161
+
162
+ export default ( src: string, emitFrame: (bitmap: ImageBitmap) => void, debug: boolean): Promise<void> => {
163
+ if (typeof VideoDecoder === 'function' && typeof EncodedVideoChunk === 'function') {
164
+ if (debug)
165
+ console.info('WebCodecs is natively supported, using native version...');
166
+ return decodeVideo(src, emitFrame, {
167
+ VideoDecoder,
168
+ EncodedVideoChunk,
169
+ debug,
170
+ });
171
+ }
172
+ if (debug) console.info('WebCodecs is not available in this browser.');
173
+ return Promise.resolve();
174
+ };
@@ -1,15 +0,0 @@
1
- <component name="InspectionProjectProfileManager">
2
- <profile version="1.0">
3
- <option name="myName" value="Project Default" />
4
- <inspection_tool class="HtmlUnknownAttribute" enabled="true" level="WARNING" enabled_by_default="true">
5
- <option name="myValues">
6
- <value>
7
- <list size="1">
8
- <item index="0" class="java.lang.String" itemvalue="jsx" />
9
- </list>
10
- </value>
11
- </option>
12
- <option name="myCustomValuesEnabled" value="true" />
13
- </inspection_tool>
14
- </profile>
15
- </component>