forked from simonw/tools
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathvideo-to-gif.html
More file actions
428 lines (362 loc) · 15.3 KB
/
video-to-gif.html
File metadata and controls
428 lines (362 loc) · 15.3 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
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Video to GIF</title>
<link rel="stylesheet" href="styles.css">
<style>
body {
max-width: 960px;
margin: 0 auto;
padding: 24px 20px 56px;
}
header {
margin-bottom: 1.25rem;
}
main {
display: grid;
gap: 1.5rem;
}
.panel {
padding: clamp(1.25rem, 3vw, 2rem);
}
.drop-zone {
border: 2px dashed var(--color-border, #d0d7de);
border-radius: 12px;
padding: 32px 20px;
text-align: center;
cursor: pointer;
transition: border-color 0.2s ease, background-color 0.2s ease;
}
.drop-zone input {
display: none;
}
.drop-zone.dragover {
border-color: var(--color-accent, #0070f3);
background-color: rgba(0, 112, 243, 0.08);
}
.drop-zone p {
margin: 0.35rem 0 0;
color: var(--color-muted, #57606a);
}
.controls-grid {
display: grid;
grid-template-columns: repeat(auto-fit, minmax(220px, 1fr));
gap: 1rem;
}
.form-group {
display: flex;
flex-direction: column;
gap: 0.35rem;
}
.status-text {
min-height: 1.25rem;
color: var(--color-muted, #57606a);
}
.status-text.error {
color: #b42318;
}
.progress-bar {
width: 100%;
background: #f4f6f8;
border-radius: 8px;
height: 10px;
overflow: hidden;
}
.progress-bar span {
display: block;
height: 100%;
width: 0%;
background: linear-gradient(90deg, #0070f3, #5b8def);
transition: width 0.2s ease;
}
.file-info {
display: flex;
flex-wrap: wrap;
gap: 0.5rem 1.5rem;
color: var(--color-muted, #57606a);
}
.preview {
width: 100%;
max-height: 320px;
border-radius: 10px;
background: #0f172a08;
display: grid;
place-items: center;
padding: 1rem;
}
video {
max-width: 100%;
max-height: 300px;
border-radius: 10px;
}
@media (max-width: 640px) {
body {
padding: 18px 16px 48px;
}
}
</style>
</head>
<body>
<header class="page-header">
<a class="site-link" href="https://tools.mathspp.com/" aria-label="Back to tools.mathspp.com">← tools.mathspp.com</a>
<h1>Video to GIF</h1>
<p class="lead">Drop a video and convert it to a GIF directly in your browser. Nothing is uploaded to a server.</p>
</header>
<main>
<section class="surface panel">
<div class="drop-zone" tabindex="0" role="button" aria-label="Upload video" id="drop-zone">
<strong>Drop your video here</strong>
<p>or click to choose a file</p>
<input type="file" accept="video/*" id="video-input" aria-label="Upload video">
</div>
<p class="status-text" id="status-text">No video loaded yet.</p>
<div class="preview" aria-live="polite" id="preview" hidden>
<video controls muted></video>
</div>
</section>
<section class="surface panel" aria-live="polite">
<h2>Conversion</h2>
<div class="file-info" id="file-info" hidden>
<span id="file-name"></span>
<span id="file-size"></span>
<span id="file-duration"></span>
</div>
<div class="controls-grid">
<div class="form-group">
<label for="fps">Frame rate (FPS)</label>
<input type="number" id="fps" min="1" max="30" value="10" inputmode="numeric">
</div>
<div class="form-group">
<label for="max-width">Max width (px)</label>
<input type="number" id="max-width" min="64" max="1280" value="640" inputmode="numeric">
</div>
</div>
<div class="tool-actions" style="margin-top: 1rem;">
<button type="button" id="convert-btn" disabled>Convert to GIF</button>
<button type="button" id="reset-btn">Reset</button>
</div>
<div class="progress-bar" aria-hidden="true" hidden id="progress-bar">
<span id="progress-inner"></span>
</div>
<p class="status-text" id="conversion-status"></p>
<div class="tool-actions">
<button type="button" id="download-btn" disabled>Download GIF</button>
</div>
</section>
</main>
<script type="module">
const ffmpegVersion = '0.12.10';
const ffmpegModuleURL = `https://cdnjs.cloudflare.com/ajax/libs/ffmpeg/${ffmpegVersion}/esm/index.min.js`;
const ffmpegUtilURL = `https://cdnjs.cloudflare.com/ajax/libs/ffmpeg/${ffmpegVersion}/esm/utils.min.js`;
const { FFmpeg } = await import(ffmpegModuleURL);
const { fetchFile, toBlobURL } = await import(ffmpegUtilURL);
(function () {
const dropZone = document.getElementById('drop-zone');
const fileInput = document.getElementById('video-input');
const statusText = document.getElementById('status-text');
const previewWrapper = document.getElementById('preview');
const previewVideo = previewWrapper.querySelector('video');
const convertBtn = document.getElementById('convert-btn');
const resetBtn = document.getElementById('reset-btn');
const downloadBtn = document.getElementById('download-btn');
const fpsInput = document.getElementById('fps');
const maxWidthInput = document.getElementById('max-width');
const fileInfo = document.getElementById('file-info');
const fileNameEl = document.getElementById('file-name');
const fileSizeEl = document.getElementById('file-size');
const fileDurationEl = document.getElementById('file-duration');
const progressBar = document.getElementById('progress-bar');
const progressInner = document.getElementById('progress-inner');
const conversionStatus = document.getElementById('conversion-status');
const ffmpegBaseURL = `https://cdn.jsdelivr.net/npm/@ffmpeg/core@${ffmpegVersion}/dist/umd`;
let loadedFile = null;
let gifBlob = null;
let ffmpeg = null;
let ffmpegReady = false;
let previewUrl = null;
let ffmpegUtils = null;
async function safeUnlink(path) {
if (!ffmpegReady) return;
try {
if (typeof ffmpeg.deleteFile === 'function') {
await ffmpeg.deleteFile(path);
} else if (ffmpeg.FS) {
ffmpeg.FS('unlink', path);
}
} catch (error) {
// Ignore missing files
}
}
function formatBytes(bytes) {
if (bytes === 0) return '0 B';
const k = 1024;
const sizes = ['B', 'KB', 'MB', 'GB'];
const i = Math.floor(Math.log(bytes) / Math.log(k));
return `${(bytes / Math.pow(k, i)).toFixed(1)} ${sizes[i]}`;
}
function setStatus(message, isError = false) {
statusText.textContent = message;
statusText.classList.toggle('error', isError);
}
function setConversionStatus(message, isError = false) {
conversionStatus.textContent = message;
conversionStatus.classList.toggle('error', isError);
}
function toggleDropZoneHighlight(active) {
dropZone.classList.toggle('dragover', active);
}
function reset() {
if (previewUrl) {
URL.revokeObjectURL(previewUrl);
previewUrl = null;
}
loadedFile = null;
gifBlob = null;
fileInput.value = '';
convertBtn.disabled = true;
downloadBtn.disabled = true;
previewWrapper.hidden = true;
previewVideo.removeAttribute('src');
previewVideo.load();
fileInfo.hidden = true;
progressBar.hidden = true;
progressInner.style.width = '0%';
setStatus('No video loaded yet.');
setConversionStatus('');
}
async function ensureFFmpeg() {
if (ffmpegReady) return;
ffmpeg = new FFmpeg();
ffmpegUtils = { fetchFile, toBlobURL };
ffmpeg.on('log', ({ message }) => {
console.log(message);
});
ffmpeg.on('progress', ({ progress, ratio }) => {
const value = Number.isFinite(progress) ? progress : (Number.isFinite(ratio) ? ratio : 0);
updateProgress(value);
});
setConversionStatus('Loading FFmpeg core (~31 MB)…');
await ffmpeg.load({
coreURL: await ffmpegUtils.toBlobURL(`${ffmpegBaseURL}/ffmpeg-core.js`, 'text/javascript'),
wasmURL: await ffmpegUtils.toBlobURL(`${ffmpegBaseURL}/ffmpeg-core.wasm`, 'application/wasm'),
});
ffmpegReady = true;
}
function updateFileInfo(file, durationSeconds) {
fileNameEl.textContent = `Name: ${file.name}`;
fileSizeEl.textContent = `Size: ${formatBytes(file.size)}`;
fileDurationEl.textContent = durationSeconds ? `Duration: ${durationSeconds.toFixed(1)}s` : '';
fileInfo.hidden = false;
}
function updateProgress(ratio) {
const percent = Math.min(100, Math.round(ratio * 100));
progressInner.style.width = `${percent}%`;
progressBar.hidden = false;
setConversionStatus(`Processing… ${percent}%`);
}
function deriveOutputName(inputName) {
const withoutExt = inputName.replace(/\.[^.]+$/, '');
return `${withoutExt}.gif`;
}
async function convertToGif() {
if (!loadedFile) return;
convertBtn.disabled = true;
downloadBtn.disabled = true;
progressInner.style.width = '0%';
progressBar.hidden = false;
setConversionStatus('Preparing conversion…');
try {
await ensureFFmpeg();
const inputName = loadedFile.name;
const outputName = deriveOutputName(inputName);
const data = await ffmpegUtils.fetchFile(loadedFile);
// Clean previous files if any
await safeUnlink(inputName);
await safeUnlink(outputName);
await ffmpeg.writeFile(inputName, data);
const fps = Math.max(1, Math.min(Number(fpsInput.value) || 10, 30));
const maxWidth = Math.max(64, Math.min(Number(maxWidthInput.value) || 640, 1280));
const vf = `fps=${fps},scale=${maxWidth}:-1:flags=lanczos`;
await ffmpeg.exec(['-i', inputName, '-vf', vf, '-loop', '0', outputName]);
const outputData = await ffmpeg.readFile(outputName);
gifBlob = new Blob([outputData.buffer], { type: 'image/gif' });
const downloadName = outputName;
downloadBtn.dataset.filename = downloadName;
setConversionStatus('GIF ready!');
downloadBtn.disabled = false;
await safeUnlink(inputName);
await safeUnlink(outputName);
} catch (error) {
console.error(error);
setConversionStatus(error.message || 'Conversion failed.', true);
} finally {
convertBtn.disabled = !loadedFile;
progressBar.hidden = false;
}
}
function handleDownload() {
if (!gifBlob) return;
const url = URL.createObjectURL(gifBlob);
const a = document.createElement('a');
a.href = url;
a.download = downloadBtn.dataset.filename || 'output.gif';
document.body.appendChild(a);
a.click();
a.remove();
setTimeout(() => URL.revokeObjectURL(url), 0);
}
function handleFiles(files) {
const file = files[0];
if (!file) return;
if (previewUrl) {
URL.revokeObjectURL(previewUrl);
}
previewUrl = URL.createObjectURL(file);
previewVideo.src = previewUrl;
previewVideo.load();
previewWrapper.hidden = false;
setStatus('Video ready. Click convert to create a GIF.');
loadedFile = file;
gifBlob = null;
convertBtn.disabled = false;
downloadBtn.disabled = true;
setConversionStatus('');
progressBar.hidden = true;
progressInner.style.width = '0%';
previewVideo.onloadedmetadata = () => {
updateFileInfo(file, previewVideo.duration);
};
}
dropZone.addEventListener('click', () => fileInput.click());
dropZone.addEventListener('keydown', (event) => {
if (event.key === 'Enter' || event.key === ' ') {
event.preventDefault();
fileInput.click();
}
});
dropZone.addEventListener('dragover', (event) => {
event.preventDefault();
toggleDropZoneHighlight(true);
});
dropZone.addEventListener('dragleave', () => toggleDropZoneHighlight(false));
dropZone.addEventListener('drop', (event) => {
event.preventDefault();
toggleDropZoneHighlight(false);
handleFiles(event.dataTransfer.files);
});
fileInput.addEventListener('change', (event) => {
handleFiles(event.target.files);
});
convertBtn.addEventListener('click', convertToGif);
downloadBtn.addEventListener('click', handleDownload);
resetBtn.addEventListener('click', reset);
reset();
})();
</script>
<footer class="page-footer">
<p>Built with ❤️, 🤖, and 🐍, by <a href="https://mathspp.com/">Rodrigo Girão Serrão</a></p>
</footer>
</body>
</html>