-
Notifications
You must be signed in to change notification settings - Fork 36
Expand file tree
/
Copy pathkurento-service.js
More file actions
2756 lines (2375 loc) · 94.4 KB
/
kurento-service.js
File metadata and controls
2756 lines (2375 loc) · 94.4 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
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* Copyright 2023 SejonJang (wkdtpwhs@gmail.com)
*
* Licensed under the GNU General Public License v3.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.gnu.org/licenses/gpl-3.0.html
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
// //console.log("location.host : "+location.host)
let locationHost = window.__CONFIG__.API_BASE_URL.replace(/^https?:\/\//, '').replace(/:\d+$/, '');
let participants = {};
let userId = null;
let nickName = null;
let roomId = null;
let roomName = null;
// turn Config
let turnUrl = null;
let turnUser = null;
let turnPwd = null;
let origGetUserMedia;
// websocket 연결 확인 후 register() 실행
var ws = new WebSocket(window.__CONFIG__.API_BASE_URL.replace(/^http/, 'ws') + '/signal');
ws.onopen = () => {
register();
initScript();
initEvent();
}
var initTurnServer = function(){
fetch(window.__CONFIG__.API_BASE_URL + '/admin/turnconfig', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
}
})
.then(response => response.json()) // JSON 데이터로 변환
.then(data => {
turnUrl = data.url;
turnUser = data.username;
turnPwd = data.credential;
})
.catch(error => {
console.error('Error:', error);
});
}
var initScript = function () {
dataChannel.init();
dataChannelChatting.init();
dataChannelFileUtil.init();
catchMind.init();
// 실시간 자막 기능
initSpeechRecognition();
initSubtitleUI();
}
let constraints = {
audio: {
autoGainControl: true,
channelCount: 2,
echoCancellation: true,
latency: 0,
noiseSuppression: true,
sampleRate: 48000,
sampleSize: 16,
volume: 0.5
}
};
let initEvent = function(){
$('#subtitleBtn').click(function(){
toggleSubtitle();
});
$('#screenShareBtn').click(function(){
screenShare();
});
}
// 오디오 권한 체크 후 미디어 초기화
async function initializeMediaDevices() {
// 오디오 에러 popup 로드
await PopupLoader.loadPopup('audio_error');
// 먼저 오디오 권한을 체크
const hasAudioPermission = await checkAudioPermission();
if (!hasAudioPermission.success) {
// 오디오 권한이 없으면 에러 모달 표시
await showAudioErrorModal(hasAudioPermission.errorType, hasAudioPermission.error);
return;
}
// 오디오 권한이 있으면 기존 로직 실행
try {
const stream = await navigator.mediaDevices.getUserMedia(constraints);
// Add your logic after successfully getting the media here.
constraints.video = {
width: { ideal: 1280, max: 1920 },
height: { ideal: 720, max: 1080 },
frameRate: {
ideal: 30, // 권장 프레임률
min: 15, // 최소 허용치
max: 30 // 최대 제한 (화면 공유 시 30fps 이상은 리소스 과부하 유발)
}
};
// 스트림 해제 (테스트용이므로)
stream.getTracks().forEach(track => track.stop());
} catch (error) {
console.error('Media devices initialization failed:', error);
await showAudioErrorModal(classifyMediaError(error), error);
}
}
// 함수 호출
initializeMediaDevices();
// navigator.mediaDevices와 그 하위의 getUserMedia 메서드가 존재하는지 확인합니다.
if (navigator.mediaDevices && navigator.mediaDevices.getUserMedia) {
// 원래의 getUserMedia 메서드를 저장합니다.
origGetUserMedia = navigator.mediaDevices.getUserMedia;
let customGetUserMedia = navigator.mediaDevices.getUserMedia.bind(navigator.mediaDevices);
// getUserMedia 메서드를 덮어씁니다.
navigator.mediaDevices.getUserMedia = function (cs) {
// 원래의 getUserMedia 메서드를 호출합니다.
return customGetUserMedia(cs).catch(function (error) {
// 비디오 요청이 실패한 경우
if (cs.video) {
console.warn("Video error occurred, using dummy video instead.", error);
// 오디오 스트림만 요청합니다.
return navigator.mediaDevices.getUserMedia({ audio: cs.audio })
.then(function (audioStream) {
// 오디오 스트림에 더미 비디오 트랙을 추가합니다.
const dummyVideoTrack = getDummyVideoTrack();
audioStream.addTrack(dummyVideoTrack);
// 수정된 스트림을 반환합니다.
return audioStream;
});
}
// 그외의 에러를 그대로 반환합니다.
return Promise.reject(error);
});
};
// 더미 비디오 트랙을 생성하는 함수입니다.
function getDummyVideoTrack() {
// 캔버스를 생성하여 더미 이미지를 그립니다.
const canvas = document.createElement('canvas');
// canvas.width = 1280;
// canvas.height = 720;
const ctx = canvas.getContext('2d');
ctx.fillStyle = 'gray';
ctx.fillRect(0, 0, canvas.width, canvas.height);
// 캔버스의 내용을 기반으로 더미 비디오 스트림을 생성합니다.
const dummyStream = canvas.captureStream(60);
// 더미 비디오 트랙을 반환합니다.
return dummyStream.getVideoTracks()[0];
}
}
ws.onmessage = function (message) {
var parsedMessage = JSON.parse(message.data);
// console.info('Received message: ' + message.data);
switch (parsedMessage.id) {
case 'existingParticipants':
onExistingParticipants(parsedMessage);
break;
case 'newParticipantArrived':
onNewParticipant(parsedMessage);
break;
case 'participantLeft':
onParticipantLeft(parsedMessage);
break;
case 'receiveVideoAnswer':
receiveVideoResponse(parsedMessage);
break;
case 'iceCandidate':
participants[parsedMessage.name].rtcPeer.addIceCandidate(parsedMessage.candidate, function (error) {
if (error) {
console.error("Error adding candidate: " + error);
return;
}
});
break;
case 'ConnectionFail': // 연결 실패 메시지 처리
// 모달을 표시
$('#connectionFailModal').modal('show');
// 모달의 확인 버튼에 클릭 이벤트 핸들러를 연결
$('#reconnectButton').click(function() {
leaveRoom('error');
window.location.reload(); // 프로미스 완료 후 페이지 새로고침
});
break;
case 'textOverlayResponse':
console.debug('textOverlayResponse', parsedMessage);
break;
default:
console.error('Unrecognized message', parsedMessage);
}
}
function register() {
// kurentoroom.html 진입 시 서버에서 방/유저 정보 조회
let kurentoRoomInfo = null;
try {
// 방 정보를 서버에서 조회
const url = window.__CONFIG__.API_BASE_URL + '/chat/room/' + new URLSearchParams(window.location.search).get('roomId');
const successCallback = (response) => {
if(response.result === 'REDIRECT_ROOM'){
console.log('room redirect to : ', response.data.roomId);
location.reload();
} else if(response.result === 'REDIRECT_DASHBOARD'){
Toastify({
text: "현재 방에 참여할 수 없습니다. \n 잠시 후 다시 시도해주세요.",
duration: 3000, // 토스트는 3초 유지
newWindow: true,
close: true,
gravity: "top",
position: "center",
stopOnFocus: true,
style: {
background: "linear-gradient(to right, #00b09b, #96c93d)",
},
}).showToast();
// 2초 후 리다이렉트
setTimeout(function() {
location.href = window.__CONFIG__.BASE_URL + '/roomlist.html';
}, 2000);
} else {
if (response?.data) {
kurentoRoomInfo = response.data;
initTurnServer();
// 방 정보가 있으면 필요한 데이터 할당
if (kurentoRoomInfo) {
// TODO userId 는 '@' 가 있어서 사용 불가능
userId = kurentoRoomInfo.nickName || kurentoRoomInfo.uuid;
nickName = kurentoRoomInfo.nickName;
roomId = kurentoRoomInfo.roomId;
roomName = kurentoRoomInfo.roomName;
// 추가 정보: userCount, maxUserCnt, roomPwd, secretChk, roomType 등
}
$('#room-header').text('ROOM ' + roomName);
$('#room').css('display', 'block');
let message = {
id: 'joinRoom',
nickName : nickName,
userId: nickName,
roomId: roomId,
}
sendMessageToServer(message);
}
}
};
const errorCallback = (error) => {
console.error('방 정보 조회 실패:', error);
if (error?.responseJSON && ['40050', '40051', '40052'].includes(error.responseJSON.code)) {
self.showToast('로그인이 필요한 서비스입니다.');
window.location.href = window.__CONFIG__.BASE_URL + '/login/chatlogin.html';
} else if (error?.responseJSON && '40061' === error.responseJSON.code) {
alert("입장 정보가 확인되지 않았습니다. 다시 시도해주세요.")
window.location.href = window.__CONFIG__.BASE_URL + '/roomlist.html';
}
};
// AJAX 요청 실행
tokenAjax(url, 'GET', false, '', successCallback, errorCallback);
} catch (e) {
console.error('kurentoRoomInfo 파싱 오류:', e);
}
}
function onNewParticipant(request) {
let newParticipant = request.data;
receiveVideo(newParticipant);
}
function receiveVideoResponse(result) {
participants[result.name].rtcPeer.processAnswer(result.sdpAnswer, function (error) {
if (error) return console.error(error);
});
}
function callResponse(message) {
if (message.response != 'accepted') {
console.info('Call not accepted by peer. Closing call');
stop();
} else {
webRtcPeer.processAnswer(message.sdpAnswer, function (error) {
if (error) return console.error(error);
});
}
}
function onExistingParticipants(msg) {
var participant = new Participant(userId, nickName, roomId);
participants[userId] = participant;
dataChannel.initDataChannelUser(participant);
var video = participant.getVideoElement();
var audio = participant.getAudioElement();
function handleSuccess(stream) {
var hasVideo = constraints.video && stream.getVideoTracks().length > 0
var options = {
localVideo: hasVideo ? video : null,
localAudio: audio,
mediaStream: stream,
mediaConstraints: constraints,
onicecandidate: participant.onIceCandidate.bind(participant),
dataChannels : true, // dataChannel 사용 여부
dataChannelConfig: { // dataChannel event 설정
id : dataChannel.getChannelName,
// onopen : dataChannel.handleDataChannelOpen,
// onclose : dataChannel.handleDataChannelClose,
onmessage : dataChannel.handleDataChannelMessageReceived,
onerror : dataChannel.handleDataChannelError
},
configuration: {
iceServers: [
{
urls: turnUrl,
username: turnUser,
credential: turnPwd
}
]
}
};
participant.rtcPeer = new kurentoUtils.WebRtcPeer.WebRtcPeerSendrecv(options,
function(error) {
if (error) {
return console.error(error);
}
this.generateOffer(participant.offerToReceiveVideo.bind(participant));
mediaDevice.init(); // video 와 audio 장비를 모두 가져온 후 mediaDvice 장비 영역 세팅
});
msg.data.forEach(receiveVideo)
}
// 오디오 권한 체크 후 getUserMedia 호출
async function initializeUserMedia() {
const hasAudioPermission = await checkAudioPermission();
if (!hasAudioPermission.success) {
showAudioErrorModal(hasAudioPermission.errorType, hasAudioPermission.error);
return;
}
try {
const stream = await navigator.mediaDevices.getUserMedia(constraints);
handleSuccess(stream);
} catch (error) {
console.error('getUserMedia failed:', error);
showAudioErrorModal(classifyMediaError(error), error);
}
}
initializeUserMedia();
}
function receiveVideo(sender) {
var participant = new Participant(sender.userId, sender.nickName, roomId);
participants[sender.userId] = participant;
var video = participant.getVideoElement();
var audio = participant.getAudioElement();
var options = {
remoteVideo: video,
remoteAudio : audio,
onicecandidate: participant.onIceCandidate.bind(participant),
dataChannels : true, // dataChannel 사용 여부
dataChannelConfig: { // dataChannel event 설정
id : dataChannel.getChannelName,
onopen : dataChannel.handleDataChannelOpen,
onclose : dataChannel.handleDataChannelClose,
onmessage : dataChannel.handleDataChannelMessageReceived,
onerror : dataChannel.handleDataChannelError
},
configuration: { // 이 부분에서 TURN 서버 연결 설정
iceServers: [
{
urls: turnUrl,
username: turnUser,
credential: turnPwd
}
]
}
}
participant.rtcPeer = new kurentoUtils.WebRtcPeer.WebRtcPeerSendrecv(options,
function (error) {
if (error) {
return console.error(error);
}
this.generateOffer(participant.offerToReceiveVideo.bind(participant));
});
participant.rtcPeer.peerConnection.onaddstream = function(event) {
audio.srcObject = event.stream;
video.srcObject = event.stream;
};
}
var leftUserfunc = function(){
// 서버로 연결 종료 메시지 전달
sendMessageToServer({
id: 'leaveRoom'
});
// 진행 중인 모든 연결을 종료
for (let key in participants) {
if (participants.hasOwnProperty(key)) {
participants[key].dispose();
}
}
// WebSocket 연결을 종료합니다.
ws.close();
}
// 웹 종료 or 새로고침 시 이벤트
window.onbeforeunload = function () {
leaveRoom();
};
// 나가기 버튼 눌렀을 때 이벤트
// 결국 replace 되기 때문에 얘도 onbeforeunload 를 탄다
$('#button-leave').on('click', function(){
setCookie('room-id', '', -1); // 쿠키 삭제
location.replace(window.__CONFIG__.BASE_URL + '/roomlist.html');
});
function leaveRoom(type) {
if(type !== 'error'){ // type 이 error 이 아닐 경우에만 퇴장 메시지 전송
sendDataChannelMessage(" 님이 떠나셨습니다ㅠㅠ");
}
// 다른 유저들의 gameParticipants 에서 방을 떠난 유저 삭제
// TODO 추후 삭제된 유저를 정의해서 특정 유저를 삭제할 필요 있음
setTimeout(leftUserfunc, 10); // 퇴장 메시지 전송을 위해 timeout 설정
}
function onParticipantLeft(request) {
var participant = participants[request.name];
//console.log('Participant ' + request.name + ' left');
participant.dispose();
delete participants[request.name];
}
function sendMessageToServer(message) {
var jsonMessage = JSON.stringify(message);
//console.log('Sending message: ' + jsonMessage);
ws.send(jsonMessage);
}
// 메시지를 데이터 채널을 통해 전송하는 함수
function sendDataChannelMessage(message){
if (participants[userId].rtcPeer.dataChannel.readyState === 'open') {
dataChannel.sendMessage(message);
} else {
console.warn("Data channel is not open. Cannot send message.");
}
}
/** 화면 공유 실행 과정
* 나와 연결된 다른 peer 에 나의 화면을 공유하기 위해서는 다른 peer 에 보내는 Track 에서 stream 을 교체할 필요가 있다.
* Track 이란 현재 MediaStream 을 구성하는 각 요소를 의미한다.
* - Track 는 오디오, 비디오, 자막 총 3개의 stream 으로 구성된다.
* - 때문에 Track 객체는 track[0] = 오디오, track[1] = 비디오 의 배열 구조로 되어있다
* MediaStream 이란 video stream 과 audio steam 등의 미디어 스트림을 다루는 객체를 이야기한다
* - stream(스트림)이란 쉽게 생각하자면 비디오와 오디오 데이터라고 이해하면 될 듯 하다 -
*
* 즉 상대방에게 보내는 track 에서 나의 웹캠 videoStream 대신 공유 화면에 해당하는 videoStream 으로 변경하는 것이다.
*
* 더 구체적으로는 아래 순서를 따른다.
*
* 1. startScreenShare() 함수를 호출합니다.
* 2. ScreenHandler.start() 함수를 호출하여 shareView 변수에 화면 공유에 사용될 MediaStream 객체를 할당합니다.
* 3. 화면 공유 화면을 로컬 화면에 표시합니다.
* 4. 연결된 다른 peer에게 화면 공유 화면을 전송하기 위해 RTCRtpSender.replaceTrack() 함수를 사용하여 연결된 다른 peer에게 전송되는 비디오 Track을 shareView.getVideoTracks()[0]으로 교체합니다.
* 5. shareView 객체의 비디오 Track이 종료되는 경우, stopScreenShare() 함수를 호출하여 화면 공유를 중지합니다.
* 5. stopScreenShare() 함수에서는 ScreenHandler.end() 함수를 호출하여 shareView 객체에서 발생하는 모든 Track에 대해 stop() 함수를 호출하여 스트림 전송을 중지합니다.
* 6. 원래 화면으로 되돌리기 위해 연결된 다른 peer에게 전송하는 Track을 로컬 비디오 Track으로 교체합니다.
* 즉, 해당 코드는 WebRTC 기술을 사용하여 MediaStream 객체를 사용해 로컬에서 받은 Track을 다른 peer로 전송하고, replaceTrack() 함수를 사용하여 비디오 Track을 교체하여 화면 공유를 구현하는 코드입니다.
* **/
// 화면 공유를 위한 변수 선언
const screenHandler = new ScreenHandler();
let shareView = null;
// 화면 공유 설정 및 통계
const screenShareConfig = {
// 화질 프리셋
qualityPresets: {
'high': {
width: { ideal: 1920, max: 1920 },
height: { ideal: 1080, max: 1080 },
frameRate: { ideal: 30, max: 30 }
},
'medium': {
width: { ideal: 1280, max: 1280 },
height: { ideal: 720, max: 720 },
frameRate: { ideal: 15, max: 20 }
},
'low': {
width: { ideal: 640, max: 640 },
height: { ideal: 360, max: 360 },
frameRate: { ideal: 10, max: 15 }
},
'auto': {
width: { ideal: 1280, max: 1920 },
height: { ideal: 720, max: 1080 },
frameRate: { ideal: 15, max: 30 }
}
},
// 현재 설정
currentQuality: 'auto',
// 통계 정보
stats: {
frameRate: 0,
bitrate: 0,
packetsLost: 0,
timestamp: Date.now()
},
// 자동 최적화 설정
autoOptimize: true,
qualityAdjustInterval: null
};
// 네트워크 품질 감지
async function detectNetworkQuality() {
try {
// RTCPeerConnection에서 통계 정보 수집
const participant = participants[userId];
if (!participant || !participant.rtcPeer || !participant.rtcPeer.peerConnection) {
return 'medium';
}
const stats = await participant.rtcPeer.peerConnection.getStats();
let outboundRtp = null;
let candidatePair = null;
stats.forEach(report => {
if (report.type === 'outbound-rtp' && report.kind === 'video') {
outboundRtp = report;
} else if (report.type === 'candidate-pair' && report.state === 'succeeded') {
candidatePair = report;
}
});
if (outboundRtp && candidatePair) {
// 향상된 네트워크 품질 분석
const bitrate = outboundRtp.bytesSent * 8 / 1000; // kbps
const packetLoss = outboundRtp.packetsLost || 0;
const rtt = candidatePair.currentRoundTripTime * 1000 || 0; // ms
const jitter = outboundRtp.jitter || 0;
// 다중 지표 기반 품질 결정
let qualityScore = 100;
// 비트레이트 점수 (40%)
if (bitrate > 2000) {
qualityScore += 0;
} else if (bitrate > 1000) {
qualityScore -= 15;
} else {
qualityScore -= 30;
}
// 패킷 손실 점수 (30%)
qualityScore -= Math.min(packetLoss * 2, 40);
// RTT 점수 (20%)
if (rtt > 200) {
qualityScore -= 20;
} else if (rtt > 100) {
qualityScore -= 10;
}
// 지터 점수 (10%)
if (jitter > 0.05) {
qualityScore -= 10;
}
// 품질 등급 결정
let quality;
if (qualityScore >= 80) {
quality = 'high';
} else if (qualityScore >= 50) {
quality = 'medium';
} else {
quality = 'low';
}
lastNetworkQuality = quality;
return quality;
}
return 'medium';
} catch (error) {
console.warn('네트워크 품질 감지 실패:', error);
return 'medium';
}
}
// 디바이스 성능 감지 시스템
const devicePerformance = {
// 성능 지표
metrics: {
cpuUsage: 0,
memoryUsage: 0,
frameDropRate: 0,
encodeTime: 0,
lastUpdated: Date.now()
},
// 성능 등급
grade: 'medium', // 'high', 'medium', 'low'
// 성능 히스토리 (최근 10개 측정값)
history: {
frameRates: [],
encodeTimes: [],
bitrates: []
}
};
// 디바이스 성능 감지
async function detectDevicePerformance() {
try {
const participant = participants[userId];
if (!participant || !participant.rtcPeer) {
return 'medium';
}
const stats = await participant.rtcPeer.peerConnection.getStats();
let outboundRtp = null;
let codecStats = null;
stats.forEach(report => {
if (report.type === 'outbound-rtp' && report.kind === 'video') {
outboundRtp = report;
} else if (report.type === 'codec' && report.mimeType && report.mimeType.includes('video')) {
codecStats = report;
}
});
if (outboundRtp) {
// 프레임률 계산
const currentFrameRate = outboundRtp.framesPerSecond || 0;
const framesSent = outboundRtp.framesSent || 0;
const framesEncoded = outboundRtp.framesEncoded || 0;
// 프레임 드롭률 계산
const frameDropRate = framesSent > 0 ? ((framesEncoded - framesSent) / framesEncoded) * 100 : 0;
// 인코딩 시간 (밀리초)
const encodeTime = outboundRtp.totalEncodeTime || 0;
const encodedFrames = outboundRtp.framesEncoded || 1;
const avgEncodeTime = (encodeTime * 1000) / encodedFrames; // ms per frame
// 메트릭 업데이트
devicePerformance.metrics.frameDropRate = frameDropRate;
devicePerformance.metrics.encodeTime = avgEncodeTime;
devicePerformance.metrics.lastUpdated = Date.now();
// 히스토리 업데이트
updatePerformanceHistory(currentFrameRate, avgEncodeTime, outboundRtp.bytesSent);
// 성능 등급 결정
return calculatePerformanceGrade();
}
return 'medium';
} catch (error) {
console.warn('디바이스 성능 감지 실패:', error);
return 'medium';
}
}
// 성능 히스토리 업데이트
function updatePerformanceHistory(frameRate, encodeTime, bitrate) {
const maxHistorySize = 10;
// 프레임률 히스토리
devicePerformance.history.frameRates.push(frameRate);
if (devicePerformance.history.frameRates.length > maxHistorySize) {
devicePerformance.history.frameRates.shift();
}
// 인코딩 시간 히스토리
devicePerformance.history.encodeTimes.push(encodeTime);
if (devicePerformance.history.encodeTimes.length > maxHistorySize) {
devicePerformance.history.encodeTimes.shift();
}
// 비트레이트 히스토리
devicePerformance.history.bitrates.push(bitrate);
if (devicePerformance.history.bitrates.length > maxHistorySize) {
devicePerformance.history.bitrates.shift();
}
}
// 성능 등급 계산
function calculatePerformanceGrade() {
const { frameDropRate, encodeTime } = devicePerformance.metrics;
const { frameRates, encodeTimes } = devicePerformance.history;
// 평균값 계산
const avgFrameRate = frameRates.length > 0 ?
frameRates.reduce((a, b) => a + b, 0) / frameRates.length : 0;
const avgEncodeTime = encodeTimes.length > 0 ?
encodeTimes.reduce((a, b) => a + b, 0) / encodeTimes.length : 0;
// 성능 점수 계산 (0-100)
let score = 100;
// 프레임 드롭률 페널티
score -= Math.min(frameDropRate * 2, 30);
// 인코딩 시간 페널티 (>20ms 시 페널티)
if (avgEncodeTime > 20) {
score -= Math.min((avgEncodeTime - 20) * 2, 30);
}
// 평균 프레임률 보너스/페널티
if (avgFrameRate < 10) {
score -= 20;
} else if (avgFrameRate > 25) {
score += 10;
}
// 성능 등급 결정
if (score >= 80) {
devicePerformance.grade = 'high';
return 'high';
} else if (score >= 50) {
devicePerformance.grade = 'medium';
return 'medium';
} else {
devicePerformance.grade = 'low';
return 'low';
}
}
// 통합 품질 결정 (네트워크 + 디바이스)
async function determineOptimalQuality() {
const networkQuality = await detectNetworkQuality();
const deviceQuality = await detectDevicePerformance();
// 품질 우선순위 매트릭스
const qualityMatrix = {
'high_high': 'high',
'high_medium': 'medium',
'high_low': 'medium',
'medium_high': 'medium',
'medium_medium': 'medium',
'medium_low': 'low',
'low_high': 'low',
'low_medium': 'low',
'low_low': 'low'
};
const key = `${networkQuality}_${deviceQuality}`;
const optimalQuality = qualityMatrix[key] || 'medium';
console.log(`품질 결정: 네트워크(${networkQuality}) + 디바이스(${deviceQuality}) = ${optimalQuality}`);
return optimalQuality;
}
// 고급 화면 공유 품질 자동 조정
async function adjustScreenShareQuality() {
if (!shareView || !screenShareConfig.autoOptimize) return;
const optimalQuality = await determineOptimalQuality();
// 현재 품질과 다를 때만 조정
if (optimalQuality !== screenShareConfig.currentQuality) {
const currentPreset = screenShareConfig.qualityPresets[optimalQuality];
// 현재 트랙의 제약조건 업데이트
const videoTrack = shareView.getVideoTracks()[0];
if (videoTrack && currentPreset) {
try {
// 점진적 품질 조정 (급격한 변화 방지)
const smoothTransition = await createSmoothQualityTransition(
screenShareConfig.currentQuality,
optimalQuality
);
await videoTrack.applyConstraints(smoothTransition);
screenShareConfig.currentQuality = optimalQuality;
console.log(`화면 공유 품질 조정: ${optimalQuality} (점진적 전환)`);
// UI 업데이트
updateScreenShareUI(optimalQuality);
// 품질 변경 알림
showQualityChangeNotification(optimalQuality);
} catch (error) {
console.warn('화면 공유 품질 조정 실패:', error);
// 실패 시 이전 품질로 롤백
try {
const fallbackPreset = screenShareConfig.qualityPresets[screenShareConfig.currentQuality];
await videoTrack.applyConstraints(fallbackPreset);
} catch (rollbackError) {
console.error('품질 롤백 실패:', rollbackError);
}
}
}
}
}
// 점진적 품질 전환 생성
async function createSmoothQualityTransition(currentQuality, targetQuality) {
const current = screenShareConfig.qualityPresets[currentQuality];
const target = screenShareConfig.qualityPresets[targetQuality];
// 중간값 계산으로 부드러운 전환
const transition = {
width: {
ideal: Math.round((current.width.ideal + target.width.ideal) / 2),
max: target.width.max
},
height: {
ideal: Math.round((current.height.ideal + target.height.ideal) / 2),
max: target.height.max
},
frameRate: {
ideal: Math.round((current.frameRate.ideal + target.frameRate.ideal) / 2),
max: target.frameRate.max
}
};
return transition;
}
// 품질 변경 알림
function showQualityChangeNotification(quality) {
const qualityLabels = {
'high': '🟢 고화질',
'medium': '🟡 중화질',
'low': '🔴 저화질',
'auto': '🔄 자동'
};
// 임시 알림 표시
const notification = document.createElement('div');
notification.style.cssText = `
position: fixed;
top: 50px;
right: 10px;
background: rgba(0,0,0,0.8);
color: white;
padding: 8px 12px;
border-radius: 6px;
font-size: 12px;
z-index: 10000;
opacity: 0;
transition: opacity 0.3s ease;
`;
notification.textContent = `화질 조정: ${qualityLabels[quality]}`;
document.body.appendChild(notification);
// 페이드 인
setTimeout(() => {
notification.style.opacity = '1';
}, 100);
// 3초 후 자동 제거
setTimeout(() => {
notification.style.opacity = '0';
setTimeout(() => {
if (notification.parentNode) {
notification.parentNode.removeChild(notification);
}
}, 300);
}, 3000);
}
// 강화된 화면 공유 통계 업데이트
async function updateScreenShareStats() {
if (!shareView) return;
try {
const participant = participants[userId];
if (!participant || !participant.rtcPeer) return;
const stats = await participant.rtcPeer.peerConnection.getStats();
let outboundRtp = null;
let inboundRtp = null;
stats.forEach(report => {
if (report.type === 'outbound-rtp' && report.kind === 'video') {
outboundRtp = report;
} else if (report.type === 'inbound-rtp' && report.kind === 'video') {
inboundRtp = report;
}
});
if (outboundRtp) {
const now = Date.now();
const timeDiff = (now - screenShareConfig.stats.timestamp) / 1000;
if (timeDiff > 0) {
// 기본 통계
const bytesDiff = outboundRtp.bytesSent - (screenShareConfig.stats.bytesLastSent || 0);
screenShareConfig.stats.bitrate = (bytesDiff * 8) / (timeDiff * 1000); // kbps
screenShareConfig.stats.frameRate = outboundRtp.framesPerSecond || 0;
screenShareConfig.stats.packetsLost = outboundRtp.packetsLost || 0;
screenShareConfig.stats.bytesLastSent = outboundRtp.bytesSent;
screenShareConfig.stats.timestamp = now;
// 확장 통계
screenShareConfig.stats.framesEncoded = outboundRtp.framesEncoded || 0;
screenShareConfig.stats.framesSent = outboundRtp.framesSent || 0;
screenShareConfig.stats.encodeTime = outboundRtp.totalEncodeTime || 0;
screenShareConfig.stats.qualityLimitationReason = outboundRtp.qualityLimitationReason || 'none';
// 화질 제한 원인 분석
analyzeQualityLimitation(outboundRtp.qualityLimitationReason);
// 성능 경고 확인
checkPerformanceWarnings();
// UI 업데이트
updateStatsDisplay();
}
}
} catch (error) {
console.warn('화면 공유 통계 업데이트 실패:', error);
}
}
// 화질 제한 원인 분석
function analyzeQualityLimitation(reason) {
const limitationReasons = {
'none': '제한 없음',
'cpu': 'CPU 성능 제한',
'bandwidth': '대역폭 제한',
'other': '기타 제한'
};
if (reason && reason !== 'none') {
console.warn(`화질 제한 감지: ${limitationReasons[reason] || reason}`);
// 제한 원인별 자동 대응
if (reason === 'cpu') {
// CPU 제한 시 프레임률 우선 감소
suggestCpuOptimization();
} else if (reason === 'bandwidth') {
// 대역폭 제한 시 해상도 우선 감소
suggestBandwidthOptimization();
}
}
}
// CPU 최적화 제안
function suggestCpuOptimization() {
if (screenShareConfig.currentQuality !== 'low') {
console.log('CPU 부하로 인한 자동 최적화 제안: 프레임률 감소');
// 필요시 자동으로 낮은 품질로 전환
if (screenShareConfig.autoOptimize) {
const currentPreset = screenShareConfig.qualityPresets[screenShareConfig.currentQuality];
const optimizedPreset = {
...currentPreset,