-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathscript.js
More file actions
650 lines (538 loc) · 21.7 KB
/
Copy pathscript.js
File metadata and controls
650 lines (538 loc) · 21.7 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
let mediaInfoInstance = null;
let currentFileData = null;
// ===== 新增:读取网址参数 =====
const urlParams = new URLSearchParams(window.location.search);
const fileParam = urlParams.get('file');
// 初始化 MediaInfo
async function initMediaInfo() {
try {
// 优先使用 UMD 的 MediaInfo 对象;兼容不同的导出形式
const MediaInfoFactory =
(typeof MediaInfo !== 'undefined' && (MediaInfo.default || MediaInfo)) || null;
if (!MediaInfoFactory) throw new Error('MediaInfo 库未加载');
mediaInfoInstance = await MediaInfoFactory({
locateFile: (path) => 'https://unpkg.com/mediainfo.js/dist/' + path
});
console.log('MediaInfo 初始化完成');
} catch (error) {
console.error('MediaInfo 初始化失败:', error);
alert('分析库加载失败,请检查网络后刷新。');
}
}
// 页面加载
window.addEventListener('load', () => {
initMediaInfo().then(() => {
initEventListeners();
// 如果网址里带了 file 参数,自动分析
if (fileParam) {
document.getElementById('uploadSection').style.display = 'none';
showLoading();
updateProgress(0, '正在从网址读取文件...');
analyzeUrl(fileParam);
}
});
});
// 事件监听
function initEventListeners() {
const uploadArea = document.getElementById('uploadArea');
const fileInput = document.getElementById('fileInput');
uploadArea.addEventListener('dragover', (e) => {
e.preventDefault();
uploadArea.classList.add('drag-over');
});
uploadArea.addEventListener('dragleave', () => {
uploadArea.classList.remove('drag-over');
});
uploadArea.addEventListener('drop', (e) => {
e.preventDefault();
uploadArea.classList.remove('drag-over');
const files = e.dataTransfer.files;
if (files.length > 0) handleFile(files[0]);
});
fileInput.addEventListener('change', (e) => {
if (e.target.files.length > 0) handleFile(e.target.files[0]);
});
}
// ===== 新增:从网址分析文件 =====
async function analyzeUrl(url) {
if (!mediaInfoInstance) {
// 还没初始化完,稍后重试
setTimeout(() => analyzeUrl(url), 500);
return;
}
try {
updateProgress(5, '正在获取文件信息...');
// 先用 HEAD 拿文件大小
let fileSize = 0;
try {
const headResp = await fetch(url, { method: 'HEAD' });
if (!headResp.ok) throw new Error('HTTP ' + headResp.status);
fileSize = parseInt(headResp.headers.get('content-length') || '0', 10);
} catch (e) {
throw new Error('无法访问文件(可能是跨域 CORS 限制):' + e.message);
}
if (!fileSize) throw new Error('无法获取文件大小,服务器未返回 Content-Length。');
updateProgress(10, `文件大小:${formatFileSize(fileSize)},开始分析...`);
const getSize = () => fileSize;
const readChunk = async (size, offset) => {
const end = Math.min(offset + size, fileSize) - 1;
const resp = await fetch(url, {
headers: { 'Range': `bytes=${offset}-${end}` }
});
if (!resp.ok && resp.status !== 206) {
throw new Error('分段读取失败:HTTP ' + resp.status);
}
const buf = await resp.arrayBuffer();
return new Uint8Array(buf);
};
const result = await mediaInfoInstance.analyzeData(getSize, readChunk);
updateProgress(100, '分析完成');
// 构造一个类似 File 的对象,供 displayResults 使用
const nameFromUrl = decodeURIComponent(
(url.split('/').pop() || 'video').split('?')[0]
);
const fakeFile = {
name: nameFromUrl,
size: fileSize,
type: ''
};
setTimeout(() => displayResults(fakeFile, result), 300);
} catch (error) {
console.error('分析网址失败:', error);
document.getElementById('loadingSection').innerHTML =
'<p style="color:#c00;line-height:1.8;">' +
'❌ 分析失败:' + error.message +
'<br><br>最常见原因:<b>跨域(CORS)限制</b>。<br>' +
'浏览器不允许本页读取另一个域名的视频文件。<br>' +
'请确认 OpenList(或其反向代理)返回了 ' +
'<code>Access-Control-Allow-Origin</code> 头。' +
'</p>';
}
}
// 处理本地拖入的文件
async function handleFile(file) {
if (!mediaInfoInstance) {
alert('分析库还没加载完,请稍后再试。');
return;
}
const maxSize = 24 * 1024 * 1024 * 1024; // 24GB
if (file.size > maxSize) {
alert('文件太大,最大支持 24GB。');
return;
}
currentFileData = file;
showLoading();
updateProgress(0, '准备分析...');
try {
const isLargeFile = file.size > 100 * 1024 * 1024;
let result;
if (isLargeFile) {
result = await analyzeFileInChunks(file);
} else {
updateProgress(50, '读取文件...');
const arrayBuffer = await file.arrayBuffer();
const uint8Array = new Uint8Array(arrayBuffer);
updateProgress(80, '分析中...');
result = await mediaInfoInstance.analyzeData(
() => uint8Array.length,
(size, offset) => uint8Array.slice(offset, offset + size)
);
}
updateProgress(100, '分析完成');
setTimeout(() => displayResults(file, result), 300);
} catch (error) {
console.error('分析本地文件失败:', error);
alert('分析失败:' + error.message);
hideLoading();
}
}
// 大文件分段分析
async function analyzeFileInChunks(file) {
let chunkSize;
if (file.size > 1024 * 1024 * 1024) chunkSize = 1024 * 1024;
else if (file.size > 500 * 1024 * 1024) chunkSize = 512 * 1024;
else chunkSize = 64 * 1024;
const fileSize = file.size;
updateProgress(10, '分析大文件...');
const getSize = () => fileSize;
const readChunk = async (size, fileOffset) => {
const progress = Math.min(10 + (fileOffset / fileSize) * 70, 80);
updateProgress(progress, `处理中:${formatFileSize(fileOffset)} / ${formatFileSize(fileSize)}`);
const start = fileOffset;
const end = Math.min(start + size, fileSize);
const chunk = file.slice(start, end);
const arrayBuffer = await chunk.arrayBuffer();
return new Uint8Array(arrayBuffer);
};
return await mediaInfoInstance.analyzeData(getSize, readChunk);
}
// 显示结果
function displayResults(file, mediaInfo) {
hideLoading();
document.getElementById('uploadSection').style.display = 'none';
document.getElementById('fileName').textContent = file.name;
document.getElementById('fileSize').textContent = formatFileSize(file.size);
document.getElementById('fileType').textContent = file.type || '未知';
const tracks = parseMediaInfo(mediaInfo);
fillSummaryInfo(tracks);
fillGeneralInfo(tracks.general);
fillVideoInfo(tracks.video);
fillAudioInfo(tracks.audio);
fillRawInfo(mediaInfo);
document.getElementById('resultsSection').style.display = 'block';
}
// 解析 MediaInfo 结果
function parseMediaInfo(mediaInfo) {
const tracks = { general: [], video: [], audio: [] };
if (mediaInfo && mediaInfo.media && mediaInfo.media.track) {
mediaInfo.media.track.forEach(track => {
const t = track['@type'];
if (t === 'General') tracks.general.push(track);
else if (t === 'Video') tracks.video.push(track);
else if (t === 'Audio') tracks.audio.push(track);
});
}
return tracks;
}
// 摘要信息
function fillSummaryInfo(tracks) {
const container = document.getElementById('summaryInfo');
container.innerHTML = '';
if (tracks.video.length > 0) {
tracks.video.forEach((track, index) => {
const section = document.createElement('div');
section.className = 'summary-section';
const title = document.createElement('h4');
title.innerHTML = `🎥 视频${tracks.video.length > 1 ? ' ' + (index + 1) : ''}`;
section.appendChild(title);
const text = document.createElement('div');
text.className = 'summary-text';
const parts = [];
if (track.Format) {
let codec = track.Format;
if (track.Format_Profile) codec += ` (${track.Format_Profile})`;
parts.push(`编码:${codec}`);
}
if (track.Width && track.Height) {
let res = `${track.Width}×${track.Height}`;
if (track.DisplayAspectRatio) res += ` (${formatAspectRatio(track.DisplayAspectRatio)})`;
parts.push(`分辨率:${res}`);
}
if (track.FrameRate) parts.push(`帧率:${formatValue('FrameRate', track.FrameRate)}`);
if (track.BitRate) parts.push(`码率:${formatValue('BitRate', track.BitRate)}`);
text.textContent = parts.length ? parts.join(',') : '无数据';
if (!parts.length) text.className += ' no-data';
section.appendChild(text);
container.appendChild(section);
});
}
if (tracks.audio.length > 0) {
tracks.audio.forEach((track, index) => {
const section = document.createElement('div');
section.className = 'summary-section';
const title = document.createElement('h4');
title.innerHTML = `🔊 音频${tracks.audio.length > 1 ? ' ' + (index + 1) : ''}`;
section.appendChild(title);
const text = document.createElement('div');
text.className = 'summary-text';
const parts = [];
if (track.Format) {
let codec = track.Format;
if (track.Format_Profile) codec += ` (${track.Format_Profile})`;
parts.push(`编码:${codec}`);
}
if (track.SamplingRate) parts.push(`采样率:${formatValue('SamplingRate', track.SamplingRate)}`);
if (track.Channel_s_) {
let ch = `${track.Channel_s_} 声道`;
if (track.ChannelLayout) ch += ` (${track.ChannelLayout})`;
parts.push(`声道:${ch}`);
} else if (track.ChannelLayout) {
parts.push(`声道:${track.ChannelLayout}`);
}
if (track.BitRate) parts.push(`码率:${formatValue('BitRate', track.BitRate)}`);
text.textContent = parts.length ? parts.join(',') : '无数据';
if (!parts.length) text.className += ' no-data';
section.appendChild(text);
container.appendChild(section);
});
}
if (tracks.video.length === 0 && tracks.audio.length === 0) {
const section = document.createElement('div');
section.className = 'summary-section';
section.innerHTML = '<div class="summary-text no-data">未找到视频/音频轨</div>';
container.appendChild(section);
}
}
// 常规信息
function fillGeneralInfo(generalTracks) {
const container = document.getElementById('generalInfo');
container.innerHTML = '';
if (generalTracks.length === 0) {
container.innerHTML = '<p>无常规信息</p>';
return;
}
const track = generalTracks[0];
const fields = [
{ key: 'CompleteName', label: '完整名称' },
{ key: 'Format', label: '格式' },
{ key: 'Format_Version', label: '格式版本' },
{ key: 'FileSize', label: '文件大小' },
{ key: 'Duration', label: '时长' },
{ key: 'OverallBitRate', label: '总码率' },
{ key: 'Encoded_Date', label: '编码日期' },
{ key: 'Tagged_Date', label: '标记日期' }
];
const grid = document.createElement('div');
grid.className = 'info-grid';
fields.forEach(f => {
const value = track[f.key];
if (value) grid.appendChild(createInfoItem(f.label, formatValue(f.key, value)));
});
container.appendChild(grid);
}
// 视频信息
function fillVideoInfo(videoTracks) {
const container = document.getElementById('videoInfo');
container.innerHTML = '';
if (videoTracks.length === 0) {
container.innerHTML = '<p>未找到视频轨</p>';
return;
}
videoTracks.forEach((track, index) => {
const div = document.createElement('div');
div.className = 'track-info';
if (videoTracks.length > 1) {
const h = document.createElement('h4');
h.textContent = `视频轨 ${index + 1}`;
div.appendChild(h);
}
const fields = [
{ key: 'Format', label: '格式' },
{ key: 'Format_Profile', label: '格式配置' },
{ key: 'Width', label: '宽度' },
{ key: 'Height', label: '高度' },
{ key: 'DisplayAspectRatio', label: '宽高比' },
{ key: 'FrameRate', label: '帧率' },
{ key: 'BitRate', label: '码率' },
{ key: 'ColorSpace', label: '色彩空间' },
{ key: 'BitDepth', label: '位深' },
{ key: 'Duration', label: '时长' }
];
const grid = document.createElement('div');
grid.className = 'info-grid';
fields.forEach(f => {
const value = track[f.key];
if (value) grid.appendChild(createInfoItem(f.label, formatValue(f.key, value)));
});
div.appendChild(grid);
container.appendChild(div);
});
}
// 音频信息
function fillAudioInfo(audioTracks) {
const container = document.getElementById('audioInfo');
container.innerHTML = '';
if (audioTracks.length === 0) {
container.innerHTML = '<p>未找到音频轨</p>';
return;
}
audioTracks.forEach((track, index) => {
const div = document.createElement('div');
div.className = 'track-info';
if (audioTracks.length > 1) {
const h = document.createElement('h4');
h.textContent = `音频轨 ${index + 1}`;
div.appendChild(h);
}
const fields = [
{ key: 'Format', label: '格式' },
{ key: 'Format_Profile', label: '格式配置' },
{ key: 'Duration', label: '时长' },
{ key: 'BitRate', label: '码率' },
{ key: 'Channel_s_', label: '声道数' },
{ key: 'ChannelLayout', label: '声道布局' },
{ key: 'SamplingRate', label: '采样率' },
{ key: 'BitDepth', label: '位深' },
{ key: 'Language', label: '语言' }
];
const grid = document.createElement('div');
grid.className = 'info-grid';
fields.forEach(f => {
const value = track[f.key];
if (value) grid.appendChild(createInfoItem(f.label, formatValue(f.key, value)));
});
div.appendChild(grid);
container.appendChild(div);
});
}
// 原始数据
function fillRawInfo(mediaInfo) {
document.getElementById('rawInfo').textContent = JSON.stringify(mediaInfo, null, 2);
}
// 值格式化
function formatValue(key, value) {
if (!value && value !== 0) return '';
if (key === 'Duration') return formatDuration(value);
if (key === 'FileSize' && !isNaN(value)) return formatFileSize(parseInt(value, 10));
if ((key === 'BitRate' || key === 'OverallBitRate') && !isNaN(value))
return Math.round(parseInt(value, 10) / 1000) + ' kbps';
if (key === 'SamplingRate' && !isNaN(value))
return Math.round(parseInt(value, 10) / 1000) + ' kHz';
if (key === 'FrameRate' && !isNaN(value))
return parseFloat(value).toFixed(3) + ' fps';
if ((key === 'Width' || key === 'Height') && !isNaN(value))
return value + ' px';
if (key === 'DisplayAspectRatio') return formatAspectRatio(value);
return value.toString();
}
// 时长格式化
function formatDuration(duration) {
if (!duration) return '';
if (typeof duration === 'string' && (duration.includes('h') || duration.includes(':')))
return duration;
let totalSeconds;
if (typeof duration === 'string') {
const parsed = parseFloat(duration);
if (isNaN(parsed)) return duration;
totalSeconds = parsed;
} else {
totalSeconds = parseFloat(duration);
}
if (totalSeconds > 3600000) totalSeconds = totalSeconds / 1000;
const hours = Math.floor(totalSeconds / 3600);
const minutes = Math.floor((totalSeconds % 3600) / 60);
const seconds = Math.floor(totalSeconds % 60);
if (hours > 0) {
return `${hours}:${minutes.toString().padStart(2, '0')}:${seconds.toString().padStart(2, '0')}`;
}
return `${minutes}:${seconds.toString().padStart(2, '0')}`;
}
// 宽高比格式化
function formatAspectRatio(ratio) {
if (!ratio) return '';
if (typeof ratio === 'string' && ratio.includes(':')) return ratio;
const numericRatio = parseFloat(ratio);
if (isNaN(numericRatio)) return ratio;
const commonRatios = [
{ ratio: 16 / 9, display: '16:9' },
{ ratio: 4 / 3, display: '4:3' },
{ ratio: 21 / 9, display: '21:9' },
{ ratio: 1.85, display: '1.85:1' },
{ ratio: 2.35, display: '2.35:1' },
{ ratio: 2.39, display: '2.39:1' },
{ ratio: 1, display: '1:1' },
{ ratio: 3 / 2, display: '3:2' },
{ ratio: 5 / 4, display: '5:4' },
{ ratio: 16 / 10, display: '16:10' }
];
let closest = commonRatios[0];
let minDiff = Math.abs(numericRatio - closest.ratio);
commonRatios.forEach(r => {
const d = Math.abs(numericRatio - r.ratio);
if (d < minDiff) { minDiff = d; closest = r; }
});
if (minDiff < 0.01) return closest.display;
const simplified = simplifyRatio(numericRatio);
if (simplified) return simplified;
return numericRatio.toFixed(2) + ':1';
}
function simplifyRatio(decimal) {
for (let denominator = 1; denominator <= 20; denominator++) {
const numerator = Math.round(decimal * denominator);
if (Math.abs(numerator / denominator - decimal) < 0.005) {
const gcd = findGCD(numerator, denominator);
const num = numerator / gcd;
const den = denominator / gcd;
if (num <= 50 && den <= 50) return `${num}:${den}`;
}
}
return null;
}
function findGCD(a, b) {
while (b !== 0) {
const t = b;
b = a % b;
a = t;
}
return a;
}
// 创建信息项
function createInfoItem(label, value) {
const item = document.createElement('div');
item.className = 'info-item';
const labelSpan = document.createElement('span');
labelSpan.className = 'label';
labelSpan.textContent = label + ':';
const valueSpan = document.createElement('span');
valueSpan.className = 'value';
valueSpan.textContent = value;
item.appendChild(labelSpan);
item.appendChild(valueSpan);
return item;
}
// 切换标签
function showTab(tabName) {
document.querySelectorAll('.tab-pane').forEach(el => el.classList.remove('active'));
document.querySelectorAll('.tab-btn').forEach(el => el.classList.remove('active'));
document.getElementById(tabName + '-tab').classList.add('active');
if (window.event && window.event.target) window.event.target.classList.add('active');
}
// 加载状态
function showLoading() {
document.getElementById('loadingSection').style.display = 'block';
document.getElementById('resultsSection').style.display = 'none';
if (!document.getElementById('progressBar')) {
const section = document.getElementById('loadingSection');
const wrap = document.createElement('div');
wrap.className = 'progress-container';
wrap.innerHTML = `
<div class="progress-bar-container">
<div class="progress-bar" id="progressBar"></div>
</div>
<div class="progress-text" id="progressText">初始化...</div>
`;
section.appendChild(wrap);
}
}
function updateProgress(percent, text) {
const bar = document.getElementById('progressBar');
const txt = document.getElementById('progressText');
const loadingText = document.getElementById('loadingText');
if (bar) bar.style.width = percent + '%';
if (txt) txt.textContent = text || `${Math.round(percent)}%`;
if (loadingText && text) loadingText.textContent = text;
}
function hideLoading() {
document.getElementById('loadingSection').style.display = 'none';
}
// 重置
function resetAnalyzer() {
document.getElementById('resultsSection').style.display = 'none';
document.getElementById('uploadSection').style.display = 'block';
document.getElementById('fileInput').value = '';
currentFileData = null;
const pc = document.querySelector('.progress-container');
if (pc) pc.remove();
}
// 导出结果
function exportResults() {
if (!currentFileData) return;
const raw = document.getElementById('rawInfo').textContent;
const blob = new Blob([raw], { type: 'application/json' });
const url = URL.createObjectURL(blob);
const a = document.createElement('a');
a.href = url;
a.download = (currentFileData.name || 'video') + '_mediainfo.json';
document.body.appendChild(a);
a.click();
document.body.removeChild(a);
URL.revokeObjectURL(url);
}
// 文件大小格式化
function formatFileSize(bytes) {
if (bytes === 0) return '0 Bytes';
const k = 1024;
const sizes = ['Bytes', 'KB', 'MB', 'GB', 'TB'];
const i = Math.floor(Math.log(bytes) / Math.log(k));
return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
}