‘liusuyi’
2023-08-31 296bc1c12ed1cff4839a6387757845c98379c273
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
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>自适应容器示例</title>
    <script th:src="@{/js/jquery-3.6.4.min.js}"></script>
    <style>
        body, html {
            margin: 0;
            padding: 0;
            height: 100%;
        }
 
        .container-wrapper {
            display: flex;
            flex-direction: column;
            height: 100%;
        }
 
        .container {
            background-color: #151414; /* 将网格项目的颜色设置为红色背景 */
            flex: 9;
            border: 1px solid #ccc;
            box-sizing: border-box;
            display: grid;
            grid-template-columns: repeat(2, 1fr); /* 默认 2x2 网格 */
            grid-gap: 10px;
            overflow: hidden; /* 防止视频溢出容器 */
        }
 
        .grid-item {
            background-color: #151414; /* 将网格项目的颜色设置为红色背景 */
            text-align: center;
            display: flex;
            justify-content: center;
            align-items: center;
            border: 1px solid #ccc;
            box-sizing: border-box;
            padding: 10px; /* 内边距为 10px */
            position: relative; /* 添加相对定位 */
        }
 
        .video-container {
            width: 100%;
            height: 100%;
            display: flex;
            justify-content: center;
            align-items: center;
            overflow: hidden; /* 防止视频溢出容器 */
            position: absolute; /* 添加绝对定位 */
            top: 0;
            left: 0;
            right: 0;
            bottom: 0;
        }
 
        .container2 {
            flex: 1;
            border: 1px solid #ccc;
            padding: 10px;
            box-sizing: border-box;
        }
 
        /* 修改 video 样式 */
        video {
            width: 100%;
            height: 100%;
            object-fit: fill;
        }
    </style>
</head>
<body>
<div class="container-wrapper">
    <div class="container" id="gridContainer">
        <!-- 网格项目将由 JavaScript 动态生成 -->
    </div>
    <div class="container2">
        <div class="button-container">
            <button class="toggle-button" onclick="changeGrid(1, 1)">1x1</button>
            <button class="toggle-button" onclick="changeGrid(2, 2)">2x2</button>
            <button class="toggle-button" onclick="changeGrid(3, 3)">3x3</button>
            <button class="toggle-button" onclick="changeGrid(4, 4)">4x4</button>
        </div>
    </div>
</div>
 
<script>
    function calculateAspectRatio(videoWidth, videoHeight) {
        return videoWidth / videoHeight;
    }
 
    function adjustGridItemSize(gridItem, videoWidth, videoHeight) {
        const aspectRatio = calculateAspectRatio(videoWidth, videoHeight);
        gridItem.style.aspectRatio = aspectRatio; /* 设置宽高比 */
    }
 
    function changeGrid(rows, cols) {
        closeAllVideo();
        const gridContainer = document.getElementById('gridContainer');
        gridContainer.innerHTML = '';
 
        for (let i = 1; i <= rows * cols; i++) {
            const gridItem = document.createElement('div');
            gridItem.className = 'grid-item';
            const videoContainer = document.createElement('div');
            videoContainer.className = 'video-container';
            const video = document.createElement('video');
            video.id="video"+i;
            video.controls = true;
            video.autoplay = true;
            video.muted = true;
            videoContainer.appendChild(video);
            gridItem.appendChild(videoContainer);
            gridContainer.appendChild(gridItem);
 
            video.addEventListener('loadedmetadata', function () {
                adjustGridItemSize(gridItem, gridItem.videoWidth, gridItem.videoHeight);
            });
            console.log(video.id)
        }
 
        gridContainer.style.gridTemplateColumns = `repeat(${cols}, 1fr)`;
    }
 
 
    var chanMap = new Map();
    window.onload = function () {
        changeGrid(2, 2);
        chanMap.set("video1", "http://127.0.0.1:8889/245/");
        chanMap.set("video2", "http://127.0.0.1:8889/164/");
        chanMap.set("video3", "http://127.0.0.1:8889/164/");
        chanMap.set("video4", "http://127.0.0.1:8889/165/");
        chanMap.set("video5", "http://127.0.0.1:8889/165/");
        console.log(chanMap);
    }
    const linkToIceServers = (links) => (
        (links !== null) ? links.split(', ').map((link) => {
            const m = link.match(/^<(.+?)>; rel="ice-server"(; username="(.*?)"; credential="(.*?)"; credential-type="password")?/i);
            const ret = {
                urls: [m[1]],
            };
 
            if (m[3] !== undefined) {
                ret.username = unquoteCredential(m[3]);
                ret.credential = unquoteCredential(m[4]);
                ret.credentialType = "password";
            }
 
            return ret;
        }) : []
    );
    const parseOffer = (offer) => {
        const ret = {
            iceUfrag: '',
            icePwd: '',
            medias: [],
        };
 
        for (const line of offer.split('\r\n')) {
            if (line.startsWith('m=')) {
                ret.medias.push(line.slice('m='.length));
            } else if (ret.iceUfrag === '' && line.startsWith('a=ice-ufrag:')) {
                ret.iceUfrag = line.slice('a=ice-ufrag:'.length);
            } else if (ret.icePwd === '' && line.startsWith('a=ice-pwd:')) {
                ret.icePwd = line.slice('a=ice-pwd:'.length);
            }
        }
 
        return ret;
    };
    const generateSdpFragment = (offerData, candidates) => {
        const candidatesByMedia = {};
        for (const candidate of candidates) {
            const mid = candidate.sdpMLineIndex;
            if (candidatesByMedia[mid] === undefined) {
                candidatesByMedia[mid] = [];
            }
            candidatesByMedia[mid].push(candidate);
        }
 
        let frag = 'a=ice-ufrag:' + offerData.iceUfrag + '\r\n'
            + 'a=ice-pwd:' + offerData.icePwd + '\r\n';
 
        let mid = 0;
 
        for (const media of offerData.medias) {
            if (candidatesByMedia[mid] !== undefined) {
                frag += 'm=' + media + '\r\n'
                    + 'a=mid:' + mid + '\r\n';
 
                for (const candidate of candidatesByMedia[mid]) {
                    frag += 'a=' + candidate.candidate + '\r\n';
                }
            }
            mid++;
        }
 
        return frag;
    }
 
    class WHEPClient {
        constructor(wurl, videoId) {
            this.video = videoId;
            this.url = new URL('whep', wurl);
            this.pc = null;
            this.restartTimeout = null;
            this.eTag = '';
            this.queuedCandidates = [];
            this.start();
        }
 
        start() {
            console.log("requesting ICE servers");
            fetch(this.url, {
                method: 'OPTIONS',
            })
                .then((res) => this.onIceServers(res))
                .catch((err) => {
                    console.log('error: ' + err);
                    this.scheduleRestart();
                });
        }
 
        onIceServers(res) {
            this.pc = new RTCPeerConnection({
                iceServers: linkToIceServers(res.headers.get('Link')),
            });
 
            const direction = "sendrecv";
            this.pc.addTransceiver("video", {direction});
            this.pc.addTransceiver("audio", {direction});
 
            this.pc.onicecandidate = (evt) => this.onLocalCandidate(evt);
            this.pc.oniceconnectionstatechange = () => this.onConnectionState();
 
            this.pc.ontrack = (evt) => {
                console.log("new track:", evt.track.kind);
                document.getElementById(this.video).srcObject = evt.streams[0];
            };
 
            this.pc.createOffer()
                .then((offer) => this.onLocalOffer(offer));
        }
 
        onLocalOffer(offer) {
            this.offerData = parseOffer(offer.sdp);
            this.pc.setLocalDescription(offer);
 
            console.log("sending offer");
 
            fetch(this.url, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/sdp',
                },
                body: offer.sdp,
            })
                .then((res) => {
                    if (res.status !== 201) {
                        throw new Error('bad status code');
                    }
                    this.eTag = res.headers.get('E-Tag');
                    return res.text();
                })
                .then((sdp) => this.onRemoteAnswer(new RTCSessionDescription({
                    type: 'answer',
                    sdp,
                })))
                .catch((err) => {
                    console.log('error: ' + err);
                    this.scheduleRestart();
                });
        }
 
        onConnectionState() {
            if (this.restartTimeout !== null) {
                return;
            }
 
            console.log("peer connection state:", this.pc.iceConnectionState);
 
            switch (this.pc.iceConnectionState) {
                case "disconnected":
                    this.scheduleRestart();
            }
        }
 
        onRemoteAnswer(answer) {
            if (this.restartTimeout !== null) {
                return;
            }
 
            this.pc.setRemoteDescription(new RTCSessionDescription(answer));
 
            if (this.queuedCandidates.length !== 0) {
                this.sendLocalCandidates(this.queuedCandidates);
                this.queuedCandidates = [];
            }
        }
 
        onLocalCandidate(evt) {
            if (this.restartTimeout !== null) {
                return;
            }
 
            if (evt.candidate !== null) {
                if (this.eTag === '') {
                    this.queuedCandidates.push(evt.candidate);
                } else {
                    this.sendLocalCandidates([evt.candidate])
                }
            }
        }
 
        sendLocalCandidates(candidates) {
            fetch(this.url, {
                method: 'PATCH',
                headers: {
                    'Content-Type': 'application/trickle-ice-sdpfrag',
                    'If-Match': this.eTag,
                },
                body: generateSdpFragment(this.offerData, candidates),
            })
                .then((res) => {
                    if (res.status !== 204) {
                        throw new Error('bad status code');
                    }
                })
                .catch((err) => {
                    console.log('error: ' + err);
                    this.scheduleRestart();
                });
        }
 
        scheduleRestart() {
            if (this.restartTimeout !== null) {
                return;
            }
 
            if (this.pc !== null) {
                this.pc.close();
                this.pc = null;
            }
 
            this.restartTimeout = window.setTimeout(() => {
                this.restartTimeout = null;
                this.start();
            }, restartPause);
 
            this.eTag = '';
            this.queuedCandidates = [];
        }
 
        stop() {
            if (this.pc) {
                try {
                    this.pc.close();
                } catch (e) {
                    console.log("Failure close peer connection:" + e);
                }
                this.pc = null;
            }
        }
    }
 
    let videoMap = new Map();
    $(document).on('click', 'video', function() {
        let ID = this.id;//获取当前点击事件的元素
        console.log(ID);
        console.log(videoMap);
        if (videoMap.get(ID) != null) {
            closeVideo(ID);
        } else {
            let stream = chanMap.get(ID);
            let client = new WHEPClient(stream, ID);
            videoMap.set(ID, client);
        }
    });
 
    function closeVideo(id) {
        console.log("关闭" + id)
        let client = videoMap.get(id);
        client.stop(id);
        videoMap.delete(id);
    }
    function closeAllVideo(){
        videoMap.forEach((val,key) => {
            console.log(val,key);
            val.stop(key);
            videoMap.delete(key);
        })
    }
 
</script>
</body>
</html>