-
-
Notifications
You must be signed in to change notification settings - Fork 95
/
gif.html
430 lines (391 loc) · 16.3 KB
/
gif.html
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
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>OBS Overlay - Social Stream Ninja</title>
<link rel="icon" href="./icons/favicon.ico" />
<link rel="preload" href="./thirdparty/NotoColorEmoji.ttf" as="font" type="font/ttf" crossorigin="anonymous">
<style>
@import url('https://fonts.googleapis.com/css2?family=Montserrat:wght@400;600;700&display=swap');
body {
font-family: 'Montserrat', Arial, sans-serif;
background-color: transparent;
display: flex;
justify-content: center;
align-items: center;
height: 100vh;
margin: 0;
overflow: hidden;
}
#mediaContainer {
position: fixed;
top: 0;
left: 0;
width: 100%;
height: 100%;
display: flex;
justify-content: center;
align-items: center;
opacity: 0;
transition: opacity 0.5s ease-in-out;
}
#mediaContent {
max-width: 100%;
max-height: 100%;
object-fit: contain;
}
img,svg,video{
max-height:100vh;
max-width:100vw;
}
</style>
</head>
<body>
<div id="mediaContainer">
<img id="mediaContent" src="" alt="Media Content">
</div>
<script>
const urlParams = new URLSearchParams(window.location.search);
const mediaContainer = document.getElementById('mediaContainer');
const mediaContent = document.getElementById('mediaContent');
let mediaQueue = [];
let isPlaying = false;
const fadeoutTime = 300
const minDisplayTime = parseInt(urlParams.get('showtime')) || (fadeoutTime+1);
function processData(data) {
//console.log(data);
if (data.content) {
data = data.content;
}
// the URL should be a direct image/video/audio/svg, but it might also be a link to tenor/giphy.
// Here, we want to show contentimg as an near full window or full window
// we want to make sure its preloaded before display it, to ensure a smooth fade in and out, and that it is valid
// we want to mute it, and play it, if the audio context is suspended and can't be resumed/enabled due to lack of user gesture input.
// if we're using window.obsstudio, then gestures aren't needed to play audio, but we need to make sure thats the casse.
// if a user has urlParams.has('muted') enabled, then we should mute any video by default
// we can look at the file type to tell if its a webm, gif, jpeg, svg, webp, audio, or mp4; and treat it accordingly; video/img/svg tag, audio-muted, etc.
// if it can't play, lets put an error in the console log saying say; CORS issue?
// additional data that will be available, that we dont need to use now, but is available, is:
// data.chatimg - avatar of user
// data.chatname - name of user
// data.chatmessage - a text message from user
// data.type - what site, like twitch or facebook, that the message came from
// data.donation - an possible donation value if there was a donation attached.
// data.contentimg = "https://picsum.photos/1280/720?random=" + Math.random();
if (data.contentimg) {
mediaQueue.push(data.contentimg);
if (!isPlaying) {
playNextMedia();
}
}
}
function playNextMedia() {
if (mediaQueue.length === 0) {
isPlaying = false;
return;
}
isPlaying = true;
let mediaUrl = mediaQueue.shift();
const youtubeVideoId = getYouTubeVideoId(mediaUrl);
if (youtubeVideoId) {
mediaUrl = createYouTubeEmbed(youtubeVideoId);
}
if (isEmbeddedContent(mediaUrl)) {
displayEmbeddedContent(mediaUrl);
} else {
const fileExtension = mediaUrl.split('.').pop().toLowerCase();
if (['jpg', 'jpeg', 'png', 'gif', 'webp'].includes(fileExtension)) {
displayImage(mediaUrl);
} else if (['mp4', 'webm'].includes(fileExtension)) {
displayVideo(mediaUrl);
} else if (['mp3', 'wav', 'ogg'].includes(fileExtension)) {
playAudio(mediaUrl);
} else if (fileExtension === 'svg') {
displaySVG(mediaUrl);
} else if (fileExtension === 'html' || mediaUrl.split('/').pop().split('.').length == 1) {
displayEmbeddedContent(mediaUrl);
} else if (mediaUrl.split('/').pop().split('.').pop().length > 4) {
displayImage(mediaUrl);
} else {
console.error('Unsupported file type:', fileExtension);
playNextMedia();
}
}
}
function isEmbeddedContent(content) {
return content.includes('<iframe') || content.includes('<embed');
}
function getYouTubeVideoId(url) {
const regExp = /^.*(youtu.be\/|v\/|u\/\w\/|embed\/|watch\?v=|\&v=)([^#\&\?]*).*/;
const match = url.match(regExp);
return (match && match[2].length === 11) ? match[2] : null;
}
function createYouTubeEmbed(videoId) {
return `<iframe src="https://www.youtube.com/embed/${videoId}?autoplay=1" frameborder="0" allow="autoplay; encrypted-media" allowfullscreen></iframe>`;
}
function displayEmbeddedContent(content) {
let embedElement;
if (content.startsWith('http') || content.endsWith('.html')) {
embedElement = document.createElement('iframe');
embedElement.src = content;
} else {
const tempDiv = document.createElement('div');
tempDiv.innerHTML = content;
embedElement = tempDiv.querySelector('iframe, embed');
if (!embedElement) {
console.error('Invalid embedded content');
playNextMedia();
return;
}
}
let src = embedElement.src;
for (let i = embedElement.attributes.length - 1; i >= 0; i--) {
embedElement.removeAttribute(embedElement.attributes[i].name);
}
if (src.includes('youtube.com') || src.includes('youtu.be')) {
const urlObj = new URL(src);
urlObj.searchParams.set('autoplay', '1');
src = urlObj.toString();
}
embedElement.src = src;
embedElement.style.width = '100%';
embedElement.style.height = '100%';
embedElement.style.border = 'none';
embedElement.setAttribute("allow","autoplay");
embedElement.replaceWith(embedElement.cloneNode(true));
mediaContainer.innerHTML = '';
mediaContainer.appendChild(embedElement);
fadeIn();
setTimeout(() => {
fadeOut(() => {
mediaContainer.innerHTML = '';
mediaContainer.appendChild(mediaContent);
playNextMedia();
});
}, minDisplayTime);
}
function displayImage(url) {
const img = new Image();
img.onload = () => {
mediaContent.src = url;
fadeIn();
if (url.toLowerCase().endsWith('.gif')) {
const gifDuration = getGifDuration(img);
const displayTime = Math.max(gifDuration, minDisplayTime);
setTimeout(() => {
fadeOut(() => playNextMedia());
}, displayTime);
} else {
setTimeout(() => {
fadeOut(() => playNextMedia());
}, minDisplayTime);
}
};
img.onerror = () => {
console.error('Failed to load image:', url);
playNextMedia();
};
img.src = url;
}
function displayVideo(url) {
const video = document.createElement('video');
video.src = url;
video.muted = urlParams.has('muted');
video.oncanplay = () => {
mediaContent.replaceWith(video);
fadeIn();
video.play();
const videoDuration = video.duration * 1000;
const displayTime = Math.max(videoDuration, minDisplayTime);
setTimeout(() => {
if (videoDuration < minDisplayTime) {
video.loop = true;
setTimeout(() => {
video.loop = false;
video.onended = () => {
fadeOut(() => {
video.replaceWith(mediaContent);
playNextMedia();
});
};
}, minDisplayTime - videoDuration);
} else {
video.onended = () => {
fadeOut(() => {
video.replaceWith(mediaContent);
playNextMedia();
});
};
}
}, 0);
};
video.onerror = () => {
console.error('Failed to load video:', url);
playNextMedia();
};
}
function playAudio(url) {
const audio = new Audio(url);
audio.muted = urlParams.has('muted');
audio.oncanplay = () => {
fadeIn();
audio.play();
};
audio.onended = () => {
fadeOut(() => playNextMedia());
};
audio.onerror = () => {
console.error('Failed to load audio:', url);
playNextMedia();
};
}
function displaySVG(url) {
fetch(url)
.then(response => response.text())
.then(svgContent => {
mediaContainer.innerHTML = svgContent;
fadeIn();
setTimeout(() => {
fadeOut(() => {
mediaContainer.innerHTML = '';
mediaContainer.appendChild(mediaContent);
playNextMedia();
});
}, 5000);
})
.catch(error => {
console.error('Failed to load SVG:', url, error);
playNextMedia();
});
}
function fadeIn() {
mediaContainer.style.opacity = '1';
}
function fadeOut(callback) {
mediaContainer.style.opacity = '0';
setTimeout(callback, fadeoutTime); // 200
}
const iframe = document.createElement("iframe");
const filename = new URL(window.location.href).pathname.split('/').pop().split('.')[0] || "dock";
iframe.src = "https://vdo.socialstream.ninja/?ln&salt=vdo.ninja¬mobile¬mobile&password=false&solo&view=" + urlParams.get('session') + "&novideo&noaudio&label="+filename+"&cleanoutput&room=" + urlParams.get('session');
iframe.style.width = "0px";
iframe.style.height = "0px";
iframe.style.position = "fixed";
iframe.style.left = "-100px";
iframe.style.top = "-100px";
iframe.id = "frame1";
document.body.appendChild(iframe);
const eventMethod = window.addEventListener ? "addEventListener" : "attachEvent";
const eventer = window[eventMethod];
const messageEvent = eventMethod === "attachEvent" ? "onmessage" : "message";
eventer(messageEvent, function (e) {
if (e.source != iframe.contentWindow) return;
if ("dataReceived" in e.data) {
if ("overlayNinja" in e.data.dataReceived) {
processData(e.data.dataReceived.overlayNinja);
}
}
});
// Handle audio context for browsers that require user interaction
document.addEventListener('click', () => {
if (window.AudioContext || window.webkitAudioContext) {
const AudioContext = window.AudioContext || window.webkitAudioContext;
const audioContext = new AudioContext();
if (audioContext.state === 'suspended') {
audioContext.resume();
}
}
});
function getUint24(view, pos) {
return (view.getUint8(pos) | (view.getUint8(pos + 1) << 8) | (view.getUint8(pos + 2) << 16));
}
function getWebPDuration(arr) {
const view = new DataView(arr.buffer);
let pos = 12; // Skip RIFF header
let duration = 0;
let frames = 0;
let loopCount = 0;
while (pos < arr.length) {
const chunkId = String.fromCharCode(arr[pos], arr[pos+1], arr[pos+2], arr[pos+3]);
const chunkSize = view.getUint32(pos + 4, true);
if (chunkId === 'VP8X') {
const flags = view.getUint32(pos + 8, true);
if (!(flags & 2)) {
console.warn('Not an animated WebP');
return minDisplayTime;
}
} else if (chunkId === 'ANIM') {
loopCount = view.getUint16(pos + 12, true);
// console.log('Loop count:', loopCount === 0 ? 'infinite' : loopCount);
} else if (chunkId === 'ANMF') {
frames++;
const frameDuration = getUint24(view, pos + 20);
duration += frameDuration;
// console.log(`Frame ${frames}: duration: ${frameDuration}ms`);
}
pos += 8 + chunkSize;
if (chunkSize % 2 !== 0) pos++; // Padding byte
}
if (duration) {
duration = Math.max(fadeoutTime,Math.max(Math.ceil(minDisplayTime/duration)*duration)-fadeoutTime/1.5);
duration = Math.min((minDisplayTime+fadeoutTime)*5,duration); // won't be 5x longer then the min time; 10s?
} else {
duration = minDisplayTime;
}
return duration;
}
function analyzeAnimatedImage(blob, callback) {
const reader = new FileReader();
reader.onload = function(e) {
const arr = new Uint8Array(e.target.result);
if (blob.type === 'image/webp') {
try{
const duration = getWebPDuration(arr);
callback(duration);
} catch(e){
callback(minDisplayTime);
}
} else {
console.warn('Unsupported animated image format');
callback(minDisplayTime);
}
};
reader.readAsArrayBuffer(blob);
}
function displayImage(url) {
fetch(url)
.then(response => response.blob())
.then(blob => {
const objectURL = URL.createObjectURL(blob);
mediaContent.onload = () => {
fadeIn();
if (url.toLowerCase().endsWith('.webp')) {
analyzeAnimatedImage(blob, (duration) => {
const displayTime = Math.max(duration, minDisplayTime);
setTimeout(() => {
fadeOut(() => {
URL.revokeObjectURL(objectURL);
playNextMedia();
});
}, displayTime);
});
} else {
setTimeout(() => {
fadeOut(() => {
URL.revokeObjectURL(objectURL);
playNextMedia();
});
}, minDisplayTime);
}
};
mediaContent.src = objectURL;
})
.catch(error => {
console.error('Failed to load image:', url, error);
playNextMedia();
});
}
</script>
</body>
</html>