-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpush_transcode.html
More file actions
636 lines (568 loc) · 28.1 KB
/
Copy pathpush_transcode.html
File metadata and controls
636 lines (568 loc) · 28.1 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
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<title>多码率转播-WS-FLV</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<script type="text/javascript" charset="utf-8" src="/aliplayer-min.js"></script>
<link rel="stylesheet" href="/aliplayer-min.css">
<style>
:root { --bg:#0f0f1a; --card:#1a1a2e; --accent:#4cc9f0; --danger:#f72585; --success:#06d6a0; --text:#e0e0e0; --muted:#888; --border:#2a2a3e; --warning:#ff9f1c; }
* { margin:0; padding:0; box-sizing:border-box; }
body { font-family:-apple-system,BlinkMacSystemFont,'Segoe UI',Roboto,sans-serif; background:var(--bg); color:var(--text); min-height:100vh; display:flex; align-items:center; justify-content:center; padding:20px; }
.container { width:100%; max-width:900px; background:var(--card); border-radius:16px; padding:30px; box-shadow:0 20px 60px rgba(0,0,0,0.5); }
.header { display:flex; align-items:center; justify-content:space-between; margin-bottom:20px; flex-wrap:wrap; gap:12px; }
.title { font-size:1.4em; font-weight:600; display:flex; align-items:center; gap:10px; }
.dot { width:10px; height:10px; border-radius:50%; background:var(--muted); }
.dot.live { background:var(--danger); animation:pulse 1.5s infinite; }
@keyframes pulse { 0%,100%{opacity:1} 50%{opacity:0.3} }
.btn { padding:10px 22px; border:none; border-radius:8px; font-size:0.95em; font-weight:500; cursor:pointer; display:inline-flex; align-items:center; gap:6px; }
.btn-start { background:var(--accent); color:#000; } .btn-stop { background:var(--danger); color:#fff; }
.btn:disabled { opacity:0.4; cursor:not-allowed; }
.input-group { margin-bottom:16px; }
.input-group label { display:block; font-size:0.85em; color:var(--muted); margin-bottom:6px; }
.input-group input { width:100%; padding:8px 12px; border-radius:6px; border:1px solid var(--border); background:var(--bg); color:var(--text); font-size:0.9em; }
.preview-wrap { background:#000; border-radius:12px; overflow:hidden; margin-bottom:20px; border:2px solid var(--border); position:relative; }
.preview-wrap canvas { width:100%; display:block; max-height:400px; }
.overlay { position:absolute; bottom:12px; left:12px; background:rgba(0,0,0,0.7); color:var(--danger); padding:4px 10px; border-radius:4px; font-size:0.75em; display:none; }
.overlay.show { display:block; }
.stats { display:grid; grid-template-columns:repeat(4,1fr); gap:12px; margin-bottom:20px; }
.stat-card { background:rgba(255,255,255,0.03); border:1px solid var(--border); border-radius:10px; padding:14px; text-align:center; }
.stat-card .value { font-size:1.6em; font-weight:700; font-family:monospace; }
.stat-card .label { font-size:0.75em; color:var(--muted); margin-top:4px; }
.value.video { color:var(--accent); } .value.audio { color:var(--success); } .value.time { color:#ff9f1c; }
.settings { display:flex; gap:16px; flex-wrap:wrap; padding:16px; background:rgba(255,255,255,0.02); border:1px solid var(--border); border-radius:10px; margin-bottom:20px; }
.setting { display:flex; align-items:center; gap:8px; }
.setting label { font-size:0.85em; color:var(--muted); }
.setting select { padding:6px 10px; border-radius:6px; border:1px solid var(--border); background:var(--bg); color:var(--text); }
.log-panel { background:#000; border:1px solid var(--border); border-radius:10px; padding:12px; max-height:180px; overflow-y:auto; font-family:monospace; font-size:0.7em; color:#aaa; }
.log-warn { color:#ff9f1c; } .log-error { color:#f72585; } .log-success { color:#06d6a0; }
.tip-box { font-size:10px; color:#555; text-align:center; margin-top:10px; }
.tip-box span:first-child { margin-right:4px; }
</style>
</head>
<body>
<div class="container">
<div class="header">
<div class="title"><span class="dot" id="statusDot"></span>多码率转播</div>
<div>
<button class="btn btn-start" id="startBtn" onclick="startRelay()">▶ 开始转推</button>
<button class="btn btn-stop" id="stopBtn" onclick="stopRelay()" disabled>■ 停止</button>
</div>
</div>
<div class="input-group">
<label>拉流地址 (WS-FLV)</label>
<input type="text" id="pullUrl" value="ws://127.0.0.1:8501/a/b.flv">
</div>
<div class="input-group" style="margin-bottom:20px;">
<label>推流目标地址 (WS)</label>
<input type="text" id="pushUrl" value="ws://127.0.0.1:8501/a/c" style="width:100%;">
</div>
<!-- 调试预览窗口(隐藏) -->
<div id="debugPreview" style="margin-bottom:20px; display:none;">
<div class="preview-wrap">
<div id="player" style="width:100%; height:240px;"></div>
<div class="overlay" id="overlay">原始流预览</div>
</div>
</div>
<div class="preview-wrap">
<canvas id="mixCanvas" width="854" height="480"></canvas>
<div class="overlay" id="liveBadge">🔴 LIVE 转推输出</div>
</div>
<div class="stats">
<div class="stat-card"><div class="value video" id="videoCount">0</div><div class="label">视频帧</div></div>
<div class="stat-card"><div class="value audio" id="audioCount">0</div><div class="label">音频帧</div></div>
<div class="stat-card"><div class="value time" id="elapsedTime">00:00</div><div class="label">时长</div></div>
<div class="stat-card"><div class="value" style="color:#fff;" id="bitrate">0</div><div class="label">kbps</div></div>
</div>
<div class="settings">
<div class="setting"><label>分辨率</label><select id="resSelect"><option value="480x360">480×360</option><option value="640x480">640×480</option><option value="854x480" selected>854×480</option><option value="1280x720">1280×720</option><option value="1920x1080">1920×1080</option></select></div>
<div class="setting"><label>帧率</label><select id="fpsSelect"><option value="15">15</option><option value="20">20</option><option value="25" selected>25</option><option value="30">30</option></select></div>
<div class="setting"><label>码率</label><select id="bitrateSelect"><option value="200">200k</option><option value="300">300k</option><option value="500">500k</option><option value="800">800k</option><option value="1000" selected>1000k</option><option value="1500">1500k</option><option value="2000">2000k</option><option value="2500">2500k</option><option value="3000">3000k</option><option value="4000">4000k</option></select></div>
</div>
<div class="log-panel" id="logPanel"></div>
<div class="tip-box">
<span>💡</span>
<span>本页面旨在提供一个直播转码思路:通过前端 Web 页面实现低成本直播转码,可任意设置不同码率推流,无需专用硬件芯片和软件</span>
</div>
<div style="margin-top:30px;padding:12px 0;text-align:center;font-size:12px;color:#6a6a7a;border-top:1px solid rgba(255,255,255,0.06);">
本页面由 <strong style="color:#6c8cff;"><a href="https://github.com/2723659854/rtmp-server" style="color: white">xiaosongshu/rtmp-server</a></strong> 提供
</div>
</div>
<script>
// ==================== 全局变量 ====================
const KEYFRAME_INTERVAL = 15;
let player = null;
let videoEl = null;
let canvas, ctx, animFrameId = null;
let audioCtx = null, audioDest = null;
let ws = null, videoEncoder = null, audioEncoder = null;
let isPushing = false;
let avcConfigSent = false, aacConfigSent = false, metaSent = false;
let videoChunkCount = 0, audioChunkCount = 0;
let totalBytes = 0, statsTimer;
let WIDTH = 854, HEIGHT = 480, FPS = 25, BITRATE = 1000000;
let streamStartPerf = 0;
let videoFrameIndex = 0, audioFrameIndex = 0;
let SAMPLE_RATE = 48000;
let canvasStream = null;
let videoReader = null;
let audioReader = null;
let canvasRenderReady = false;
// ==================== 日志 ====================
function log(msg, level = 'info') {
const t = new Date().toLocaleTimeString();
const p = document.getElementById('logPanel');
const css = level === 'warn' ? 'log-warn' : level === 'error' ? 'log-error' : level === 'success' ? 'log-success' : '';
p.innerHTML += `<div><span style="color:#555">${t}</span> <span class="${css}">${msg}</span></div>`;
p.scrollTop = p.scrollHeight;
}
// ==================== UI 更新 ====================
function updateConfig() {
const [w, h] = document.getElementById('resSelect').value.split('x');
WIDTH = +w; HEIGHT = +h;
FPS = +document.getElementById('fpsSelect').value;
BITRATE = +document.getElementById('bitrateSelect').value * 1000;
if(canvas){
canvas.width = WIDTH;
canvas.height = HEIGHT;
}
}
function updateStats() {
document.getElementById('videoCount').textContent = videoChunkCount;
document.getElementById('audioCount').textContent = audioChunkCount;
if (streamStartPerf > 0) {
const sec = Math.floor((performance.now() - streamStartPerf) / 1000);
document.getElementById('elapsedTime').textContent =
`${String(Math.floor(sec/60)).padStart(2,'0')}:${String(sec%60).padStart(2,'0')}`;
if (sec > 0) document.getElementById('bitrate').textContent =
Math.floor(totalBytes * 8 / sec / 1000);
}
}
function setStatus(live) {
document.getElementById('statusDot').className = 'dot' + (live ? ' live' : '');
document.getElementById('liveBadge').className = 'overlay' + (live ? ' show' : '');
}
// ==================== FLV 封装发送 ====================
function sendTag(type, payload, timestampMs) {
if (!isPushing || !ws || ws.readyState !== WebSocket.OPEN) return;
const size = payload.length;
const tag = new Uint8Array(11 + size + 4);
tag[0] = type;
tag[1] = (size >> 16) & 0xFF;
tag[2] = (size >> 8) & 0xFF;
tag[3] = size & 0xFF;
const ts = Math.floor(timestampMs);
tag[4] = (ts >> 16) & 0xFF;
tag[5] = (ts >> 8) & 0xFF;
tag[6] = ts & 0xFF;
tag[7] = (ts >> 24) & 0xFF;
tag[8] = 0; tag[9] = 0; tag[10] = 0;
tag.set(payload, 11);
const prevTagSize = 11 + size;
tag[prevTagSize] = (prevTagSize >> 24) & 0xFF;
tag[prevTagSize+1] = (prevTagSize >> 16) & 0xFF;
tag[prevTagSize+2] = (prevTagSize >> 8) & 0xFF;
tag[prevTagSize+3] = prevTagSize & 0xFF;
ws.send(tag);
totalBytes += tag.length;
}
function sendFlvHeader() {
if (!ws || ws.readyState !== WebSocket.OPEN) return;
ws.send(new Uint8Array([0x46,0x4C,0x56,0x01,0x05,0x00,0x00,0x00,0x09,0x00,0x00,0x00,0x00]));
}
function sendMetaData() {
if (metaSent || !isPushing) return;
metaSent = true;
function n2b(n) { const a = new Uint8Array(8); new DataView(a.buffer).setFloat64(0, n, false); return Array.from(a); }
function s2b(s) { return Array.from(new TextEncoder().encode(s)); }
const meta = [
['duration', 0], ['width', WIDTH], ['height', HEIGHT],
['videocodecid', 7], ['audiocodecid', 10],
['audiosamplerate', SAMPLE_RATE], ['audiosamplesize', 16],
['stereo', true], ['filesize', 0], ['framerate', FPS]
];
const buf = [];
buf.push(0x02, 0x00, 0x0A, ...s2b('onMetaData'), 0x03);
for (const [k, v] of meta) {
buf.push((k.length >> 8) & 0xFF, k.length & 0xFF, ...s2b(k));
if (typeof v === 'number') buf.push(0x00, ...n2b(v));
else if (typeof v === 'boolean') buf.push(0x01, v ? 1 : 0);
}
buf.push(0x00, 0x00, 0x09);
sendTag(0x12, new Uint8Array(buf), 0);
log('发送FLV MetaData标签', 'success');
}
function sendAACConfig(desc) {
if (aacConfigSent || !desc || !isPushing) return;
aacConfigSent = true;
const d = new Uint8Array(desc);
const b = new Uint8Array(2 + d.length);
b[0] = 0xAF; b[1] = 0x00; b.set(d, 2);
sendTag(8, b, 0);
log('发送AAC序列配置头', 'success');
}
function sendAvcSequenceHeader(desc) {
if (avcConfigSent || !isPushing) return;
avcConfigSent = true;
const b = new Uint8Array(5 + desc.length);
b[0] = 0x17; b[1] = 0x00; b[2] = 0; b[3] = 0; b[4] = 0;
b.set(new Uint8Array(desc), 5);
sendTag(9, b, 0);
log('发送AVC SPS/PPS序列头', 'success');
}
function buildVideoBody(data, isKey) {
const b = new Uint8Array(5 + data.length);
b[0] = isKey ? 0x17 : 0x27;
b[1] = 0x01; b[2] = 0; b[3] = 0; b[4] = 0;
b.set(data, 5);
return b;
}
function buildAudioBody(data) {
const b = new Uint8Array(2 + data.length);
b[0] = 0xAF; b[1] = 0x01;
b.set(data, 2);
return b;
}
// ==================== 拉流 ====================
function initPlayer() {
return new Promise((resolve, reject) => {
const pullUrl = document.getElementById('pullUrl').value.trim();
if (!pullUrl) return reject(new Error('请输入拉流地址'));
if (player) { try { player.dispose(); } catch(e) {} }
let playerReady = false;
let videoPlaying = false;
const checkReady = () => {
if (playerReady && videoPlaying) {
if (!videoEl) {
reject(new Error('无法获取播放器 video 元素'));
} else {
videoEl.muted = false;
log('流已就绪并开始播放', 'success');
resolve();
}
}
};
const checkVideoPlaying = (video) => {
const checkInterval = setInterval(() => {
if (video && video.readyState >= 2 && video.videoWidth > 0) {
clearInterval(checkInterval);
videoPlaying = true;
log(`开始播放: ${video.videoWidth}x${video.videoHeight}`, 'success');
checkReady();
}
}, 100);
setTimeout(() => {
clearInterval(checkInterval);
if (!videoPlaying) {
log('播放超时', 'warn');
}
}, 10000);
};
player = new Aliplayer({
id: 'player',
source: pullUrl,
width: '100%',
height: '100%',
autoplay: true,
isLive: true,
muted: false,
playsinline: true,
preload: 'auto',
useH5Prism: true,
controlBarVisibility: 'hover',
showBarTime: 3000
}, () => {
log('播放器已就绪', 'success');
playerReady = true;
videoEl = document.querySelector('#player video');
checkVideoPlaying(videoEl);
});
player.on('error', (e) => {
log(`播放错误: ${e?.message || e}`, 'error');
reject(new Error(`播放错误: ${e?.message || e}`));
});
});
}
function setupCanvasDraw() {
canvas = document.getElementById('mixCanvas');
canvas.width = WIDTH;
canvas.height = HEIGHT;
ctx = canvas.getContext('2d');
canvasRenderReady = true;
let intervalId = null;
function draw() {
ctx.fillStyle = "#000000";
ctx.fillRect(0,0,WIDTH,HEIGHT);
try{
if(videoEl && videoEl.readyState >= 2 && videoEl.videoWidth > 0){
// 保持原始比例居中显示,避免拉伸变形
const vw = videoEl.videoWidth;
const vh = videoEl.videoHeight;
const videoRatio = vw / vh;
const canvasRatio = WIDTH / HEIGHT;
let drawW, drawH, offsetX, offsetY;
if (videoRatio > canvasRatio) {
// 视频更宽,按宽度适配,上下留黑边
drawW = WIDTH;
drawH = WIDTH / videoRatio;
offsetX = 0;
offsetY = (HEIGHT - drawH) / 2;
} else {
// 视频更高(竖屏),按高度适配,左右留黑边
drawH = HEIGHT;
drawW = HEIGHT * videoRatio;
offsetX = (WIDTH - drawW) / 2;
offsetY = 0;
}
ctx.drawImage(videoEl, offsetX, offsetY, drawW, drawH);
}else{
ctx.fillStyle = "#666";
ctx.font = "16px Arial";
ctx.textAlign = "center";
ctx.fillText("等待流...", WIDTH/2, HEIGHT/2);
}
}catch(e){
console.error('画布绘制错误:', e);
}
}
function loop() {
draw();
animFrameId = requestAnimationFrame(loop);
}
function startLoop() {
if (intervalId) { clearInterval(intervalId); intervalId = null; }
if (animFrameId) { cancelAnimationFrame(animFrameId); }
loop();
}
function startInterval() {
if (animFrameId) { cancelAnimationFrame(animFrameId); animFrameId = null; }
if (intervalId) { clearInterval(intervalId); }
intervalId = setInterval(draw, 1000 / FPS);
}
document.addEventListener('visibilitychange', () => {
if (document.hidden) {
log('页面进入后台,切换为定时渲染', 'warn');
startInterval();
} else {
log('页面恢复前台,切换为动画帧渲染', 'info');
startLoop();
}
});
startLoop();
log('画布渲染循环启动(已启用后台保持)', 'info');
}
function setupAudio() {
if (!audioCtx) audioCtx = new (window.AudioContext || window.webkitAudioContext)();
if(audioCtx.state === 'suspended') audioCtx.resume();
audioDest = audioCtx.createMediaStreamDestination();
const source = audioCtx.createMediaElementSource(videoEl);
const gain = audioCtx.createGain();
gain.gain.value = 0.8;
source.connect(gain).connect(audioDest);
gain.connect(audioCtx.destination);
log('音频通道已建立', 'info');
}
// ==================== 编码推流 ====================
async function startEncoding() {
updateConfig();
videoChunkCount = 0; audioChunkCount = 0; totalBytes = 0;
avcConfigSent = false; aacConfigSent = false; metaSent = false;
videoFrameIndex = 0; audioFrameIndex = 0;
streamStartPerf = performance.now();
videoReader = null;
audioReader = null;
const pushUrl = document.getElementById('pushUrl').value.trim();
ws = new WebSocket(pushUrl);
ws.binaryType = 'arraybuffer';
ws.onopen = async () => {
log('推流WebSocket连接成功', 'success');
isPushing = true;
document.getElementById('startBtn').disabled = true;
document.getElementById('stopBtn').disabled = false;
setStatus(true);
statsTimer = setInterval(updateStats, 500);
sendFlvHeader();
sendMetaData();
if(canvasStream) canvasStream.getTracks().forEach(t=>t.stop());
canvasStream = canvas.captureStream(FPS);
const videoTrack = canvasStream.getVideoTracks()[0];
videoEncoder = new VideoEncoder({
output(chunk, meta) {
if (!isPushing) return;
const data = new Uint8Array(chunk.byteLength);
chunk.copyTo(data);
if (meta?.decoderConfig?.description && !avcConfigSent) {
sendAvcSequenceHeader(new Uint8Array(meta.decoderConfig.description));
}
if (data.length > 0) {
videoChunkCount++;
const dts = videoFrameIndex * (1000 / FPS);
sendTag(9, buildVideoBody(data, chunk.type === 'key'), dts);
videoFrameIndex++;
}
},
error(e) { log(`视频编码错误: ${e.message}`, 'error'); }
});
// 根据分辨率动态选择 AVC level
// level 3.1 (31=0x1F): 最大约1280x720
// level 4.0 (32=0x28): 支持1920x1080
// level 4.1 (33=0x29): 支持更高分辨率
const pixels = WIDTH * HEIGHT;
let avcLevel;
if (pixels <= 921600) {
avcLevel = '1F'; // level 3.1
} else if (pixels <= 2073600) {
avcLevel = '28'; // level 4.0
} else {
avcLevel = '29'; // level 4.1
}
const codecStr = `avc1.4200${avcLevel}`;
videoEncoder.configure({
codec: codecStr,
width: WIDTH,
height: HEIGHT,
bitrate: BITRATE,
framerate: FPS,
latencyMode: 'realtime',
bitrateMode: 'constant',
rcQuota: { qMin: 10, qMax: 51 },
maxFramerate: FPS
});
log(`视频编码器配置完成 ${WIDTH}x${HEIGHT} ${FPS}fps`, 'success');
log(`canvasRenderReady状态: ${canvasRenderReady}`, 'info');
const audioTrack = audioDest.stream.getAudioTracks()[0];
if (audioTrack) {
const audioSettings = audioTrack.getSettings();
SAMPLE_RATE = audioSettings.sampleRate || 48000;
audioEncoder = new AudioEncoder({
output(chunk, meta) {
if (!isPushing) return;
if (meta?.decoderConfig?.description && !aacConfigSent) {
sendAACConfig(meta.decoderConfig.description);
}
const data = new Uint8Array(chunk.byteLength);
chunk.copyTo(data);
if (data.length > 0) {
audioChunkCount++;
const frameDurationMs = (1024 / SAMPLE_RATE) * 1000;
const dts = audioFrameIndex * frameDurationMs;
sendTag(8, buildAudioBody(data), dts);
audioFrameIndex++;
}
},
error(e) { log(`音频编码错误: ${e.message}`, 'error'); }
});
audioEncoder.configure({
codec: 'mp4a.40.2',
sampleRate: SAMPLE_RATE,
numberOfChannels: Math.min(audioSettings.channelCount || 1, 2),
bitrate: 96000
});
log(`音频编码器: ${SAMPLE_RATE}Hz ${Math.min(audioSettings.channelCount,2)}ch`, 'info');
}
log('开始读取视频帧', 'success');
const vp = new MediaStreamTrackProcessor({ track: videoTrack });
videoReader = vp.readable.getReader();
let fc = 0, lkf = -KEYFRAME_INTERVAL;
log('开始采集视频帧', 'info');
(async function readVideo() {
while (isPushing) {
try {
const { done, value } = await videoReader.read();
if (done) { log('视频轨道结束', 'info'); break; }
if (videoEncoder && videoEncoder.state === 'configured') {
const isKey = (fc - lkf >= KEYFRAME_INTERVAL) || fc === 0;
videoEncoder.encode(value, { keyFrame: isKey });
if (isKey) lkf = fc;
fc++;
}
value.close();
} catch (e) { if (isPushing) log(`视频读取异常: ${e.message}`, 'error'); break; }
}
})();
if (audioTrack) {
const ap = new MediaStreamTrackProcessor({ track: audioTrack });
audioReader = ap.readable.getReader();
(async function readAudio() {
log('开始采集音频帧', 'info');
while (isPushing) {
try {
const { done, value } = await audioReader.read();
if (done) { log('音频轨道结束', 'info'); break; }
if (audioEncoder && audioEncoder.state === 'configured') {
audioEncoder.encode(value);
}
value.close();
} catch (e) { if (isPushing) log(`音频读取异常: ${e.message}`, 'error'); break; }
}
})();
}
};
ws.onerror = () => { log('WebSocket 连接错误', 'error'); stopRelay(); };
ws.onclose = (e) => { log(`WebSocket 关闭 (code:${e.code})`, 'warn'); if (isPushing) stopRelay(); };
}
// ==================== 开始 / 停止 ====================
async function startRelay() {
if (isPushing) return;
try {
log('正在拉取流...', 'info');
await initPlayer();
setupCanvasDraw();
setupAudio();
log('转推初始化完成,建立推流连接...', 'success');
await startEncoding();
} catch (err) {
log(`启动失败: ${err.message}`, 'error');
await stopRelay();
}
}
async function stopRelay() {
if (!isPushing && !player) return;
log('正在停止转推,释放资源...', 'warn');
isPushing = false;
if(videoReader){ try{ await videoReader.cancel(); }catch(e){} videoReader = null; }
if(audioReader){ try{ await audioReader.cancel(); }catch(e){} audioReader = null; }
if (videoEncoder && videoEncoder.state !== 'closed') {
try { await videoEncoder.flush(); } catch(e) {}
try { videoEncoder.close(); } catch(e) {}
videoEncoder = null;
}
if (audioEncoder && audioEncoder.state !== 'closed') {
try { await audioEncoder.flush(); } catch(e) {}
try { audioEncoder.close(); } catch(e) {}
audioEncoder = null;
}
if(canvasStream){
canvasStream.getTracks().forEach(track=>track.stop());
canvasStream = null;
}
if (statsTimer) { clearInterval(statsTimer); statsTimer = null; }
if (animFrameId) { cancelAnimationFrame(animFrameId); animFrameId = null; }
if (audioCtx) {
try { await audioCtx.close(); } catch(e) {}
audioCtx = null;
audioDest = null;
}
if (ws) { try { ws.close(1000, "stop"); } catch(e) {} ws = null; }
if (player) { try { player.dispose(); } catch(e) {} player = null; videoEl = null; }
document.getElementById('startBtn').disabled = false;
document.getElementById('stopBtn').disabled = true;
setStatus(false);
updateStats();
log('所有资源已释放,停止完成', 'warn');
}
document.getElementById('resSelect').addEventListener('change', ()=>{
if(!isPushing) updateConfig();
else log('推流中切换分辨率需重启推流生效', 'warn');
});
window.addEventListener('beforeunload', async (e) => {
if (isPushing) {
e.preventDefault();
await stopRelay();
}
});
log('就绪,请填入 WS-FLV 拉流地址及推流目标地址,点击开始转推', 'info');
</script>
</body>
</html>