├── 01_mediastream ├── public │ └── mediastream │ │ ├── css │ │ └── client.css │ │ ├── index.html │ │ └── js │ │ └── client.js └── server.js ├── 02_device └── webserver │ ├── public │ └── device │ │ ├── index.html │ │ └── js │ │ └── client.js │ └── server.js ├── 03_takephoto ├── public │ └── takephoto │ │ ├── css │ │ └── client.css │ │ ├── index.html │ │ └── js │ │ └── client.js └── server.js ├── 04_recorder └── recorder │ ├── css │ └── client.css │ ├── index.html │ └── js │ └── client.js ├── 05_desktop └── recorder │ ├── css │ └── client.css │ ├── index.html │ └── js │ └── client.js ├── 11_signal ├── css │ └── main.css ├── index.html ├── js │ └── client.js └── server.js ├── 12_peerconnection └── peerconnection │ ├── css │ └── main.css │ ├── index.html │ └── js │ └── client.js ├── 16_getstat └── getstats │ ├── css │ └── main.css │ ├── index.html │ └── js │ ├── client.js │ └── third_party │ └── graph.js ├── 19_chat └── chat_new │ ├── css │ └── main.css │ ├── index.html │ ├── js │ ├── main_bw.js │ └── third_party │ │ └── graph.js │ └── server.js ├── 23_living ├── css │ └── main.css ├── index.html ├── js │ ├── .main.js.swo │ ├── .main.js.swp │ ├── .main_base.js.swp │ └── main.js ├── room.html └── server.js ├── LICENSE └── README.md /01_mediastream/public/mediastream/css/client.css: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2015 The WebRTC project authors. All Rights Reserved. 3 | * 4 | * Use of this source code is governed by a BSD-style license 5 | * that can be found in the LICENSE file in the root of the source 6 | * tree. 7 | */ 8 | button { 9 | margin: 0 20px 25px 0; 10 | vertical-align: top; 11 | width: 134px; 12 | } 13 | 14 | div#getUserMedia { 15 | padding: 0 0 8px 0; 16 | } 17 | 18 | div.input { 19 | display: inline-block; 20 | margin: 0 4px 0 0; 21 | vertical-align: top; 22 | width: 310px; 23 | } 24 | 25 | div.input > div { 26 | margin: 0 0 20px 0; 27 | vertical-align: top; 28 | } 29 | 30 | div.output { 31 | background-color: #eee; 32 | display: inline-block; 33 | font-family: 'Inconsolata', 'Courier New', monospace; 34 | font-size: 0.9em; 35 | padding: 10px 10px 10px 25px; 36 | position: relative; 37 | top: 10px; 38 | white-space: pre; 39 | width: 270px; 40 | } 41 | 42 | section#statistics div { 43 | display: inline-block; 44 | font-family: 'Inconsolata', 'Courier New', monospace; 45 | vertical-align: top; 46 | width: 308px; 47 | } 48 | 49 | section#statistics div#senderStats { 50 | margin: 0 20px 0 0; 51 | } 52 | 53 | section#constraints > div { 54 | margin: 0 0 20px 0; 55 | } 56 | 57 | section#video > div { 58 | display: inline-block; 59 | margin: 0 20px 0 0; 60 | vertical-align: top; 61 | width: calc(50% - 22px); 62 | } 63 | 64 | section#video > div div { 65 | font-size: 0.9em; 66 | margin: 0 0 0.5em 0; 67 | width: 320px; 68 | } 69 | 70 | h2 { 71 | margin: 0 0 1em 0; 72 | } 73 | 74 | section#constraints label { 75 | display: inline-block; 76 | width: 156px; 77 | } 78 | 79 | section { 80 | margin: 0 0 20px 0; 81 | padding: 0 0 15px 0; 82 | } 83 | 84 | section#video { 85 | width: calc(100% + 20px); 86 | } 87 | 88 | video { 89 | --width: 90%; 90 | display: inline-block; 91 | width: var(--width); 92 | height: calc(var(--width) * 0.75); 93 | margin: 0 0 10px 0; 94 | } 95 | 96 | @media screen and (max-width: 720px) { 97 | button { 98 | font-weight: 500; 99 | height: 56px; 100 | line-height: 1.3em; 101 | width: 90px; 102 | } 103 | 104 | div#getUserMedia { 105 | padding: 0 0 40px 0; 106 | } 107 | 108 | section#statistics div { 109 | width: calc(50% - 14px); 110 | } 111 | 112 | video { 113 | display: inline-block; 114 | width: var(--width); 115 | height: 96px; 116 | } 117 | } 118 | -------------------------------------------------------------------------------- /01_mediastream/public/mediastream/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | WebRTC capture video and audio 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | -------------------------------------------------------------------------------- /01_mediastream/public/mediastream/js/client.js: -------------------------------------------------------------------------------- 1 | 'use strict' 2 | 3 | var videoplay = document.querySelector('video#player'); 4 | 5 | function gotMediaStream(stream){ 6 | 7 | var videoTrack = stream.getVideoTracks()[0]; 8 | 9 | window.stream = stream; 10 | videoplay.srcObject = stream; 11 | } 12 | 13 | function handleError(err){ 14 | console.log('getUserMedia error:', err); 15 | } 16 | 17 | function start() { 18 | 19 | if(!navigator.mediaDevices || 20 | !navigator.mediaDevices.getUserMedia){ 21 | 22 | console.log('getUserMedia is not supported!'); 23 | return; 24 | 25 | }else{ 26 | 27 | var constraints = { 28 | video : { 29 | width: 640, 30 | height: 480, 31 | frameRate:15, 32 | facingMode: 'enviroment' 33 | //, 34 | //deviceId : deviceId ? {exact:deviceId} : undefined 35 | }, 36 | audio : false 37 | } 38 | 39 | navigator.mediaDevices.getUserMedia(constraints) 40 | .then(gotMediaStream) 41 | .catch(handleError); 42 | } 43 | } 44 | 45 | start(); 46 | -------------------------------------------------------------------------------- /01_mediastream/server.js: -------------------------------------------------------------------------------- 1 | 'use strict' 2 | 3 | var http = require('http'); 4 | var https = require('https'); 5 | var fs = require('fs'); 6 | 7 | var serveIndex = require('serve-index'); 8 | 9 | var express = require('express'); 10 | var app = express(); 11 | 12 | //顺序不能换 13 | app.use(serveIndex('./public')); 14 | app.use(express.static('./public')); 15 | 16 | var options = { 17 | key : fs.readFileSync('./cert/1557605_www.learningrtc.cn.key'), 18 | cert : fs.readFileSync('./cert/1557605_www.learningrtc.cn.pem') 19 | } 20 | 21 | var https_server = https.createServer(options, app); 22 | https_server.listen(443, '0.0.0.0'); 23 | 24 | var http_server = http.createServer(app); 25 | http_server.listen(80, '0.0.0.0'); 26 | 27 | 28 | -------------------------------------------------------------------------------- /02_device/webserver/public/device/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | WebRTC get audio and video devices 4 | 5 | 6 |
7 | 8 | 9 |
10 |
11 | 12 | 13 |
14 |
15 | 16 | 17 |
18 | 19 | 20 | 21 | 22 | 23 | -------------------------------------------------------------------------------- /02_device/webserver/public/device/js/client.js: -------------------------------------------------------------------------------- 1 | 'use strict' 2 | var audioSource = document.querySelector("select#audioSource"); 3 | var audioOutput = document.querySelector("select#audioOutput"); 4 | var videoSource = document.querySelector("select#videoSource"); 5 | 6 | if(!navigator.mediaDevices || 7 | !navigator.mediaDevices.enumerateDevices){ 8 | console.log('enumerateDevices is not supported!'); 9 | }else { 10 | navigator.mediaDevices.enumerateDevices() 11 | .then(gotDevices) 12 | .catch(handleError); 13 | } 14 | 15 | function gotDevices(deviceInfos){ 16 | deviceInfos.forEach( function(deviceInfo){ 17 | console.log(deviceInfo.kind + ": label = " 18 | + deviceInfo.label + ": id = " 19 | + deviceInfo.deviceId + ": groupId = " 20 | + deviceInfo.groupId); 21 | var option = document.createElement('option'); 22 | option.text = deviceInfo.label; 23 | option.value = deviceInfo.deviceId; 24 | if(deviceInfo.kind === 'audioinput'){ 25 | audioSource.appendChild(option); 26 | }else if(deviceInfo.kind === 'audiooutput'){ 27 | audioOutput.appendChild(option); 28 | }else if(deviceInfo.kind === 'videoinput'){ 29 | videoSource.appendChild(option); 30 | } 31 | }); 32 | 33 | } 34 | 35 | function handleError(err){ 36 | console.log(err.name + " : " + err.message); 37 | } 38 | -------------------------------------------------------------------------------- /02_device/webserver/server.js: -------------------------------------------------------------------------------- 1 | 'use strict' 2 | 3 | var http = require('http'); 4 | var https = require('https'); 5 | var fs = require('fs'); 6 | 7 | var serveIndex = require('serve-index'); 8 | 9 | var express = require('express'); 10 | var app = express(); 11 | 12 | //顺序不能换 13 | app.use(serveIndex('./public')); 14 | app.use(express.static('./public')); 15 | 16 | var options = { 17 | key : fs.readFileSync('./cert/1557605_www.learningrtc.cn.key'), 18 | cert : fs.readFileSync('./cert/1557605_www.learningrtc.cn.pem') 19 | } 20 | 21 | var https_server = https.createServer(options, app); 22 | https_server.listen(443, '0.0.0.0'); 23 | 24 | var http_server = http.createServer(app); 25 | http_server.listen(80, '0.0.0.0'); 26 | 27 | 28 | -------------------------------------------------------------------------------- /03_takephoto/public/takephoto/css/client.css: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2015 The WebRTC project authors. All Rights Reserved. 3 | * 4 | * Use of this source code is governed by a BSD-style license 5 | * that can be found in the LICENSE file in the root of the source 6 | * tree. 7 | */ 8 | button { 9 | margin: 0 20px 25px 0; 10 | vertical-align: top; 11 | width: 134px; 12 | } 13 | 14 | div#getUserMedia { 15 | padding: 0 0 8px 0; 16 | } 17 | 18 | div.input { 19 | display: inline-block; 20 | margin: 0 4px 0 0; 21 | vertical-align: top; 22 | width: 310px; 23 | } 24 | 25 | div.input > div { 26 | margin: 0 0 20px 0; 27 | vertical-align: top; 28 | } 29 | 30 | div.output { 31 | background-color: #eee; 32 | display: inline-block; 33 | font-family: 'Inconsolata', 'Courier New', monospace; 34 | font-size: 0.9em; 35 | padding: 10px 10px 10px 25px; 36 | position: relative; 37 | top: 10px; 38 | white-space: pre; 39 | width: 270px; 40 | } 41 | 42 | section#statistics div { 43 | display: inline-block; 44 | font-family: 'Inconsolata', 'Courier New', monospace; 45 | vertical-align: top; 46 | width: 308px; 47 | } 48 | 49 | section#statistics div#senderStats { 50 | margin: 0 20px 0 0; 51 | } 52 | 53 | section#constraints > div { 54 | margin: 0 0 20px 0; 55 | } 56 | 57 | section#video > div { 58 | display: inline-block; 59 | margin: 0 20px 0 0; 60 | vertical-align: top; 61 | width: calc(50% - 22px); 62 | } 63 | 64 | section#video > div div { 65 | font-size: 0.9em; 66 | margin: 0 0 0.5em 0; 67 | width: 320px; 68 | } 69 | 70 | h2 { 71 | margin: 0 0 1em 0; 72 | } 73 | 74 | section#constraints label { 75 | display: inline-block; 76 | width: 156px; 77 | } 78 | 79 | section { 80 | margin: 0 0 20px 0; 81 | padding: 0 0 15px 0; 82 | } 83 | 84 | section#video { 85 | width: calc(100% + 20px); 86 | } 87 | 88 | video { 89 | --width: 90%; 90 | display: inline-block; 91 | width: var(--width); 92 | height: calc(var(--width) * 0.75); 93 | margin: 0 0 10px 0; 94 | } 95 | 96 | @media screen and (max-width: 720px) { 97 | button { 98 | font-weight: 500; 99 | height: 56px; 100 | line-height: 1.3em; 101 | width: 90px; 102 | } 103 | 104 | div#getUserMedia { 105 | padding: 0 0 40px 0; 106 | } 107 | 108 | section#statistics div { 109 | width: calc(50% - 14px); 110 | } 111 | 112 | video { 113 | display: inline-block; 114 | width: var(--width); 115 | height: 96px; 116 | } 117 | } 118 | -------------------------------------------------------------------------------- /03_takephoto/public/takephoto/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | WebRTC capture video and audio 4 | 5 | 6 | 7 | 29 | 30 | 31 | 32 |
33 |
34 | 35 | 42 |
43 | 44 |
45 | 46 |
47 | 48 |
49 |
50 |
51 | 52 |
53 |
54 | 55 |
56 |
57 | 58 | 59 | 60 | 61 | 62 | 63 | -------------------------------------------------------------------------------- /03_takephoto/public/takephoto/js/client.js: -------------------------------------------------------------------------------- 1 | 'use strict' 2 | 3 | //filter 4 | var filtersSelect = document.querySelector('select#filter'); 5 | 6 | //picture 7 | var snapshot = document.querySelector('button#snapshot'); 8 | var picture = document.querySelector('canvas#picture'); 9 | picture.width = 640; 10 | picture.height = 480; 11 | 12 | var videoplay = document.querySelector('video#player'); 13 | 14 | function gotMediaStream(stream){ 15 | var videoTrack = stream.getVideoTracks()[0]; 16 | 17 | window.stream = stream; 18 | videoplay.srcObject = stream; 19 | } 20 | 21 | function handleError(err){ 22 | console.log('getUserMedia error:', err); 23 | } 24 | 25 | function start() { 26 | 27 | if(!navigator.mediaDevices || 28 | !navigator.mediaDevices.getUserMedia){ 29 | 30 | console.log('getUserMedia is not supported!'); 31 | return; 32 | 33 | }else{ 34 | 35 | //var deviceId = videoSource.value; 36 | var constraints = { 37 | video : { 38 | width: 640, 39 | height: 480, 40 | frameRate:15, 41 | facingMode: 'enviroment' 42 | //, 43 | //deviceId : deviceId ? {exact:deviceId} : undefined 44 | }, 45 | audio : false 46 | } 47 | 48 | navigator.mediaDevices.getUserMedia(constraints) 49 | .then(gotMediaStream) 50 | .catch(handleError); 51 | } 52 | } 53 | 54 | filtersSelect.onchange = function(){ 55 | videoplay.className = filtersSelect.value; 56 | } 57 | 58 | snapshot.onclick = function() { 59 | picture.className = filtersSelect.value; 60 | picture.getContext('2d').drawImage(videoplay, 0, 0, picture.width, picture.height); 61 | } 62 | 63 | 64 | start(); 65 | -------------------------------------------------------------------------------- /03_takephoto/server.js: -------------------------------------------------------------------------------- 1 | 'use strict' 2 | 3 | var http = require('http'); 4 | var https = require('https'); 5 | var fs = require('fs'); 6 | 7 | var serveIndex = require('serve-index'); 8 | 9 | var express = require('express'); 10 | var app = express(); 11 | 12 | //顺序不能换 13 | app.use(serveIndex('./public')); 14 | app.use(express.static('./public')); 15 | 16 | var options = { 17 | key : fs.readFileSync('./cert/1557605_www.learningrtc.cn.key'), 18 | cert : fs.readFileSync('./cert/1557605_www.learningrtc.cn.pem') 19 | } 20 | 21 | var https_server = https.createServer(options, app); 22 | https_server.listen(443, '0.0.0.0'); 23 | 24 | var http_server = http.createServer(app); 25 | http_server.listen(80, '0.0.0.0'); 26 | 27 | 28 | -------------------------------------------------------------------------------- /04_recorder/recorder/css/client.css: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2015 The WebRTC project authors. All Rights Reserved. 3 | * 4 | * Use of this source code is governed by a BSD-style license 5 | * that can be found in the LICENSE file in the root of the source 6 | * tree. 7 | */ 8 | button { 9 | margin: 0 20px 25px 0; 10 | vertical-align: top; 11 | width: 134px; 12 | } 13 | 14 | div#getUserMedia { 15 | padding: 0 0 8px 0; 16 | } 17 | 18 | div.input { 19 | display: inline-block; 20 | margin: 0 4px 0 0; 21 | vertical-align: top; 22 | width: 310px; 23 | } 24 | 25 | div.input > div { 26 | margin: 0 0 20px 0; 27 | vertical-align: top; 28 | } 29 | 30 | div.output { 31 | background-color: #eee; 32 | display: inline-block; 33 | font-family: 'Inconsolata', 'Courier New', monospace; 34 | font-size: 0.9em; 35 | padding: 10px 10px 10px 25px; 36 | position: relative; 37 | top: 10px; 38 | white-space: pre; 39 | width: 270px; 40 | } 41 | 42 | section#statistics div { 43 | display: inline-block; 44 | font-family: 'Inconsolata', 'Courier New', monospace; 45 | vertical-align: top; 46 | width: 308px; 47 | } 48 | 49 | section#statistics div#senderStats { 50 | margin: 0 20px 0 0; 51 | } 52 | 53 | section#constraints > div { 54 | margin: 0 0 20px 0; 55 | } 56 | 57 | section#video > div { 58 | display: inline-block; 59 | margin: 0 20px 0 0; 60 | vertical-align: top; 61 | width: calc(50% - 22px); 62 | } 63 | 64 | section#video > div div { 65 | font-size: 0.9em; 66 | margin: 0 0 0.5em 0; 67 | width: 320px; 68 | } 69 | 70 | h2 { 71 | margin: 0 0 1em 0; 72 | } 73 | 74 | section#constraints label { 75 | display: inline-block; 76 | width: 156px; 77 | } 78 | 79 | section { 80 | margin: 0 0 20px 0; 81 | padding: 0 0 15px 0; 82 | } 83 | 84 | section#video { 85 | width: calc(100% + 20px); 86 | } 87 | 88 | video { 89 | --width: 90%; 90 | display: inline-block; 91 | width: var(--width); 92 | height: calc(var(--width) * 0.75); 93 | margin: 0 0 10px 0; 94 | } 95 | 96 | @media screen and (max-width: 720px) { 97 | button { 98 | font-weight: 500; 99 | height: 56px; 100 | line-height: 1.3em; 101 | width: 90px; 102 | } 103 | 104 | div#getUserMedia { 105 | padding: 0 0 40px 0; 106 | } 107 | 108 | section#statistics div { 109 | width: calc(50% - 14px); 110 | } 111 | 112 | video { 113 | display: inline-block; 114 | width: var(--width); 115 | height: 96px; 116 | } 117 | } 118 | -------------------------------------------------------------------------------- /04_recorder/recorder/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | WebRTC capture video and audio 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 | -------------------------------------------------------------------------------- /04_recorder/recorder/js/client.js: -------------------------------------------------------------------------------- 1 | 'use strict' 2 | 3 | var videoplay = document.querySelector('video#player'); 4 | //var audioplay = document.querySelector('audio#audioplayer'); 5 | 6 | //record 7 | var recvideo = document.querySelector('video#recplayer'); 8 | var btnRecord = document.querySelector('button#record'); 9 | var btnPlay = document.querySelector('button#recplay'); 10 | var btnDownload = document.querySelector('button#download'); 11 | 12 | var buffer; 13 | var mediaRecorder; 14 | 15 | 16 | function gotMediaStream(stream){ 17 | 18 | window.stream = stream; 19 | videoplay.srcObject = stream; 20 | 21 | } 22 | 23 | function handleError(err){ 24 | console.log('getUserMedia error:', err); 25 | } 26 | 27 | function start() { 28 | 29 | if(!navigator.mediaDevices || 30 | !navigator.mediaDevices.getUserMedia){ 31 | 32 | console.log('getUserMedia is not supported!'); 33 | return; 34 | 35 | }else{ 36 | 37 | var constraints = { 38 | video : { 39 | width: 640, 40 | height: 480, 41 | frameRate:15 42 | }, 43 | audio : false 44 | } 45 | 46 | navigator.mediaDevices.getUserMedia(constraints) 47 | .then(gotMediaStream) 48 | .catch(handleError); 49 | } 50 | } 51 | 52 | start(); 53 | 54 | function handleDataAvailable(e){ 55 | if(e && e.data && e.data.size > 0){ 56 | buffer.push(e.data); 57 | } 58 | } 59 | 60 | function startRecord(){ 61 | 62 | buffer = []; 63 | 64 | var options = { 65 | mimeType: 'video/webm;codecs=vp8' 66 | } 67 | 68 | if(!MediaRecorder.isTypeSupported(options.mimeType)){ 69 | console.error(`${options.mimeType} is not supported!`); 70 | return; 71 | } 72 | 73 | try{ 74 | mediaRecorder = new MediaRecorder(window.stream, options); 75 | }catch(e){ 76 | console.error('Failed to create MediaRecorder:', e); 77 | return; 78 | } 79 | 80 | mediaRecorder.ondataavailable = handleDataAvailable; 81 | mediaRecorder.start(10); 82 | 83 | } 84 | 85 | function stopRecord(){ 86 | mediaRecorder.stop(); 87 | } 88 | 89 | btnRecord.onclick = ()=>{ 90 | 91 | if(btnRecord.textContent === 'Start Record'){ 92 | startRecord(); 93 | btnRecord.textContent = 'Stop Record'; 94 | btnPlay.disabled = true; 95 | btnDownload.disabled = true; 96 | }else{ 97 | 98 | stopRecord(); 99 | btnRecord.textContent = 'Start Record'; 100 | btnPlay.disabled = false; 101 | btnDownload.disabled = false; 102 | 103 | } 104 | } 105 | 106 | btnPlay.onclick = ()=> { 107 | var blob = new Blob(buffer, {type: 'video/webm'}); 108 | recvideo.src = window.URL.createObjectURL(blob); 109 | recvideo.srcObject = null; 110 | recvideo.controls = true; 111 | recvideo.play(); 112 | } 113 | 114 | btnDownload.onclick = ()=> { 115 | var blob = new Blob(buffer, {type: 'video/webm'}); 116 | var url = window.URL.createObjectURL(blob); 117 | var a = document.createElement('a'); 118 | 119 | a.href = url; 120 | a.style.display = 'none'; 121 | a.download = 'aaa.webm'; 122 | a.click(); 123 | } 124 | 125 | -------------------------------------------------------------------------------- /05_desktop/recorder/css/client.css: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2015 The WebRTC project authors. All Rights Reserved. 3 | * 4 | * Use of this source code is governed by a BSD-style license 5 | * that can be found in the LICENSE file in the root of the source 6 | * tree. 7 | */ 8 | button { 9 | margin: 0 20px 25px 0; 10 | vertical-align: top; 11 | width: 134px; 12 | } 13 | 14 | div#getUserMedia { 15 | padding: 0 0 8px 0; 16 | } 17 | 18 | div.input { 19 | display: inline-block; 20 | margin: 0 4px 0 0; 21 | vertical-align: top; 22 | width: 310px; 23 | } 24 | 25 | div.input > div { 26 | margin: 0 0 20px 0; 27 | vertical-align: top; 28 | } 29 | 30 | div.output { 31 | background-color: #eee; 32 | display: inline-block; 33 | font-family: 'Inconsolata', 'Courier New', monospace; 34 | font-size: 0.9em; 35 | padding: 10px 10px 10px 25px; 36 | position: relative; 37 | top: 10px; 38 | white-space: pre; 39 | width: 270px; 40 | } 41 | 42 | section#statistics div { 43 | display: inline-block; 44 | font-family: 'Inconsolata', 'Courier New', monospace; 45 | vertical-align: top; 46 | width: 308px; 47 | } 48 | 49 | section#statistics div#senderStats { 50 | margin: 0 20px 0 0; 51 | } 52 | 53 | section#constraints > div { 54 | margin: 0 0 20px 0; 55 | } 56 | 57 | section#video > div { 58 | display: inline-block; 59 | margin: 0 20px 0 0; 60 | vertical-align: top; 61 | width: calc(50% - 22px); 62 | } 63 | 64 | section#video > div div { 65 | font-size: 0.9em; 66 | margin: 0 0 0.5em 0; 67 | width: 320px; 68 | } 69 | 70 | h2 { 71 | margin: 0 0 1em 0; 72 | } 73 | 74 | section#constraints label { 75 | display: inline-block; 76 | width: 156px; 77 | } 78 | 79 | section { 80 | margin: 0 0 20px 0; 81 | padding: 0 0 15px 0; 82 | } 83 | 84 | section#video { 85 | width: calc(100% + 20px); 86 | } 87 | 88 | video { 89 | --width: 90%; 90 | display: inline-block; 91 | width: var(--width); 92 | height: calc(var(--width) * 0.75); 93 | margin: 0 0 10px 0; 94 | } 95 | 96 | @media screen and (max-width: 720px) { 97 | button { 98 | font-weight: 500; 99 | height: 56px; 100 | line-height: 1.3em; 101 | width: 90px; 102 | } 103 | 104 | div#getUserMedia { 105 | padding: 0 0 40px 0; 106 | } 107 | 108 | section#statistics div { 109 | width: calc(50% - 14px); 110 | } 111 | 112 | video { 113 | display: inline-block; 114 | width: var(--width); 115 | height: 96px; 116 | } 117 | } 118 | -------------------------------------------------------------------------------- /05_desktop/recorder/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | WebRTC capture video and audio 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 | -------------------------------------------------------------------------------- /05_desktop/recorder/js/client.js: -------------------------------------------------------------------------------- 1 | 'use strict' 2 | 3 | var videoplay = document.querySelector('video#player'); 4 | //var audioplay = document.querySelector('audio#audioplayer'); 5 | 6 | //record 7 | var recvideo = document.querySelector('video#recplayer'); 8 | var btnRecord = document.querySelector('button#record'); 9 | var btnPlay = document.querySelector('button#recplay'); 10 | var btnDownload = document.querySelector('button#download'); 11 | 12 | var buffer; 13 | var mediaRecorder; 14 | 15 | 16 | function gotMediaStream(stream){ 17 | 18 | window.stream = stream; 19 | videoplay.srcObject = stream; 20 | 21 | } 22 | 23 | function handleError(err){ 24 | console.log('getUserMedia error:', err); 25 | } 26 | 27 | function start() { 28 | 29 | if(!navigator.mediaDevices || 30 | !navigator.mediaDevices.getDisplayMedia){ 31 | 32 | console.log('getDisplayMedia is not supported!'); 33 | return; 34 | 35 | }else{ 36 | 37 | var constraints = { 38 | video : { 39 | width: 640, 40 | height: 480, 41 | frameRate:15 42 | }, 43 | audio : false 44 | } 45 | 46 | navigator.mediaDevices.getDisplayMedia(constraints) 47 | .then(gotMediaStream) 48 | .catch(handleError); 49 | } 50 | } 51 | 52 | start(); 53 | 54 | function handleDataAvailable(e){ 55 | if(e && e.data && e.data.size > 0){ 56 | buffer.push(e.data); 57 | } 58 | } 59 | 60 | function startRecord(){ 61 | 62 | buffer = []; 63 | 64 | var options = { 65 | mimeType: 'video/webm;codecs=vp8' 66 | } 67 | 68 | if(!MediaRecorder.isTypeSupported(options.mimeType)){ 69 | console.error(`${options.mimeType} is not supported!`); 70 | return; 71 | } 72 | 73 | try{ 74 | mediaRecorder = new MediaRecorder(window.stream, options); 75 | }catch(e){ 76 | console.error('Failed to create MediaRecorder:', e); 77 | return; 78 | } 79 | 80 | mediaRecorder.ondataavailable = handleDataAvailable; 81 | mediaRecorder.start(10); 82 | 83 | } 84 | 85 | function stopRecord(){ 86 | mediaRecorder.stop(); 87 | } 88 | 89 | btnRecord.onclick = ()=>{ 90 | 91 | if(btnRecord.textContent === 'Start Record'){ 92 | startRecord(); 93 | btnRecord.textContent = 'Stop Record'; 94 | btnPlay.disabled = true; 95 | btnDownload.disabled = true; 96 | }else{ 97 | 98 | stopRecord(); 99 | btnRecord.textContent = 'Start Record'; 100 | btnPlay.disabled = false; 101 | btnDownload.disabled = false; 102 | 103 | } 104 | } 105 | 106 | btnPlay.onclick = ()=> { 107 | var blob = new Blob(buffer, {type: 'video/webm'}); 108 | recvideo.src = window.URL.createObjectURL(blob); 109 | recvideo.srcObject = null; 110 | recvideo.controls = true; 111 | recvideo.play(); 112 | } 113 | 114 | btnDownload.onclick = ()=> { 115 | var blob = new Blob(buffer, {type: 'video/webm'}); 116 | var url = window.URL.createObjectURL(blob); 117 | var a = document.createElement('a'); 118 | 119 | a.href = url; 120 | a.style.display = 'none'; 121 | a.download = 'aaa.webm'; 122 | a.click(); 123 | } 124 | 125 | -------------------------------------------------------------------------------- /11_signal/css/main.css: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2015 The WebRTC project authors. All Rights Reserved. 3 | * 4 | * Use of this source code is governed by a BSD-style license 5 | * that can be found in the LICENSE file in the root of the source 6 | * tree. 7 | */ 8 | button { 9 | margin: 0 20px 25px 0; 10 | vertical-align: top; 11 | width: 134px; 12 | } 13 | 14 | div#getUserMedia { 15 | padding: 0 0 8px 0; 16 | } 17 | 18 | div.input { 19 | display: inline-block; 20 | margin: 0 4px 0 0; 21 | vertical-align: top; 22 | width: 310px; 23 | } 24 | 25 | div.input > div { 26 | margin: 0 0 20px 0; 27 | vertical-align: top; 28 | } 29 | 30 | div.output { 31 | background-color: #eee; 32 | display: inline-block; 33 | font-family: 'Inconsolata', 'Courier New', monospace; 34 | font-size: 0.9em; 35 | padding: 10px 10px 10px 25px; 36 | position: relative; 37 | top: 10px; 38 | white-space: pre; 39 | width: 270px; 40 | } 41 | 42 | section#statistics div { 43 | display: inline-block; 44 | font-family: 'Inconsolata', 'Courier New', monospace; 45 | vertical-align: top; 46 | width: 308px; 47 | } 48 | 49 | section#statistics div#senderStats { 50 | margin: 0 20px 0 0; 51 | } 52 | 53 | section#constraints > div { 54 | margin: 0 0 20px 0; 55 | } 56 | 57 | section#video > div { 58 | display: inline-block; 59 | margin: 0 20px 0 0; 60 | vertical-align: top; 61 | width: calc(50% - 22px); 62 | } 63 | 64 | section#video > div div { 65 | font-size: 0.9em; 66 | margin: 0 0 0.5em 0; 67 | width: 320px; 68 | } 69 | 70 | h2 { 71 | margin: 0 0 1em 0; 72 | } 73 | 74 | section#constraints label { 75 | display: inline-block; 76 | width: 156px; 77 | } 78 | 79 | section { 80 | margin: 0 0 20px 0; 81 | padding: 0 0 15px 0; 82 | } 83 | 84 | section#video { 85 | width: calc(100% + 20px); 86 | } 87 | 88 | video { 89 | --width: 90%; 90 | display: inline-block; 91 | width: var(--width); 92 | height: calc(var(--width) * 0.75); 93 | margin: 0 0 10px 0; 94 | } 95 | 96 | @media screen and (max-width: 720px) { 97 | button { 98 | font-weight: 500; 99 | height: 56px; 100 | line-height: 1.3em; 101 | width: 90px; 102 | } 103 | 104 | div#getUserMedia { 105 | padding: 0 0 40px 0; 106 | } 107 | 108 | section#statistics div { 109 | width: calc(50% - 14px); 110 | } 111 | 112 | video { 113 | display: inline-block; 114 | width: var(--width); 115 | height: 96px; 116 | } 117 | } 118 | -------------------------------------------------------------------------------- /11_signal/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | Chat Room 4 | 5 | 6 | 7 | 8 | 9 | 13 | 14 | 15 | 21 | 22 | 23 | 27 | 28 | 29 | 33 | 34 | 35 | 38 | 39 |
10 | 11 | 12 |
16 | 17 | 18 | 19 | 20 |
24 |
25 | 26 |
30 |
31 | 32 |
36 | 37 |
40 | 41 | 42 | 43 | 44 | 45 | 46 | -------------------------------------------------------------------------------- /11_signal/js/client.js: -------------------------------------------------------------------------------- 1 | 'use strict' 2 | 3 | // 4 | var userName = document.querySelector('input#username'); 5 | var inputRoom = document.querySelector('input#room'); 6 | var btnConnect = document.querySelector('button#connect'); 7 | var btnLeave = document.querySelector('button#leave'); 8 | var outputArea = document.querySelector('textarea#output'); 9 | var inputArea = document.querySelector('textarea#input'); 10 | var btnSend = document.querySelector('button#send'); 11 | 12 | var socket; 13 | var room; 14 | 15 | btnConnect.onclick = ()=>{ 16 | 17 | //connect 18 | socket = io.connect(); 19 | 20 | //recieve message 21 | socket.on('joined', (room, id) => { 22 | btnConnect.disabled = true; 23 | btnLeave.disabled = false; 24 | inputArea.disabled = false; 25 | btnSend.disabled = false; 26 | }); 27 | 28 | socket.on('leaved', (room, id) => { 29 | btnConnect.disabled = false; 30 | btnLeave.disabled = true; 31 | inputArea.disabled = true; 32 | btnSend.disabled = true; 33 | 34 | socket.disconnect(); 35 | }); 36 | 37 | socket.on('message', (room, data) => { 38 | outputArea.scrollTop = outputArea.scrollHeight;//窗口总是显示最后的内容 39 | outputArea.value = outputArea.value + data + '\r'; 40 | }); 41 | 42 | socket.on('disconnect', (socket)=>{ 43 | btnConnect.disabled = false; 44 | btnLeave.disabled = true; 45 | inputArea.disabled = true; 46 | btnSend.disabled = true; 47 | }); 48 | 49 | //send message 50 | room = inputRoom.value; 51 | socket.emit('join', room); 52 | } 53 | 54 | btnSend.onclick = ()=>{ 55 | var data = inputArea.value; 56 | data = userName.value + ':' + data; 57 | socket.emit('message', room, data); 58 | inputArea.value = ''; 59 | } 60 | 61 | btnLeave.onclick = ()=>{ 62 | room = inputRoom.value; 63 | socket.emit('leave', room); 64 | } 65 | 66 | inputArea.onkeypress = (event)=> { 67 | //event = event || window.event; 68 | if (event.keyCode == 13) { //回车发送消息 69 | var data = inputArea.value; 70 | data = userName.value + ':' + data; 71 | socket.emit('message', room, data); 72 | inputArea.value = ''; 73 | event.preventDefault();//阻止默认行为 74 | } 75 | } 76 | 77 | -------------------------------------------------------------------------------- /11_signal/server.js: -------------------------------------------------------------------------------- 1 | 'use strict' 2 | 3 | var log4js = require('log4js'); 4 | var http = require('http'); 5 | var https = require('https'); 6 | var fs = require('fs'); 7 | var socketIo = require('socket.io'); 8 | 9 | var express = require('express'); 10 | var serveIndex = require('serve-index'); 11 | 12 | var USERCOUNT = 3; 13 | 14 | log4js.configure({ 15 | appenders: { 16 | file: { 17 | type: 'file', 18 | filename: 'app.log', 19 | layout: { 20 | type: 'pattern', 21 | pattern: '%r %p - %m', 22 | } 23 | } 24 | }, 25 | categories: { 26 | default: { 27 | appenders: ['file'], 28 | level: 'debug' 29 | } 30 | } 31 | }); 32 | 33 | var logger = log4js.getLogger(); 34 | 35 | var app = express(); 36 | app.use(serveIndex('./public')); 37 | app.use(express.static('./public')); 38 | 39 | 40 | 41 | //http server 42 | var http_server = http.createServer(app); 43 | http_server.listen(80, '0.0.0.0'); 44 | 45 | var options = { 46 | key : fs.readFileSync('./cert/1557605_www.learningrtc.cn.key'), 47 | cert: fs.readFileSync('./cert/1557605_www.learningrtc.cn.pem') 48 | } 49 | 50 | //https server 51 | var https_server = https.createServer(options, app); 52 | var io = socketIo.listen(https_server); 53 | 54 | io.sockets.on('connection', (socket)=> { 55 | 56 | socket.on('message', (room, data)=>{ 57 | logger.debug('message, room: ' + room + ", data, type:" + data.type); 58 | socket.to(room).emit('message',room, data); 59 | }); 60 | 61 | /* 62 | socket.on('message', (room)=>{ 63 | logger.debug('message, room: ' + room ); 64 | socket.to(room).emit('message',room); 65 | }); 66 | */ 67 | 68 | socket.on('join', (room)=>{ 69 | socket.join(room); 70 | var myRoom = io.sockets.adapter.rooms[room]; 71 | var users = (myRoom)? Object.keys(myRoom.sockets).length : 0; 72 | logger.debug('the user number of room (' + room + ') is: ' + users); 73 | 74 | if(users < USERCOUNT){ 75 | socket.emit('joined', room, socket.id); //发给除自己之外的房间内的所有人 76 | if(users > 1){ 77 | socket.to(room).emit('otherjoin', room, socket.id); 78 | } 79 | 80 | }else{ 81 | socket.leave(room); 82 | socket.emit('full', room, socket.id); 83 | } 84 | //socket.emit('joined', room, socket.id); //发给自己 85 | //socket.broadcast.emit('joined', room, socket.id); //发给除自己之外的这个节点上的所有人 86 | //io.in(room).emit('joined', room, socket.id); //发给房间内的所有人 87 | }); 88 | 89 | socket.on('leave', (room)=>{ 90 | 91 | socket.leave(room); 92 | 93 | var myRoom = io.sockets.adapter.rooms[room]; 94 | var users = (myRoom)? Object.keys(myRoom.sockets).length : 0; 95 | logger.debug('the user number of room is: ' + users); 96 | 97 | //socket.emit('leaved', room, socket.id); 98 | //socket.broadcast.emit('leaved', room, socket.id); 99 | socket.to(room).emit('bye', room, socket.id); 100 | socket.emit('leaved', room, socket.id); 101 | //io.in(room).emit('leaved', room, socket.id); 102 | }); 103 | 104 | }); 105 | 106 | https_server.listen(443, '0.0.0.0'); 107 | 108 | 109 | 110 | 111 | -------------------------------------------------------------------------------- /12_peerconnection/peerconnection/css/main.css: -------------------------------------------------------------------------------- 1 | body { 2 | font-family: sans-serif; 3 | } 4 | 5 | video { 6 | max-width: 100%; 7 | width: 320px; 8 | } 9 | -------------------------------------------------------------------------------- /12_peerconnection/peerconnection/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | Realtime communication with WebRTC 6 | 7 | 8 | 9 | 10 |

Realtime communication with WebRTC

11 | 12 | 13 | 14 | 15 |
16 | 17 | 18 | 19 |
20 | 21 | 22 | 23 | 24 | 25 | -------------------------------------------------------------------------------- /12_peerconnection/peerconnection/js/client.js: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | 3 | //set constraints 4 | const mediaStreamConstraints = { 5 | video: true, 6 | }; 7 | 8 | // Set up to exchange only video. 9 | const offerOptions = { 10 | offerToReceiveVideo: 1, 11 | }; 12 | 13 | // Define peer connections, streams and video elements. 14 | const localVideo = document.getElementById('localVideo'); 15 | const remoteVideo = document.getElementById('remoteVideo'); 16 | 17 | let localStream; 18 | let remoteStream; 19 | 20 | let localPeerConnection; 21 | let remotePeerConnection; 22 | 23 | 24 | // Sets the MediaStream as the video element src. 25 | function gotLocalMediaStream(mediaStream) { 26 | localVideo.srcObject = mediaStream; 27 | localStream = mediaStream; 28 | trace('Received local stream.'); 29 | callButton.disabled = false; // Enable call button. 30 | } 31 | 32 | // Handles error by logging a message to the console. 33 | function handleLocalMediaStreamError(error) { 34 | trace(`navigator.getUserMedia error: ${error.toString()}.`); 35 | } 36 | 37 | // Handles remote MediaStream success by adding it as the remoteVideo src. 38 | function gotRemoteMediaStream(event) { 39 | const mediaStream = event.stream; 40 | remoteVideo.srcObject = mediaStream; 41 | remoteStream = mediaStream; 42 | trace('Remote peer connection received remote stream.'); 43 | } 44 | 45 | // Connects with new peer candidate. 46 | function handleConnection(event) { 47 | const peerConnection = event.target; 48 | const iceCandidate = event.candidate; 49 | 50 | if (iceCandidate) { 51 | const newIceCandidate = new RTCIceCandidate(iceCandidate); 52 | const otherPeer = getOtherPeer(peerConnection); 53 | 54 | otherPeer.addIceCandidate(newIceCandidate) 55 | .then(() => { 56 | handleConnectionSuccess(peerConnection); 57 | }).catch((error) => { 58 | handleConnectionFailure(peerConnection, error); 59 | }); 60 | 61 | trace(`${getPeerName(peerConnection)} ICE candidate:\n` + 62 | `${event.candidate.candidate}.`); 63 | } 64 | } 65 | 66 | // Logs that the connection succeeded. 67 | function handleConnectionSuccess(peerConnection) { 68 | trace(`${getPeerName(peerConnection)} addIceCandidate success.`); 69 | }; 70 | 71 | // Logs that the connection failed. 72 | function handleConnectionFailure(peerConnection, error) { 73 | trace(`${getPeerName(peerConnection)} failed to add ICE Candidate:\n`+ 74 | `${error.toString()}.`); 75 | } 76 | 77 | // Logs changes to the connection state. 78 | function handleConnectionChange(event) { 79 | const peerConnection = event.target; 80 | console.log('ICE state change event: ', event); 81 | trace(`${getPeerName(peerConnection)} ICE state: ` + 82 | `${peerConnection.iceConnectionState}.`); 83 | } 84 | 85 | // Logs error when setting session description fails. 86 | function setSessionDescriptionError(error) { 87 | trace(`Failed to create session description: ${error.toString()}.`); 88 | } 89 | 90 | // Logs success when setting session description. 91 | function setDescriptionSuccess(peerConnection, functionName) { 92 | const peerName = getPeerName(peerConnection); 93 | trace(`${peerName} ${functionName} complete.`); 94 | } 95 | 96 | // Logs success when localDescription is set. 97 | function setLocalDescriptionSuccess(peerConnection) { 98 | setDescriptionSuccess(peerConnection, 'setLocalDescription'); 99 | } 100 | 101 | // Logs success when remoteDescription is set. 102 | function setRemoteDescriptionSuccess(peerConnection) { 103 | setDescriptionSuccess(peerConnection, 'setRemoteDescription'); 104 | } 105 | 106 | // Logs offer creation and sets peer connection session descriptions. 107 | function createdOffer(description) { 108 | trace(`Offer from localPeerConnection:\n${description.sdp}`); 109 | 110 | trace('localPeerConnection setLocalDescription start.'); 111 | localPeerConnection.setLocalDescription(description) 112 | .then(() => { 113 | setLocalDescriptionSuccess(localPeerConnection); 114 | }).catch(setSessionDescriptionError); 115 | 116 | trace('remotePeerConnection setRemoteDescription start.'); 117 | remotePeerConnection.setRemoteDescription(description) 118 | .then(() => { 119 | setRemoteDescriptionSuccess(remotePeerConnection); 120 | }).catch(setSessionDescriptionError); 121 | 122 | trace('remotePeerConnection createAnswer start.'); 123 | remotePeerConnection.createAnswer() 124 | .then(createdAnswer) 125 | .catch(setSessionDescriptionError); 126 | } 127 | 128 | // Logs answer to offer creation and sets peer connection session descriptions. 129 | function createdAnswer(description) { 130 | trace(`Answer from remotePeerConnection:\n${description.sdp}.`); 131 | 132 | trace('remotePeerConnection setLocalDescription start.'); 133 | remotePeerConnection.setLocalDescription(description) 134 | .then(() => { 135 | setLocalDescriptionSuccess(remotePeerConnection); 136 | }).catch(setSessionDescriptionError); 137 | 138 | trace('localPeerConnection setRemoteDescription start.'); 139 | localPeerConnection.setRemoteDescription(description) 140 | .then(() => { 141 | setRemoteDescriptionSuccess(localPeerConnection); 142 | }).catch(setSessionDescriptionError); 143 | } 144 | 145 | 146 | // Define and add behavior to buttons. 147 | 148 | // Define action buttons. 149 | const startButton = document.getElementById('startButton'); 150 | const callButton = document.getElementById('callButton'); 151 | const hangupButton = document.getElementById('hangupButton'); 152 | 153 | // Set up initial action buttons status: disable call and hangup. 154 | callButton.disabled = true; 155 | hangupButton.disabled = true; 156 | 157 | 158 | // Handles start button action: creates local MediaStream. 159 | function startAction() { 160 | startButton.disabled = true; 161 | navigator.mediaDevices.getUserMedia(mediaStreamConstraints) 162 | .then(gotLocalMediaStream).catch(handleLocalMediaStreamError); 163 | trace('Requesting local stream.'); 164 | } 165 | 166 | // Handles call button action: creates peer connection. 167 | function callAction() { 168 | callButton.disabled = true; 169 | hangupButton.disabled = false; 170 | 171 | trace('Starting call.'); 172 | 173 | // Get local media stream tracks. 174 | const videoTracks = localStream.getVideoTracks(); 175 | const audioTracks = localStream.getAudioTracks(); 176 | if (videoTracks.length > 0) { 177 | trace(`Using video device: ${videoTracks[0].label}.`); 178 | } 179 | if (audioTracks.length > 0) { 180 | trace(`Using audio device: ${audioTracks[0].label}.`); 181 | } 182 | 183 | const servers = null; // Allows for RTC server configuration. 184 | 185 | // Create peer connections and add behavior. 186 | localPeerConnection = new RTCPeerConnection(servers); 187 | trace('Created local peer connection object localPeerConnection.'); 188 | 189 | localPeerConnection.addEventListener('icecandidate', handleConnection); 190 | localPeerConnection.addEventListener( 191 | 'iceconnectionstatechange', handleConnectionChange); 192 | 193 | remotePeerConnection = new RTCPeerConnection(servers); 194 | trace('Created remote peer connection object remotePeerConnection.'); 195 | 196 | remotePeerConnection.addEventListener('icecandidate', handleConnection); 197 | remotePeerConnection.addEventListener( 198 | 'iceconnectionstatechange', handleConnectionChange); 199 | remotePeerConnection.addEventListener('addstream', gotRemoteMediaStream); 200 | 201 | // Add local stream to connection and create offer to connect. 202 | localPeerConnection.addStream(localStream); 203 | trace('Added local stream to localPeerConnection.'); 204 | 205 | trace('localPeerConnection createOffer start.'); 206 | localPeerConnection.createOffer(offerOptions) 207 | .then(createdOffer).catch(setSessionDescriptionError); 208 | } 209 | 210 | // Handles hangup action: ends up call, closes connections and resets peers. 211 | function hangupAction() { 212 | localPeerConnection.close(); 213 | remotePeerConnection.close(); 214 | localPeerConnection = null; 215 | remotePeerConnection = null; 216 | hangupButton.disabled = true; 217 | callButton.disabled = false; 218 | trace('Ending call.'); 219 | } 220 | 221 | // Add click event handlers for buttons. 222 | startButton.addEventListener('click', startAction); 223 | callButton.addEventListener('click', callAction); 224 | hangupButton.addEventListener('click', hangupAction); 225 | 226 | 227 | // Define helper functions. 228 | 229 | // Gets the "other" peer connection. 230 | function getOtherPeer(peerConnection) { 231 | return (peerConnection === localPeerConnection) ? 232 | remotePeerConnection : localPeerConnection; 233 | } 234 | 235 | // Gets the name of a certain peer connection. 236 | function getPeerName(peerConnection) { 237 | return (peerConnection === localPeerConnection) ? 238 | 'localPeerConnection' : 'remotePeerConnection'; 239 | } 240 | 241 | // Logs an action (text) and the time when it happened on the console. 242 | function trace(text) { 243 | text = text.trim(); 244 | const now = (window.performance.now() / 1000).toFixed(3); 245 | 246 | console.log(now, text); 247 | } 248 | -------------------------------------------------------------------------------- /16_getstat/getstats/css/main.css: -------------------------------------------------------------------------------- 1 | body { 2 | font-family: sans-serif; 3 | } 4 | 5 | video { 6 | max-width: 100%; 7 | width: 320px; 8 | } 9 | -------------------------------------------------------------------------------- /16_getstat/getstats/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | Realtime communication with WebRTC 6 | 7 | 8 | 9 | 10 |

Realtime communication with WebRTC

11 | 12 | 13 | 14 | 15 |
16 | 17 | 18 | 19 |
20 | 21 |
22 |
Bitrate
23 | 24 |
25 |
26 |
Packets sent per second
27 | 28 |
29 | 30 | 31 | 32 | 33 | 34 | 35 | 36 | -------------------------------------------------------------------------------- /16_getstat/getstats/js/client.js: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | 3 | // Define peer connections, streams and video elements. 4 | const localVideo = document.getElementById('localVideo'); 5 | const remoteVideo = document.getElementById('remoteVideo'); 6 | 7 | let localStream; 8 | let remoteStream; 9 | 10 | let localPeerConnection; 11 | let remotePeerConnection; 12 | 13 | let bitrateGraph; 14 | let bitrateSeries; 15 | 16 | let packetGraph; 17 | let packetSeries; 18 | 19 | let lastResult; 20 | 21 | //set constraints 22 | const mediaStreamConstraints = { 23 | video: true, 24 | }; 25 | 26 | // Set up to exchange only video. 27 | const offerOptions = { 28 | offerToReceiveVideo: 1, 29 | }; 30 | 31 | // Sets the MediaStream as the video element src. 32 | function gotLocalMediaStream(mediaStream) { 33 | localVideo.srcObject = mediaStream; 34 | localStream = mediaStream; 35 | trace('Received local stream.'); 36 | callButton.disabled = false; // Enable call button. 37 | 38 | bitrateSeries = new TimelineDataSeries(); 39 | bitrateGraph = new TimelineGraphView('bitrateGraph', 'bitrateCanvas'); 40 | bitrateGraph.updateEndDate(); 41 | 42 | packetSeries = new TimelineDataSeries(); 43 | packetGraph = new TimelineGraphView('packetGraph', 'packetCanvas'); 44 | packetGraph.updateEndDate(); 45 | } 46 | 47 | // Handles error by logging a message to the console. 48 | function handleLocalMediaStreamError(error) { 49 | trace(`navigator.getUserMedia error: ${error.toString()}.`); 50 | } 51 | 52 | // Handles remote MediaStream success by adding it as the remoteVideo src. 53 | function gotRemoteMediaStream(event) { 54 | const mediaStream = event.stream; 55 | remoteVideo.srcObject = mediaStream; 56 | remoteStream = mediaStream; 57 | trace('Remote peer connection received remote stream.'); 58 | } 59 | 60 | // Connects with new peer candidate. 61 | function handleConnection(event) { 62 | const peerConnection = event.target; 63 | const iceCandidate = event.candidate; 64 | 65 | if (iceCandidate) { 66 | const newIceCandidate = new RTCIceCandidate(iceCandidate); 67 | const otherPeer = getOtherPeer(peerConnection); 68 | 69 | otherPeer.addIceCandidate(newIceCandidate) 70 | .then(() => { 71 | handleConnectionSuccess(peerConnection); 72 | }).catch((error) => { 73 | handleConnectionFailure(peerConnection, error); 74 | }); 75 | 76 | trace(`${getPeerName(peerConnection)} ICE candidate:\n` + 77 | `${event.candidate.candidate}.`); 78 | } 79 | } 80 | 81 | // Logs that the connection succeeded. 82 | function handleConnectionSuccess(peerConnection) { 83 | trace(`${getPeerName(peerConnection)} addIceCandidate success.`); 84 | }; 85 | 86 | // Logs that the connection failed. 87 | function handleConnectionFailure(peerConnection, error) { 88 | trace(`${getPeerName(peerConnection)} failed to add ICE Candidate:\n`+ 89 | `${error.toString()}.`); 90 | } 91 | 92 | // Logs changes to the connection state. 93 | function handleConnectionChange(event) { 94 | const peerConnection = event.target; 95 | console.log('ICE state change event: ', event); 96 | trace(`${getPeerName(peerConnection)} ICE state: ` + 97 | `${peerConnection.iceConnectionState}.`); 98 | } 99 | 100 | // Logs error when setting session description fails. 101 | function setSessionDescriptionError(error) { 102 | trace(`Failed to create session description: ${error.toString()}.`); 103 | } 104 | 105 | // Logs success when setting session description. 106 | function setDescriptionSuccess(peerConnection, functionName) { 107 | const peerName = getPeerName(peerConnection); 108 | trace(`${peerName} ${functionName} complete.`); 109 | } 110 | 111 | // Logs success when localDescription is set. 112 | function setLocalDescriptionSuccess(peerConnection) { 113 | setDescriptionSuccess(peerConnection, 'setLocalDescription'); 114 | } 115 | 116 | // Logs success when remoteDescription is set. 117 | function setRemoteDescriptionSuccess(peerConnection) { 118 | setDescriptionSuccess(peerConnection, 'setRemoteDescription'); 119 | } 120 | 121 | // Logs offer creation and sets peer connection session descriptions. 122 | function createdOffer(description) { 123 | trace(`Offer from localPeerConnection:\n${description.sdp}`); 124 | 125 | trace('localPeerConnection setLocalDescription start.'); 126 | localPeerConnection.setLocalDescription(description) 127 | .then(() => { 128 | setLocalDescriptionSuccess(localPeerConnection); 129 | }).catch(setSessionDescriptionError); 130 | 131 | trace('remotePeerConnection setRemoteDescription start.'); 132 | remotePeerConnection.setRemoteDescription(description) 133 | .then(() => { 134 | setRemoteDescriptionSuccess(remotePeerConnection); 135 | }).catch(setSessionDescriptionError); 136 | 137 | trace('remotePeerConnection createAnswer start.'); 138 | remotePeerConnection.createAnswer() 139 | .then(createdAnswer) 140 | .catch(setSessionDescriptionError); 141 | } 142 | 143 | // Logs answer to offer creation and sets peer connection session descriptions. 144 | function createdAnswer(description) { 145 | trace(`Answer from remotePeerConnection:\n${description.sdp}.`); 146 | 147 | trace('remotePeerConnection setLocalDescription start.'); 148 | remotePeerConnection.setLocalDescription(description) 149 | .then(() => { 150 | setLocalDescriptionSuccess(remotePeerConnection); 151 | }).catch(setSessionDescriptionError); 152 | 153 | trace('localPeerConnection setRemoteDescription start.'); 154 | localPeerConnection.setRemoteDescription(description) 155 | .then(() => { 156 | setRemoteDescriptionSuccess(localPeerConnection); 157 | }).catch(setSessionDescriptionError); 158 | } 159 | 160 | 161 | // Define and add behavior to buttons. 162 | 163 | // Define action buttons. 164 | const startButton = document.getElementById('startButton'); 165 | const callButton = document.getElementById('callButton'); 166 | const hangupButton = document.getElementById('hangupButton'); 167 | 168 | // Set up initial action buttons status: disable call and hangup. 169 | callButton.disabled = true; 170 | hangupButton.disabled = true; 171 | 172 | 173 | // Handles start button action: creates local MediaStream. 174 | function startAction() { 175 | startButton.disabled = true; 176 | navigator.mediaDevices.getUserMedia(mediaStreamConstraints) 177 | .then(gotLocalMediaStream).catch(handleLocalMediaStreamError); 178 | trace('Requesting local stream.'); 179 | } 180 | 181 | // Handles call button action: creates peer connection. 182 | function callAction() { 183 | callButton.disabled = true; 184 | hangupButton.disabled = false; 185 | 186 | trace('Starting call.'); 187 | 188 | // Get local media stream tracks. 189 | const videoTracks = localStream.getVideoTracks(); 190 | const audioTracks = localStream.getAudioTracks(); 191 | if (videoTracks.length > 0) { 192 | trace(`Using video device: ${videoTracks[0].label}.`); 193 | } 194 | if (audioTracks.length > 0) { 195 | trace(`Using audio device: ${audioTracks[0].label}.`); 196 | } 197 | 198 | const servers = null; // Allows for RTC server configuration. 199 | 200 | // Create peer connections and add behavior. 201 | localPeerConnection = new RTCPeerConnection(servers); 202 | trace('Created local peer connection object localPeerConnection.'); 203 | 204 | localPeerConnection.addEventListener('icecandidate', handleConnection); 205 | localPeerConnection.addEventListener( 206 | 'iceconnectionstatechange', handleConnectionChange); 207 | 208 | remotePeerConnection = new RTCPeerConnection(servers); 209 | trace('Created remote peer connection object remotePeerConnection.'); 210 | 211 | remotePeerConnection.addEventListener('icecandidate', handleConnection); 212 | remotePeerConnection.addEventListener( 213 | 'iceconnectionstatechange', handleConnectionChange); 214 | remotePeerConnection.addEventListener('addstream', gotRemoteMediaStream); 215 | 216 | // Add local stream to connection and create offer to connect. 217 | localPeerConnection.addStream(localStream); 218 | trace('Added local stream to localPeerConnection.'); 219 | 220 | trace('localPeerConnection createOffer start.'); 221 | localPeerConnection.createOffer(offerOptions) 222 | .then(createdOffer).catch(setSessionDescriptionError); 223 | } 224 | 225 | // Handles hangup action: ends up call, closes connections and resets peers. 226 | function hangupAction() { 227 | localPeerConnection.close(); 228 | remotePeerConnection.close(); 229 | localPeerConnection = null; 230 | remotePeerConnection = null; 231 | hangupButton.disabled = true; 232 | callButton.disabled = false; 233 | trace('Ending call.'); 234 | } 235 | 236 | // Add click event handlers for buttons. 237 | startButton.addEventListener('click', startAction); 238 | callButton.addEventListener('click', callAction); 239 | hangupButton.addEventListener('click', hangupAction); 240 | 241 | 242 | // Define helper functions. 243 | 244 | // Gets the "other" peer connection. 245 | function getOtherPeer(peerConnection) { 246 | return (peerConnection === localPeerConnection) ? 247 | remotePeerConnection : localPeerConnection; 248 | } 249 | 250 | // Gets the name of a certain peer connection. 251 | function getPeerName(peerConnection) { 252 | return (peerConnection === localPeerConnection) ? 253 | 'localPeerConnection' : 'remotePeerConnection'; 254 | } 255 | 256 | // Logs an action (text) and the time when it happened on the console. 257 | function trace(text) { 258 | text = text.trim(); 259 | const now = (window.performance.now() / 1000).toFixed(3); 260 | 261 | console.log(now, text); 262 | } 263 | 264 | window.setInterval( ()=>{ 265 | 266 | if(!localPeerConnection){ 267 | return; 268 | } 269 | 270 | var sender = localPeerConnection.getSenders()[0]; 271 | if(!sender){ 272 | return; 273 | } 274 | 275 | sender.getStats() 276 | .then(reports => { 277 | reports.forEach(report =>{ 278 | console.log(report); 279 | if(report.type === 'outbound-rtp'){ 280 | if(report.isRemote){ 281 | return; 282 | } 283 | 284 | var curTs = report.timestamp; 285 | var bytes = report.bytesSent; 286 | var packets = report.packetsSent; 287 | 288 | if(lastResult && lastResult.has(report.id)){ 289 | var lastBytes = lastResult.get(report.id).bytesSent; 290 | var lastTs = lastResult.get(report.id).timestamp; 291 | var bitrate = 8 * (bytes - lastBytes)/(curTs - lastTs)*1000; 292 | 293 | bitrateSeries.addPoint(curTs, bitrate); 294 | bitrateGraph.setDataSeries([bitrateSeries]); 295 | bitrateGraph.updateEndDate(); 296 | 297 | packetSeries.addPoint(curTs, packets - lastResult.get(report.id).packetsSent); 298 | packetGraph.setDataSeries([packetSeries]); 299 | packetGraph.updateEndDate(); 300 | 301 | } 302 | 303 | } 304 | 305 | }); 306 | lastResult = reports; 307 | 308 | }) 309 | .catch(err=>{ 310 | console.error(err); 311 | }); 312 | 313 | }, 1000); 314 | -------------------------------------------------------------------------------- /16_getstat/getstats/js/third_party/graph.js: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2015 The WebRTC project authors. All Rights Reserved. 3 | * 4 | * Use of this source code is governed by a BSD-style license 5 | * that can be found in the LICENSE file in the root of the source 6 | * tree. 7 | */ 8 | // taken from chrome://webrtc-internals with jshint adaptions 9 | 10 | 'use strict'; 11 | /* exported TimelineDataSeries, TimelineGraphView */ 12 | 13 | // The maximum number of data points bufferred for each stats. Old data points 14 | // will be shifted out when the buffer is full. 15 | const MAX_STATS_DATA_POINT_BUFFER_SIZE = 1000; 16 | 17 | const TimelineDataSeries = (function() { 18 | /** 19 | * @constructor 20 | */ 21 | function TimelineDataSeries() { 22 | // List of DataPoints in chronological order. 23 | this.dataPoints_ = []; 24 | 25 | // Default color. Should always be overridden prior to display. 26 | this.color_ = 'red'; 27 | // Whether or not the data series should be drawn. 28 | this.isVisible_ = true; 29 | 30 | this.cacheStartTime_ = null; 31 | this.cacheStepSize_ = 0; 32 | this.cacheValues_ = []; 33 | } 34 | 35 | TimelineDataSeries.prototype = { 36 | /** 37 | * @override 38 | */ 39 | toJSON: function() { 40 | if (this.dataPoints_.length < 1) { 41 | return {}; 42 | } 43 | 44 | let values = []; 45 | for (let i = 0; i < this.dataPoints_.length; ++i) { 46 | values.push(this.dataPoints_[i].value); 47 | } 48 | return { 49 | startTime: this.dataPoints_[0].time, 50 | endTime: this.dataPoints_[this.dataPoints_.length - 1].time, 51 | values: JSON.stringify(values), 52 | }; 53 | }, 54 | 55 | /** 56 | * Adds a DataPoint to |this| with the specified time and value. 57 | * DataPoints are assumed to be received in chronological order. 58 | */ 59 | addPoint: function(timeTicks, value) { 60 | let time = new Date(timeTicks); 61 | this.dataPoints_.push(new DataPoint(time, value)); 62 | 63 | if (this.dataPoints_.length > MAX_STATS_DATA_POINT_BUFFER_SIZE) { 64 | this.dataPoints_.shift(); 65 | } 66 | }, 67 | 68 | isVisible: function() { 69 | return this.isVisible_; 70 | }, 71 | 72 | show: function(isVisible) { 73 | this.isVisible_ = isVisible; 74 | }, 75 | 76 | getColor: function() { 77 | return this.color_; 78 | }, 79 | 80 | setColor: function(color) { 81 | this.color_ = color; 82 | }, 83 | 84 | getCount: function() { 85 | return this.dataPoints_.length; 86 | }, 87 | /** 88 | * Returns a list containing the values of the data series at |count| 89 | * points, starting at |startTime|, and |stepSize| milliseconds apart. 90 | * Caches values, so showing/hiding individual data series is fast. 91 | */ 92 | getValues: function(startTime, stepSize, count) { 93 | // Use cached values, if we can. 94 | if (this.cacheStartTime_ === startTime && 95 | this.cacheStepSize_ === stepSize && 96 | this.cacheValues_.length === count) { 97 | return this.cacheValues_; 98 | } 99 | 100 | // Do all the work. 101 | this.cacheValues_ = this.getValuesInternal_(startTime, stepSize, count); 102 | this.cacheStartTime_ = startTime; 103 | this.cacheStepSize_ = stepSize; 104 | 105 | return this.cacheValues_; 106 | }, 107 | 108 | /** 109 | * Returns the cached |values| in the specified time period. 110 | */ 111 | getValuesInternal_: function(startTime, stepSize, count) { 112 | let values = []; 113 | let nextPoint = 0; 114 | let currentValue = 0; 115 | let time = startTime; 116 | for (let i = 0; i < count; ++i) { 117 | while (nextPoint < this.dataPoints_.length && 118 | this.dataPoints_[nextPoint].time < time) { 119 | currentValue = this.dataPoints_[nextPoint].value; 120 | ++nextPoint; 121 | } 122 | values[i] = currentValue; 123 | time += stepSize; 124 | } 125 | return values; 126 | } 127 | }; 128 | 129 | /** 130 | * A single point in a data series. Each point has a time, in the form of 131 | * milliseconds since the Unix epoch, and a numeric value. 132 | * @constructor 133 | */ 134 | function DataPoint(time, value) { 135 | this.time = time; 136 | this.value = value; 137 | } 138 | 139 | return TimelineDataSeries; 140 | })(); 141 | 142 | const TimelineGraphView = (function() { 143 | // Maximum number of labels placed vertically along the sides of the graph. 144 | let MAX_VERTICAL_LABELS = 6; 145 | 146 | // Vertical spacing between labels and between the graph and labels. 147 | let LABEL_VERTICAL_SPACING = 4; 148 | // Horizontal spacing between vertically placed labels and the edges of the 149 | // graph. 150 | let LABEL_HORIZONTAL_SPACING = 3; 151 | // Horizintal spacing between two horitonally placed labels along the bottom 152 | // of the graph. 153 | // var LABEL_LABEL_HORIZONTAL_SPACING = 25; 154 | 155 | // Length of ticks, in pixels, next to y-axis labels. The x-axis only has 156 | // one set of labels, so it can use lines instead. 157 | let Y_AXIS_TICK_LENGTH = 10; 158 | 159 | let GRID_COLOR = '#CCC'; 160 | let TEXT_COLOR = '#000'; 161 | let BACKGROUND_COLOR = '#FFF'; 162 | 163 | let MAX_DECIMAL_PRECISION = 2; 164 | 165 | /** 166 | * @constructor 167 | */ 168 | function TimelineGraphView(divId, canvasId) { 169 | this.scrollbar_ = {position_: 0, range_: 0}; 170 | 171 | this.graphDiv_ = document.getElementById(divId); 172 | this.canvas_ = document.getElementById(canvasId); 173 | 174 | // Set the range and scale of the graph. Times are in milliseconds since 175 | // the Unix epoch. 176 | 177 | // All measurements we have must be after this time. 178 | this.startTime_ = 0; 179 | // The current rightmost position of the graph is always at most this. 180 | this.endTime_ = 1; 181 | 182 | this.graph_ = null; 183 | 184 | // Horizontal scale factor, in terms of milliseconds per pixel. 185 | this.scale_ = 1000; 186 | 187 | // Initialize the scrollbar. 188 | this.updateScrollbarRange_(true); 189 | } 190 | 191 | TimelineGraphView.prototype = { 192 | setScale: function(scale) { 193 | this.scale_ = scale; 194 | }, 195 | 196 | // Returns the total length of the graph, in pixels. 197 | getLength_: function() { 198 | let timeRange = this.endTime_ - this.startTime_; 199 | // Math.floor is used to ignore the last partial area, of length less 200 | // than this.scale_. 201 | return Math.floor(timeRange / this.scale_); 202 | }, 203 | 204 | /** 205 | * Returns true if the graph is scrolled all the way to the right. 206 | */ 207 | graphScrolledToRightEdge_: function() { 208 | return this.scrollbar_.position_ === this.scrollbar_.range_; 209 | }, 210 | 211 | /** 212 | * Update the range of the scrollbar. If |resetPosition| is true, also 213 | * sets the slider to point at the rightmost position and triggers a 214 | * repaint. 215 | */ 216 | updateScrollbarRange_: function(resetPosition) { 217 | let scrollbarRange = this.getLength_() - this.canvas_.width; 218 | if (scrollbarRange < 0) { 219 | scrollbarRange = 0; 220 | } 221 | 222 | // If we've decreased the range to less than the current scroll position, 223 | // we need to move the scroll position. 224 | if (this.scrollbar_.position_ > scrollbarRange) { 225 | resetPosition = true; 226 | } 227 | 228 | this.scrollbar_.range_ = scrollbarRange; 229 | if (resetPosition) { 230 | this.scrollbar_.position_ = scrollbarRange; 231 | this.repaint(); 232 | } 233 | }, 234 | 235 | /** 236 | * Sets the date range displayed on the graph, switches to the default 237 | * scale factor, and moves the scrollbar all the way to the right. 238 | */ 239 | setDateRange: function(startDate, endDate) { 240 | this.startTime_ = startDate.getTime(); 241 | this.endTime_ = endDate.getTime(); 242 | 243 | // Safety check. 244 | if (this.endTime_ <= this.startTime_) { 245 | this.startTime_ = this.endTime_ - 1; 246 | } 247 | 248 | this.updateScrollbarRange_(true); 249 | }, 250 | 251 | /** 252 | * Updates the end time at the right of the graph to be the current time. 253 | * Specifically, updates the scrollbar's range, and if the scrollbar is 254 | * all the way to the right, keeps it all the way to the right. Otherwise, 255 | * leaves the view as-is and doesn't redraw anything. 256 | */ 257 | updateEndDate: function(optDate) { 258 | this.endTime_ = optDate || (new Date()).getTime(); 259 | this.updateScrollbarRange_(this.graphScrolledToRightEdge_()); 260 | }, 261 | 262 | getStartDate: function() { 263 | return new Date(this.startTime_); 264 | }, 265 | 266 | /** 267 | * Replaces the current TimelineDataSeries with |dataSeries|. 268 | */ 269 | setDataSeries: function(dataSeries) { 270 | // Simply recreates the Graph. 271 | this.graph_ = new Graph(); 272 | for (let i = 0; i < dataSeries.length; ++i) { 273 | this.graph_.addDataSeries(dataSeries[i]); 274 | } 275 | this.repaint(); 276 | }, 277 | 278 | /** 279 | * Adds |dataSeries| to the current graph. 280 | */ 281 | addDataSeries: function(dataSeries) { 282 | if (!this.graph_) { 283 | this.graph_ = new Graph(); 284 | } 285 | this.graph_.addDataSeries(dataSeries); 286 | this.repaint(); 287 | }, 288 | 289 | /** 290 | * Draws the graph on |canvas_|. 291 | */ 292 | repaint: function() { 293 | this.repaintTimerRunning_ = false; 294 | 295 | let width = this.canvas_.width; 296 | let height = this.canvas_.height; 297 | let context = this.canvas_.getContext('2d'); 298 | 299 | // Clear the canvas. 300 | context.fillStyle = BACKGROUND_COLOR; 301 | context.fillRect(0, 0, width, height); 302 | 303 | // Try to get font height in pixels. Needed for layout. 304 | let fontHeightString = context.font.match(/([0-9]+)px/)[1]; 305 | let fontHeight = parseInt(fontHeightString); 306 | 307 | // Safety check, to avoid drawing anything too ugly. 308 | if (fontHeightString.length === 0 || fontHeight <= 0 || 309 | fontHeight * 4 > height || width < 50) { 310 | return; 311 | } 312 | 313 | // Save current transformation matrix so we can restore it later. 314 | context.save(); 315 | 316 | // The center of an HTML canvas pixel is technically at (0.5, 0.5). This 317 | // makes near straight lines look bad, due to anti-aliasing. This 318 | // translation reduces the problem a little. 319 | context.translate(0.5, 0.5); 320 | 321 | // Figure out what time values to display. 322 | let position = this.scrollbar_.position_; 323 | // If the entire time range is being displayed, align the right edge of 324 | // the graph to the end of the time range. 325 | if (this.scrollbar_.range_ === 0) { 326 | position = this.getLength_() - this.canvas_.width; 327 | } 328 | let visibleStartTime = this.startTime_ + position * this.scale_; 329 | 330 | // Make space at the bottom of the graph for the time labels, and then 331 | // draw the labels. 332 | let textHeight = height; 333 | height -= fontHeight + LABEL_VERTICAL_SPACING; 334 | this.drawTimeLabels(context, width, height, textHeight, visibleStartTime); 335 | 336 | // Draw outline of the main graph area. 337 | context.strokeStyle = GRID_COLOR; 338 | context.strokeRect(0, 0, width - 1, height - 1); 339 | 340 | if (this.graph_) { 341 | // Layout graph and have them draw their tick marks. 342 | this.graph_.layout( 343 | width, height, fontHeight, visibleStartTime, this.scale_); 344 | this.graph_.drawTicks(context); 345 | 346 | // Draw the lines of all graphs, and then draw their labels. 347 | this.graph_.drawLines(context); 348 | this.graph_.drawLabels(context); 349 | } 350 | 351 | // Restore original transformation matrix. 352 | context.restore(); 353 | }, 354 | 355 | /** 356 | * Draw time labels below the graph. Takes in start time as an argument 357 | * since it may not be |startTime_|, when we're displaying the entire 358 | * time range. 359 | */ 360 | drawTimeLabels: function(context, width, height, textHeight, startTime) { 361 | // Draw the labels 1 minute apart. 362 | let timeStep = 1000 * 60; 363 | 364 | // Find the time for the first label. This time is a perfect multiple of 365 | // timeStep because of how UTC times work. 366 | let time = Math.ceil(startTime / timeStep) * timeStep; 367 | 368 | context.textBaseline = 'bottom'; 369 | context.textAlign = 'center'; 370 | context.fillStyle = TEXT_COLOR; 371 | context.strokeStyle = GRID_COLOR; 372 | 373 | // Draw labels and vertical grid lines. 374 | while (true) { 375 | let x = Math.round((time - startTime) / this.scale_); 376 | if (x >= width) { 377 | break; 378 | } 379 | let text = (new Date(time)).toLocaleTimeString(); 380 | context.fillText(text, x, textHeight); 381 | context.beginPath(); 382 | context.lineTo(x, 0); 383 | context.lineTo(x, height); 384 | context.stroke(); 385 | time += timeStep; 386 | } 387 | }, 388 | 389 | getDataSeriesCount: function() { 390 | if (this.graph_) { 391 | return this.graph_.dataSeries_.length; 392 | } 393 | return 0; 394 | }, 395 | 396 | hasDataSeries: function(dataSeries) { 397 | if (this.graph_) { 398 | return this.graph_.hasDataSeries(dataSeries); 399 | } 400 | return false; 401 | }, 402 | 403 | }; 404 | 405 | /** 406 | * A Graph is responsible for drawing all the TimelineDataSeries that have 407 | * the same data type. Graphs are responsible for scaling the values, laying 408 | * out labels, and drawing both labels and lines for its data series. 409 | */ 410 | const Graph = (function() { 411 | /** 412 | * @constructor 413 | */ 414 | function Graph() { 415 | this.dataSeries_ = []; 416 | 417 | // Cached properties of the graph, set in layout. 418 | this.width_ = 0; 419 | this.height_ = 0; 420 | this.fontHeight_ = 0; 421 | this.startTime_ = 0; 422 | this.scale_ = 0; 423 | 424 | // The lowest/highest values adjusted by the vertical label step size 425 | // in the displayed range of the graph. Used for scaling and setting 426 | // labels. Set in layoutLabels. 427 | this.min_ = 0; 428 | this.max_ = 0; 429 | 430 | // Cached text of equally spaced labels. Set in layoutLabels. 431 | this.labels_ = []; 432 | } 433 | 434 | /** 435 | * A Label is the label at a particular position along the y-axis. 436 | * @constructor 437 | */ 438 | /* 439 | function Label(height, text) { 440 | this.height = height; 441 | this.text = text; 442 | } 443 | */ 444 | 445 | Graph.prototype = { 446 | addDataSeries: function(dataSeries) { 447 | this.dataSeries_.push(dataSeries); 448 | }, 449 | 450 | hasDataSeries: function(dataSeries) { 451 | for (let i = 0; i < this.dataSeries_.length; ++i) { 452 | if (this.dataSeries_[i] === dataSeries) { 453 | return true; 454 | } 455 | } 456 | return false; 457 | }, 458 | 459 | /** 460 | * Returns a list of all the values that should be displayed for a given 461 | * data series, using the current graph layout. 462 | */ 463 | getValues: function(dataSeries) { 464 | if (!dataSeries.isVisible()) { 465 | return null; 466 | } 467 | return dataSeries.getValues(this.startTime_, this.scale_, this.width_); 468 | }, 469 | 470 | /** 471 | * Updates the graph's layout. In particular, both the max value and 472 | * label positions are updated. Must be called before calling any of the 473 | * drawing functions. 474 | */ 475 | layout: function(width, height, fontHeight, startTime, scale) { 476 | this.width_ = width; 477 | this.height_ = height; 478 | this.fontHeight_ = fontHeight; 479 | this.startTime_ = startTime; 480 | this.scale_ = scale; 481 | 482 | // Find largest value. 483 | let max = 0; 484 | let min = 0; 485 | for (let i = 0; i < this.dataSeries_.length; ++i) { 486 | let values = this.getValues(this.dataSeries_[i]); 487 | if (!values) { 488 | continue; 489 | } 490 | for (let j = 0; j < values.length; ++j) { 491 | if (values[j] > max) { 492 | max = values[j]; 493 | } else if (values[j] < min) { 494 | min = values[j]; 495 | } 496 | } 497 | } 498 | 499 | this.layoutLabels_(min, max); 500 | }, 501 | 502 | /** 503 | * Lays out labels and sets |max_|/|min_|, taking the time units into 504 | * consideration. |maxValue| is the actual maximum value, and 505 | * |max_| will be set to the value of the largest label, which 506 | * will be at least |maxValue|. Similar for |min_|. 507 | */ 508 | layoutLabels_: function(minValue, maxValue) { 509 | if (maxValue - minValue < 1024) { 510 | this.layoutLabelsBasic_(minValue, maxValue, MAX_DECIMAL_PRECISION); 511 | return; 512 | } 513 | 514 | // Find appropriate units to use. 515 | let units = ['', 'k', 'M', 'G', 'T', 'P']; 516 | // Units to use for labels. 0 is '1', 1 is K, etc. 517 | // We start with 1, and work our way up. 518 | let unit = 1; 519 | minValue /= 1024; 520 | maxValue /= 1024; 521 | while (units[unit + 1] && maxValue - minValue >= 1024) { 522 | minValue /= 1024; 523 | maxValue /= 1024; 524 | ++unit; 525 | } 526 | 527 | // Calculate labels. 528 | this.layoutLabelsBasic_(minValue, maxValue, MAX_DECIMAL_PRECISION); 529 | 530 | // Append units to labels. 531 | for (let i = 0; i < this.labels_.length; ++i) { 532 | this.labels_[i] += ' ' + units[unit]; 533 | } 534 | 535 | // Convert |min_|/|max_| back to unit '1'. 536 | this.min_ *= Math.pow(1024, unit); 537 | this.max_ *= Math.pow(1024, unit); 538 | }, 539 | 540 | /** 541 | * Same as layoutLabels_, but ignores units. |maxDecimalDigits| is the 542 | * maximum number of decimal digits allowed. The minimum allowed 543 | * difference between two adjacent labels is 10^-|maxDecimalDigits|. 544 | */ 545 | layoutLabelsBasic_: function(minValue, maxValue, maxDecimalDigits) { 546 | this.labels_ = []; 547 | let range = maxValue - minValue; 548 | // No labels if the range is 0. 549 | if (range === 0) { 550 | this.min_ = this.max_ = maxValue; 551 | return; 552 | } 553 | 554 | // The maximum number of equally spaced labels allowed. |fontHeight_| 555 | // is doubled because the top two labels are both drawn in the same 556 | // gap. 557 | let minLabelSpacing = 2 * this.fontHeight_ + LABEL_VERTICAL_SPACING; 558 | 559 | // The + 1 is for the top label. 560 | let maxLabels = 1 + this.height_ / minLabelSpacing; 561 | if (maxLabels < 2) { 562 | maxLabels = 2; 563 | } else if (maxLabels > MAX_VERTICAL_LABELS) { 564 | maxLabels = MAX_VERTICAL_LABELS; 565 | } 566 | 567 | // Initial try for step size between conecutive labels. 568 | let stepSize = Math.pow(10, -maxDecimalDigits); 569 | // Number of digits to the right of the decimal of |stepSize|. 570 | // Used for formating label strings. 571 | let stepSizeDecimalDigits = maxDecimalDigits; 572 | 573 | // Pick a reasonable step size. 574 | while (true) { 575 | // If we use a step size of |stepSize| between labels, we'll need: 576 | // 577 | // Math.ceil(range / stepSize) + 1 578 | // 579 | // labels. The + 1 is because we need labels at both at 0 and at 580 | // the top of the graph. 581 | 582 | // Check if we can use steps of size |stepSize|. 583 | if (Math.ceil(range / stepSize) + 1 <= maxLabels) { 584 | break; 585 | } 586 | // Check |stepSize| * 2. 587 | if (Math.ceil(range / (stepSize * 2)) + 1 <= maxLabels) { 588 | stepSize *= 2; 589 | break; 590 | } 591 | // Check |stepSize| * 5. 592 | if (Math.ceil(range / (stepSize * 5)) + 1 <= maxLabels) { 593 | stepSize *= 5; 594 | break; 595 | } 596 | stepSize *= 10; 597 | if (stepSizeDecimalDigits > 0) { 598 | --stepSizeDecimalDigits; 599 | } 600 | } 601 | 602 | // Set the min/max so it's an exact multiple of the chosen step size. 603 | this.max_ = Math.ceil(maxValue / stepSize) * stepSize; 604 | this.min_ = Math.floor(minValue / stepSize) * stepSize; 605 | 606 | // Create labels. 607 | for (let label = this.max_; label >= this.min_; label -= stepSize) { 608 | this.labels_.push(label.toFixed(stepSizeDecimalDigits)); 609 | } 610 | }, 611 | 612 | /** 613 | * Draws tick marks for each of the labels in |labels_|. 614 | */ 615 | drawTicks: function(context) { 616 | let x1; 617 | let x2; 618 | x1 = this.width_ - 1; 619 | x2 = this.width_ - 1 - Y_AXIS_TICK_LENGTH; 620 | 621 | context.fillStyle = GRID_COLOR; 622 | context.beginPath(); 623 | for (let i = 1; i < this.labels_.length - 1; ++i) { 624 | // The rounding is needed to avoid ugly 2-pixel wide anti-aliased 625 | // lines. 626 | let y = Math.round(this.height_ * i / (this.labels_.length - 1)); 627 | context.moveTo(x1, y); 628 | context.lineTo(x2, y); 629 | } 630 | context.stroke(); 631 | }, 632 | 633 | /** 634 | * Draws a graph line for each of the data series. 635 | */ 636 | drawLines: function(context) { 637 | // Factor by which to scale all values to convert them to a number from 638 | // 0 to height - 1. 639 | let scale = 0; 640 | let bottom = this.height_ - 1; 641 | if (this.max_) { 642 | scale = bottom / (this.max_ - this.min_); 643 | } 644 | 645 | // Draw in reverse order, so earlier data series are drawn on top of 646 | // subsequent ones. 647 | for (let i = this.dataSeries_.length - 1; i >= 0; --i) { 648 | let values = this.getValues(this.dataSeries_[i]); 649 | if (!values) { 650 | continue; 651 | } 652 | context.strokeStyle = this.dataSeries_[i].getColor(); 653 | context.beginPath(); 654 | for (let x = 0; x < values.length; ++x) { 655 | // The rounding is needed to avoid ugly 2-pixel wide anti-aliased 656 | // horizontal lines. 657 | context.lineTo( 658 | x, bottom - Math.round((values[x] - this.min_) * scale)); 659 | } 660 | context.stroke(); 661 | } 662 | }, 663 | 664 | /** 665 | * Draw labels in |labels_|. 666 | */ 667 | drawLabels: function(context) { 668 | if (this.labels_.length === 0) { 669 | return; 670 | } 671 | let x = this.width_ - LABEL_HORIZONTAL_SPACING; 672 | 673 | // Set up the context. 674 | context.fillStyle = TEXT_COLOR; 675 | context.textAlign = 'right'; 676 | 677 | // Draw top label, which is the only one that appears below its tick 678 | // mark. 679 | context.textBaseline = 'top'; 680 | context.fillText(this.labels_[0], x, 0); 681 | 682 | // Draw all the other labels. 683 | context.textBaseline = 'bottom'; 684 | let step = (this.height_ - 1) / (this.labels_.length - 1); 685 | for (let i = 1; i < this.labels_.length; ++i) { 686 | context.fillText(this.labels_[i], x, step * i); 687 | } 688 | } 689 | }; 690 | 691 | return Graph; 692 | })(); 693 | 694 | return TimelineGraphView; 695 | })(); 696 | -------------------------------------------------------------------------------- /19_chat/chat_new/css/main.css: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2015 The WebRTC project authors. All Rights Reserved. 3 | * 4 | * Use of this source code is governed by a BSD-style license 5 | * that can be found in the LICENSE file in the root of the source 6 | * tree. 7 | */ 8 | 9 | button { 10 | margin: 10px 20px 25px 0; 11 | vertical-align: top; 12 | width: 134px; 13 | } 14 | 15 | table { 16 | margin: 200px (50% - 100) 0 0; 17 | } 18 | 19 | textarea#chat { 20 | color: #444; 21 | font-size: 0.9em; 22 | font-weight: 300; 23 | height: 325px; 24 | margin: 5px; 25 | padding: 5px; 26 | width: calc(100% - 10px); 27 | } 28 | 29 | textarea#sendtxt { 30 | color: #444; 31 | font-size: 0.9em; 32 | font-weight: 300; 33 | height: 125px; 34 | margin: 5px; 35 | padding: 5px; 36 | width: calc(100% - 10px); 37 | } 38 | 39 | div#getUserMedia { 40 | padding: 0 0 8px 0; 41 | } 42 | 43 | div.input { 44 | display: inline-block; 45 | margin: 0 4px 0 0; 46 | vertical-align: top; 47 | width: 310px; 48 | } 49 | 50 | div.input > div { 51 | margin: 0 0 20px 0; 52 | vertical-align: top; 53 | } 54 | 55 | div.output { 56 | background-color: #eee; 57 | display: inline-block; 58 | font-family: 'Inconsolata', 'Courier New', monospace; 59 | font-size: 0.9em; 60 | padding: 10px 10px 10px 25px; 61 | position: relative; 62 | top: 10px; 63 | white-space: pre; 64 | width: 270px; 65 | } 66 | 67 | div.label { 68 | display: inline-block; 69 | font-weight: 400; 70 | width: 120px; 71 | } 72 | 73 | div.graph-container { 74 | background-color: #ccc; 75 | float: left; 76 | margin: 10px; 77 | } 78 | 79 | div.preview { 80 | border-bottom: 1px solid #eee; 81 | margin: 0 0 1em 0; 82 | padding: 0 0 0.5em 0; 83 | } 84 | 85 | div.preview > div { 86 | display: inline-block; 87 | vertical-align: top; 88 | width: calc(50% - 40px); 89 | } 90 | 91 | section#statistics div { 92 | display: inline-block; 93 | font-family: 'Inconsolata', 'Courier New', monospace; 94 | vertical-align: top; 95 | width: 308px; 96 | } 97 | 98 | section#statistics div#senderStats { 99 | margin: 0 20px 0 0; 100 | } 101 | 102 | section#constraints > div { 103 | margin: 0 0 20px 0; 104 | } 105 | 106 | h2 { 107 | margin: 0 0 1em 0; 108 | } 109 | 110 | 111 | section#constraints label { 112 | display: inline-block; 113 | width: 156px; 114 | } 115 | 116 | section { 117 | margin: 0 0 20px 0; 118 | padding: 0 0 15px 0; 119 | } 120 | 121 | video { 122 | background: #222; 123 | margin: 0 0 0 0; 124 | --width: 100%; 125 | width: var(--width); 126 | height: 225px; 127 | } 128 | 129 | @media screen and (max-width: 720px) { 130 | button { 131 | font-weight: 500; 132 | height: 56px; 133 | line-height: 1.3em; 134 | width: 90px; 135 | } 136 | 137 | div#getUserMedia { 138 | padding: 0 0 40px 0; 139 | } 140 | 141 | section#statistics div { 142 | width: calc(50% - 14px); 143 | } 144 | 145 | } 146 | -------------------------------------------------------------------------------- /19_chat/chat_new/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | WebRTC PeerConnection 4 | 5 | 6 | 7 | 8 |
9 | 10 |
11 | 12 | 13 |
14 | 15 | 29 | 30 | 31 |
32 | 41 | 42 |
43 |

Chat:

44 | 45 | 46 | 47 |
48 | 49 | 50 |
51 | 52 | 64 | 65 |
66 | 67 | 68 | 69 | 70 | 71 | 72 | 73 | -------------------------------------------------------------------------------- /19_chat/chat_new/js/main_bw.js: -------------------------------------------------------------------------------- 1 | 'use strict' 2 | 3 | 4 | var btnConn = document.querySelector('button#connserver'); 5 | var btnLeave = document.querySelector('button#leave'); 6 | 7 | 8 | var chat = document.querySelector('textarea#chat'); 9 | var send_txt = document.querySelector('textarea#sendtxt'); 10 | var btnSend = document.querySelector('button#send'); 11 | 12 | var pcConfig = { 13 | 'iceServers': [{ 14 | 'urls': 'turn:stun.al.learningrtc.cn:3478', 15 | 'credential': "mypasswd", 16 | 'username': "garrylea" 17 | }] 18 | }; 19 | 20 | 21 | var pc = null; 22 | var dc = null; 23 | 24 | var roomid; 25 | var socket = null; 26 | 27 | var offerdesc = null; 28 | var state = 'init'; 29 | 30 | 31 | 32 | function sendMessage(roomid, data){ 33 | 34 | console.log('send message to other end', roomid, data); 35 | if(!socket){ 36 | console.log('socket is null'); 37 | } 38 | socket.emit('message', roomid, data); 39 | } 40 | 41 | // 42 | function receivemsg(e){ 43 | var msg = e.data; 44 | if(msg){ 45 | chat.value += '-> ' + msg + '\r\n'; 46 | }else{ 47 | console.error('received msg is null'); 48 | } 49 | } 50 | 51 | function dataChannelStateChange(){ 52 | var readyState = dc.readyState; 53 | if(readyState === 'open'){ 54 | send_txt.disabled = false; 55 | send.disabled = false; 56 | }else{ 57 | send_txt.disabled = true; 58 | send.disabled =true; 59 | } 60 | } 61 | 62 | function conn(){ 63 | 64 | socket = io.connect(); 65 | 66 | socket.on('joined', (roomid, id) => { 67 | console.log('receive joined message!', roomid, id); 68 | state = 'joined' 69 | 70 | //如果是多人的话,第一个人不该在这里创建peerConnection 71 | //都等到收到一个otherjoin时再创建 72 | //所以,在这个消息里应该带当前房间的用户数 73 | // 74 | //create conn and bind media track 75 | createPeerConnection(); 76 | 77 | btnConn.disabled = true; 78 | btnLeave.disabled = false; 79 | 80 | console.log('receive joined message, state=', state); 81 | }); 82 | 83 | socket.on('otherjoin', (roomid) => { 84 | console.log('receive joined message:', roomid, state); 85 | 86 | //如果是多人的话,每上来一个人都要创建一个新的 peerConnection 87 | // 88 | if(state === 'joined_unbind'){ 89 | createPeerConnection(); 90 | } 91 | 92 | // 93 | dc = pc.createDataChannel('chat'); 94 | dc.onmessage = receivemsg; 95 | dc.onopen = dataChannelStateChange; 96 | dc.onclose = dataChannelStateChange; 97 | 98 | state = 'joined_conn'; 99 | call(); 100 | 101 | console.log('receive other_join message, state=', state); 102 | }); 103 | 104 | socket.on('full', (roomid, id) => { 105 | console.log('receive full message', roomid, id); 106 | socket.disconnect(); 107 | hangup(); 108 | state = 'leaved'; 109 | console.log('receive full message, state=', state); 110 | alert('the room is full!'); 111 | }); 112 | 113 | socket.on('leaved', (roomid, id) => { 114 | console.log('receive leaved message', roomid, id); 115 | state='leaved' 116 | socket.disconnect(); 117 | console.log('receive leaved message, state=', state); 118 | 119 | btnConn.disabled = false; 120 | btnLeave.disabled = true; 121 | }); 122 | 123 | socket.on('bye', (room, id) => { 124 | console.log('receive bye message', roomid, id); 125 | //state = 'created'; 126 | //当是多人通话时,应该带上当前房间的用户数 127 | //如果当前房间用户不小于 2, 则不用修改状态 128 | //并且,关闭的应该是对应用户的peerconnection 129 | //在客户端应该维护一张peerconnection表,它是 130 | //一个key:value的格式,key=userid, value=peerconnection 131 | state = 'joined_unbind'; 132 | hangup(); 133 | console.log('receive bye message, state=', state); 134 | }); 135 | 136 | socket.on('disconnect', (socket) => { 137 | console.log('receive disconnect message!', roomid); 138 | if(!(state === 'leaved')){ 139 | hangup(); 140 | } 141 | state = 'leaved'; 142 | 143 | btnConn.disabled = false; 144 | btnLeave.disabled = true; 145 | 146 | }); 147 | 148 | socket.on('message', (roomid, data) => { 149 | console.log('receive message!', roomid, data); 150 | 151 | if(data === null || data === undefined){ 152 | console.error('the message is invalid!'); 153 | return; 154 | } 155 | 156 | if(data.hasOwnProperty('type') && data.type === 'offer') { 157 | 158 | pc.setRemoteDescription(new RTCSessionDescription(data)); 159 | //create answer 160 | pc.createAnswer() 161 | .then(getAnswer) 162 | .catch(handleAnswerError); 163 | 164 | }else if(data.hasOwnProperty('type') && data.type === 'answer'){ 165 | pc.setRemoteDescription(new RTCSessionDescription(data)); 166 | 167 | }else if (data.hasOwnProperty('type') && data.type === 'candidate'){ 168 | var candidate = new RTCIceCandidate({ 169 | sdpMLineIndex: data.label, 170 | candidate: data.candidate 171 | }); 172 | pc.addIceCandidate(candidate) 173 | .then(()=>{ 174 | console.log('Successed to add ice candidate'); 175 | }) 176 | .catch(err=>{ 177 | console.error(err); 178 | }); 179 | 180 | }else{ 181 | console.log('the message is invalid!', data); 182 | 183 | } 184 | 185 | }); 186 | 187 | 188 | roomid = '111111'; 189 | socket.emit('join', roomid); 190 | 191 | return true; 192 | } 193 | 194 | function connSignalServer(){ 195 | 196 | //setup connection 197 | conn(); 198 | 199 | return true; 200 | } 201 | 202 | function getMediaStream(stream){ 203 | 204 | localStream = stream; 205 | localVideo.srcObject = localStream; 206 | 207 | //这个函数的位置特别重要, 208 | //一定要放到getMediaStream之后再调用 209 | //否则就会出现绑定失败的情况 210 | 211 | 212 | bitrateSeries = new TimelineDataSeries(); 213 | bitrateGraph = new TimelineGraphView('bitrateGraph', 'bitrateCanvas'); 214 | bitrateGraph.updateEndDate(); 215 | 216 | packetSeries = new TimelineDataSeries(); 217 | packetGraph = new TimelineGraphView('packetGraph', 'packetCanvas'); 218 | packetGraph.updateEndDate(); 219 | } 220 | 221 | function getDeskStream(stream){ 222 | localStream = stream; 223 | } 224 | 225 | function handleError(err){ 226 | console.error('Failed to get Media Stream!', err); 227 | } 228 | 229 | function shareDesk(){ 230 | 231 | if(IsPC()){ 232 | navigator.mediaDevices.getDisplayMedia({video: true}) 233 | .then(getDeskStream) 234 | .catch(handleError); 235 | 236 | return true; 237 | } 238 | 239 | return false; 240 | 241 | } 242 | 243 | function handleOfferError(err){ 244 | console.error('Failed to create offer:', err); 245 | } 246 | 247 | function handleAnswerError(err){ 248 | console.error('Failed to create answer:', err); 249 | } 250 | 251 | function getAnswer(desc){ 252 | pc.setLocalDescription(desc); 253 | 254 | //send answer sdp 255 | sendMessage(roomid, desc); 256 | } 257 | 258 | function getOffer(desc){ 259 | pc.setLocalDescription(desc); 260 | offerdesc = desc; 261 | 262 | //send offer sdp 263 | sendMessage(roomid, offerdesc); 264 | 265 | } 266 | 267 | // 268 | // 269 | 270 | function createPeerConnection(){ 271 | 272 | //如果是多人的话,在这里要创建一个新的连接. 273 | //新创建好的要放到一个map表中。 274 | //key=userid, value=peerconnection 275 | console.log('create RTCPeerConnection!'); 276 | if(!pc){ 277 | pc = new RTCPeerConnection(pcConfig); 278 | 279 | pc.onicecandidate = (e)=>{ 280 | 281 | if(e.candidate) { 282 | sendMessage(roomid, { 283 | type: 'candidate', 284 | label:event.candidate.sdpMLineIndex, 285 | id:event.candidate.sdpMid, 286 | candidate: event.candidate.candidate 287 | }); 288 | }else{ 289 | console.log('this is the end candidate'); 290 | } 291 | } 292 | 293 | // 294 | pc.ondatachannel = e => { 295 | if(!dc){ 296 | dc = e.channel; 297 | dc.onmessage = receivemsg; 298 | dc.onopen = dataChannelStateChange; 299 | dc.opclose = dataChannelStateChange; 300 | } 301 | } 302 | 303 | }else { 304 | console.log('the pc have be created!'); 305 | } 306 | 307 | return; 308 | } 309 | 310 | function call(){ 311 | 312 | if(state === 'joined_conn'){ 313 | 314 | /* 315 | var offerOptions = { 316 | offerToRecieveAudio: 1, 317 | offerToRecieveVideo: 1 318 | } 319 | */ 320 | 321 | pc.createOffer() 322 | .then(getOffer) 323 | .catch(handleOfferError); 324 | } 325 | } 326 | 327 | function hangup(){ 328 | 329 | if(!pc) { 330 | return; 331 | } 332 | 333 | offerdesc = null; 334 | 335 | pc.close(); 336 | pc = null; 337 | 338 | } 339 | 340 | function leave() { 341 | 342 | socket.emit('leave', roomid); //notify server 343 | 344 | hangup(); 345 | 346 | btnConn.disabled = false; 347 | btnLeave.disabled = true; 348 | 349 | } 350 | 351 | // 352 | function sendText(){ 353 | var data = send_txt.value; 354 | if(data){ 355 | dc.send(data); 356 | } 357 | 358 | send_txt.value = ''; 359 | chat.value += '<-' + data + '\r\n'; 360 | } 361 | 362 | btnConn.onclick = connSignalServer 363 | btnLeave.onclick = leave; 364 | 365 | btnSend.onclick = sendText; 366 | -------------------------------------------------------------------------------- /19_chat/chat_new/js/third_party/graph.js: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2015 The WebRTC project authors. All Rights Reserved. 3 | * 4 | * Use of this source code is governed by a BSD-style license 5 | * that can be found in the LICENSE file in the root of the source 6 | * tree. 7 | */ 8 | // taken from chrome://webrtc-internals with jshint adaptions 9 | 10 | 'use strict'; 11 | /* exported TimelineDataSeries, TimelineGraphView */ 12 | 13 | // The maximum number of data points bufferred for each stats. Old data points 14 | // will be shifted out when the buffer is full. 15 | const MAX_STATS_DATA_POINT_BUFFER_SIZE = 1000; 16 | 17 | const TimelineDataSeries = (function() { 18 | /** 19 | * @constructor 20 | */ 21 | function TimelineDataSeries() { 22 | // List of DataPoints in chronological order. 23 | this.dataPoints_ = []; 24 | 25 | // Default color. Should always be overridden prior to display. 26 | this.color_ = 'red'; 27 | // Whether or not the data series should be drawn. 28 | this.isVisible_ = true; 29 | 30 | this.cacheStartTime_ = null; 31 | this.cacheStepSize_ = 0; 32 | this.cacheValues_ = []; 33 | } 34 | 35 | TimelineDataSeries.prototype = { 36 | /** 37 | * @override 38 | */ 39 | toJSON: function() { 40 | if (this.dataPoints_.length < 1) { 41 | return {}; 42 | } 43 | 44 | let values = []; 45 | for (let i = 0; i < this.dataPoints_.length; ++i) { 46 | values.push(this.dataPoints_[i].value); 47 | } 48 | return { 49 | startTime: this.dataPoints_[0].time, 50 | endTime: this.dataPoints_[this.dataPoints_.length - 1].time, 51 | values: JSON.stringify(values), 52 | }; 53 | }, 54 | 55 | /** 56 | * Adds a DataPoint to |this| with the specified time and value. 57 | * DataPoints are assumed to be received in chronological order. 58 | */ 59 | addPoint: function(timeTicks, value) { 60 | let time = new Date(timeTicks); 61 | this.dataPoints_.push(new DataPoint(time, value)); 62 | 63 | if (this.dataPoints_.length > MAX_STATS_DATA_POINT_BUFFER_SIZE) { 64 | this.dataPoints_.shift(); 65 | } 66 | }, 67 | 68 | isVisible: function() { 69 | return this.isVisible_; 70 | }, 71 | 72 | show: function(isVisible) { 73 | this.isVisible_ = isVisible; 74 | }, 75 | 76 | getColor: function() { 77 | return this.color_; 78 | }, 79 | 80 | setColor: function(color) { 81 | this.color_ = color; 82 | }, 83 | 84 | getCount: function() { 85 | return this.dataPoints_.length; 86 | }, 87 | /** 88 | * Returns a list containing the values of the data series at |count| 89 | * points, starting at |startTime|, and |stepSize| milliseconds apart. 90 | * Caches values, so showing/hiding individual data series is fast. 91 | */ 92 | getValues: function(startTime, stepSize, count) { 93 | // Use cached values, if we can. 94 | if (this.cacheStartTime_ === startTime && 95 | this.cacheStepSize_ === stepSize && 96 | this.cacheValues_.length === count) { 97 | return this.cacheValues_; 98 | } 99 | 100 | // Do all the work. 101 | this.cacheValues_ = this.getValuesInternal_(startTime, stepSize, count); 102 | this.cacheStartTime_ = startTime; 103 | this.cacheStepSize_ = stepSize; 104 | 105 | return this.cacheValues_; 106 | }, 107 | 108 | /** 109 | * Returns the cached |values| in the specified time period. 110 | */ 111 | getValuesInternal_: function(startTime, stepSize, count) { 112 | let values = []; 113 | let nextPoint = 0; 114 | let currentValue = 0; 115 | let time = startTime; 116 | for (let i = 0; i < count; ++i) { 117 | while (nextPoint < this.dataPoints_.length && 118 | this.dataPoints_[nextPoint].time < time) { 119 | currentValue = this.dataPoints_[nextPoint].value; 120 | ++nextPoint; 121 | } 122 | values[i] = currentValue; 123 | time += stepSize; 124 | } 125 | return values; 126 | } 127 | }; 128 | 129 | /** 130 | * A single point in a data series. Each point has a time, in the form of 131 | * milliseconds since the Unix epoch, and a numeric value. 132 | * @constructor 133 | */ 134 | function DataPoint(time, value) { 135 | this.time = time; 136 | this.value = value; 137 | } 138 | 139 | return TimelineDataSeries; 140 | })(); 141 | 142 | const TimelineGraphView = (function() { 143 | // Maximum number of labels placed vertically along the sides of the graph. 144 | let MAX_VERTICAL_LABELS = 6; 145 | 146 | // Vertical spacing between labels and between the graph and labels. 147 | let LABEL_VERTICAL_SPACING = 4; 148 | // Horizontal spacing between vertically placed labels and the edges of the 149 | // graph. 150 | let LABEL_HORIZONTAL_SPACING = 3; 151 | // Horizintal spacing between two horitonally placed labels along the bottom 152 | // of the graph. 153 | // var LABEL_LABEL_HORIZONTAL_SPACING = 25; 154 | 155 | // Length of ticks, in pixels, next to y-axis labels. The x-axis only has 156 | // one set of labels, so it can use lines instead. 157 | let Y_AXIS_TICK_LENGTH = 10; 158 | 159 | let GRID_COLOR = '#CCC'; 160 | let TEXT_COLOR = '#000'; 161 | let BACKGROUND_COLOR = '#FFF'; 162 | 163 | let MAX_DECIMAL_PRECISION = 2; 164 | 165 | /** 166 | * @constructor 167 | */ 168 | function TimelineGraphView(divId, canvasId) { 169 | this.scrollbar_ = {position_: 0, range_: 0}; 170 | 171 | this.graphDiv_ = document.getElementById(divId); 172 | this.canvas_ = document.getElementById(canvasId); 173 | 174 | // Set the range and scale of the graph. Times are in milliseconds since 175 | // the Unix epoch. 176 | 177 | // All measurements we have must be after this time. 178 | this.startTime_ = 0; 179 | // The current rightmost position of the graph is always at most this. 180 | this.endTime_ = 1; 181 | 182 | this.graph_ = null; 183 | 184 | // Horizontal scale factor, in terms of milliseconds per pixel. 185 | this.scale_ = 1000; 186 | 187 | // Initialize the scrollbar. 188 | this.updateScrollbarRange_(true); 189 | } 190 | 191 | TimelineGraphView.prototype = { 192 | setScale: function(scale) { 193 | this.scale_ = scale; 194 | }, 195 | 196 | // Returns the total length of the graph, in pixels. 197 | getLength_: function() { 198 | let timeRange = this.endTime_ - this.startTime_; 199 | // Math.floor is used to ignore the last partial area, of length less 200 | // than this.scale_. 201 | return Math.floor(timeRange / this.scale_); 202 | }, 203 | 204 | /** 205 | * Returns true if the graph is scrolled all the way to the right. 206 | */ 207 | graphScrolledToRightEdge_: function() { 208 | return this.scrollbar_.position_ === this.scrollbar_.range_; 209 | }, 210 | 211 | /** 212 | * Update the range of the scrollbar. If |resetPosition| is true, also 213 | * sets the slider to point at the rightmost position and triggers a 214 | * repaint. 215 | */ 216 | updateScrollbarRange_: function(resetPosition) { 217 | let scrollbarRange = this.getLength_() - this.canvas_.width; 218 | if (scrollbarRange < 0) { 219 | scrollbarRange = 0; 220 | } 221 | 222 | // If we've decreased the range to less than the current scroll position, 223 | // we need to move the scroll position. 224 | if (this.scrollbar_.position_ > scrollbarRange) { 225 | resetPosition = true; 226 | } 227 | 228 | this.scrollbar_.range_ = scrollbarRange; 229 | if (resetPosition) { 230 | this.scrollbar_.position_ = scrollbarRange; 231 | this.repaint(); 232 | } 233 | }, 234 | 235 | /** 236 | * Sets the date range displayed on the graph, switches to the default 237 | * scale factor, and moves the scrollbar all the way to the right. 238 | */ 239 | setDateRange: function(startDate, endDate) { 240 | this.startTime_ = startDate.getTime(); 241 | this.endTime_ = endDate.getTime(); 242 | 243 | // Safety check. 244 | if (this.endTime_ <= this.startTime_) { 245 | this.startTime_ = this.endTime_ - 1; 246 | } 247 | 248 | this.updateScrollbarRange_(true); 249 | }, 250 | 251 | /** 252 | * Updates the end time at the right of the graph to be the current time. 253 | * Specifically, updates the scrollbar's range, and if the scrollbar is 254 | * all the way to the right, keeps it all the way to the right. Otherwise, 255 | * leaves the view as-is and doesn't redraw anything. 256 | */ 257 | updateEndDate: function(optDate) { 258 | this.endTime_ = optDate || (new Date()).getTime(); 259 | this.updateScrollbarRange_(this.graphScrolledToRightEdge_()); 260 | }, 261 | 262 | getStartDate: function() { 263 | return new Date(this.startTime_); 264 | }, 265 | 266 | /** 267 | * Replaces the current TimelineDataSeries with |dataSeries|. 268 | */ 269 | setDataSeries: function(dataSeries) { 270 | // Simply recreates the Graph. 271 | this.graph_ = new Graph(); 272 | for (let i = 0; i < dataSeries.length; ++i) { 273 | this.graph_.addDataSeries(dataSeries[i]); 274 | } 275 | this.repaint(); 276 | }, 277 | 278 | /** 279 | * Adds |dataSeries| to the current graph. 280 | */ 281 | addDataSeries: function(dataSeries) { 282 | if (!this.graph_) { 283 | this.graph_ = new Graph(); 284 | } 285 | this.graph_.addDataSeries(dataSeries); 286 | this.repaint(); 287 | }, 288 | 289 | /** 290 | * Draws the graph on |canvas_|. 291 | */ 292 | repaint: function() { 293 | this.repaintTimerRunning_ = false; 294 | 295 | let width = this.canvas_.width; 296 | let height = this.canvas_.height; 297 | let context = this.canvas_.getContext('2d'); 298 | 299 | // Clear the canvas. 300 | context.fillStyle = BACKGROUND_COLOR; 301 | context.fillRect(0, 0, width, height); 302 | 303 | // Try to get font height in pixels. Needed for layout. 304 | let fontHeightString = context.font.match(/([0-9]+)px/)[1]; 305 | let fontHeight = parseInt(fontHeightString); 306 | 307 | // Safety check, to avoid drawing anything too ugly. 308 | if (fontHeightString.length === 0 || fontHeight <= 0 || 309 | fontHeight * 4 > height || width < 50) { 310 | return; 311 | } 312 | 313 | // Save current transformation matrix so we can restore it later. 314 | context.save(); 315 | 316 | // The center of an HTML canvas pixel is technically at (0.5, 0.5). This 317 | // makes near straight lines look bad, due to anti-aliasing. This 318 | // translation reduces the problem a little. 319 | context.translate(0.5, 0.5); 320 | 321 | // Figure out what time values to display. 322 | let position = this.scrollbar_.position_; 323 | // If the entire time range is being displayed, align the right edge of 324 | // the graph to the end of the time range. 325 | if (this.scrollbar_.range_ === 0) { 326 | position = this.getLength_() - this.canvas_.width; 327 | } 328 | let visibleStartTime = this.startTime_ + position * this.scale_; 329 | 330 | // Make space at the bottom of the graph for the time labels, and then 331 | // draw the labels. 332 | let textHeight = height; 333 | height -= fontHeight + LABEL_VERTICAL_SPACING; 334 | this.drawTimeLabels(context, width, height, textHeight, visibleStartTime); 335 | 336 | // Draw outline of the main graph area. 337 | context.strokeStyle = GRID_COLOR; 338 | context.strokeRect(0, 0, width - 1, height - 1); 339 | 340 | if (this.graph_) { 341 | // Layout graph and have them draw their tick marks. 342 | this.graph_.layout( 343 | width, height, fontHeight, visibleStartTime, this.scale_); 344 | this.graph_.drawTicks(context); 345 | 346 | // Draw the lines of all graphs, and then draw their labels. 347 | this.graph_.drawLines(context); 348 | this.graph_.drawLabels(context); 349 | } 350 | 351 | // Restore original transformation matrix. 352 | context.restore(); 353 | }, 354 | 355 | /** 356 | * Draw time labels below the graph. Takes in start time as an argument 357 | * since it may not be |startTime_|, when we're displaying the entire 358 | * time range. 359 | */ 360 | drawTimeLabels: function(context, width, height, textHeight, startTime) { 361 | // Draw the labels 1 minute apart. 362 | let timeStep = 1000 * 60; 363 | 364 | // Find the time for the first label. This time is a perfect multiple of 365 | // timeStep because of how UTC times work. 366 | let time = Math.ceil(startTime / timeStep) * timeStep; 367 | 368 | context.textBaseline = 'bottom'; 369 | context.textAlign = 'center'; 370 | context.fillStyle = TEXT_COLOR; 371 | context.strokeStyle = GRID_COLOR; 372 | 373 | // Draw labels and vertical grid lines. 374 | while (true) { 375 | let x = Math.round((time - startTime) / this.scale_); 376 | if (x >= width) { 377 | break; 378 | } 379 | let text = (new Date(time)).toLocaleTimeString(); 380 | context.fillText(text, x, textHeight); 381 | context.beginPath(); 382 | context.lineTo(x, 0); 383 | context.lineTo(x, height); 384 | context.stroke(); 385 | time += timeStep; 386 | } 387 | }, 388 | 389 | getDataSeriesCount: function() { 390 | if (this.graph_) { 391 | return this.graph_.dataSeries_.length; 392 | } 393 | return 0; 394 | }, 395 | 396 | hasDataSeries: function(dataSeries) { 397 | if (this.graph_) { 398 | return this.graph_.hasDataSeries(dataSeries); 399 | } 400 | return false; 401 | }, 402 | 403 | }; 404 | 405 | /** 406 | * A Graph is responsible for drawing all the TimelineDataSeries that have 407 | * the same data type. Graphs are responsible for scaling the values, laying 408 | * out labels, and drawing both labels and lines for its data series. 409 | */ 410 | const Graph = (function() { 411 | /** 412 | * @constructor 413 | */ 414 | function Graph() { 415 | this.dataSeries_ = []; 416 | 417 | // Cached properties of the graph, set in layout. 418 | this.width_ = 0; 419 | this.height_ = 0; 420 | this.fontHeight_ = 0; 421 | this.startTime_ = 0; 422 | this.scale_ = 0; 423 | 424 | // The lowest/highest values adjusted by the vertical label step size 425 | // in the displayed range of the graph. Used for scaling and setting 426 | // labels. Set in layoutLabels. 427 | this.min_ = 0; 428 | this.max_ = 0; 429 | 430 | // Cached text of equally spaced labels. Set in layoutLabels. 431 | this.labels_ = []; 432 | } 433 | 434 | /** 435 | * A Label is the label at a particular position along the y-axis. 436 | * @constructor 437 | */ 438 | /* 439 | function Label(height, text) { 440 | this.height = height; 441 | this.text = text; 442 | } 443 | */ 444 | 445 | Graph.prototype = { 446 | addDataSeries: function(dataSeries) { 447 | this.dataSeries_.push(dataSeries); 448 | }, 449 | 450 | hasDataSeries: function(dataSeries) { 451 | for (let i = 0; i < this.dataSeries_.length; ++i) { 452 | if (this.dataSeries_[i] === dataSeries) { 453 | return true; 454 | } 455 | } 456 | return false; 457 | }, 458 | 459 | /** 460 | * Returns a list of all the values that should be displayed for a given 461 | * data series, using the current graph layout. 462 | */ 463 | getValues: function(dataSeries) { 464 | if (!dataSeries.isVisible()) { 465 | return null; 466 | } 467 | return dataSeries.getValues(this.startTime_, this.scale_, this.width_); 468 | }, 469 | 470 | /** 471 | * Updates the graph's layout. In particular, both the max value and 472 | * label positions are updated. Must be called before calling any of the 473 | * drawing functions. 474 | */ 475 | layout: function(width, height, fontHeight, startTime, scale) { 476 | this.width_ = width; 477 | this.height_ = height; 478 | this.fontHeight_ = fontHeight; 479 | this.startTime_ = startTime; 480 | this.scale_ = scale; 481 | 482 | // Find largest value. 483 | let max = 0; 484 | let min = 0; 485 | for (let i = 0; i < this.dataSeries_.length; ++i) { 486 | let values = this.getValues(this.dataSeries_[i]); 487 | if (!values) { 488 | continue; 489 | } 490 | for (let j = 0; j < values.length; ++j) { 491 | if (values[j] > max) { 492 | max = values[j]; 493 | } else if (values[j] < min) { 494 | min = values[j]; 495 | } 496 | } 497 | } 498 | 499 | this.layoutLabels_(min, max); 500 | }, 501 | 502 | /** 503 | * Lays out labels and sets |max_|/|min_|, taking the time units into 504 | * consideration. |maxValue| is the actual maximum value, and 505 | * |max_| will be set to the value of the largest label, which 506 | * will be at least |maxValue|. Similar for |min_|. 507 | */ 508 | layoutLabels_: function(minValue, maxValue) { 509 | if (maxValue - minValue < 1024) { 510 | this.layoutLabelsBasic_(minValue, maxValue, MAX_DECIMAL_PRECISION); 511 | return; 512 | } 513 | 514 | // Find appropriate units to use. 515 | let units = ['', 'k', 'M', 'G', 'T', 'P']; 516 | // Units to use for labels. 0 is '1', 1 is K, etc. 517 | // We start with 1, and work our way up. 518 | let unit = 1; 519 | minValue /= 1024; 520 | maxValue /= 1024; 521 | while (units[unit + 1] && maxValue - minValue >= 1024) { 522 | minValue /= 1024; 523 | maxValue /= 1024; 524 | ++unit; 525 | } 526 | 527 | // Calculate labels. 528 | this.layoutLabelsBasic_(minValue, maxValue, MAX_DECIMAL_PRECISION); 529 | 530 | // Append units to labels. 531 | for (let i = 0; i < this.labels_.length; ++i) { 532 | this.labels_[i] += ' ' + units[unit]; 533 | } 534 | 535 | // Convert |min_|/|max_| back to unit '1'. 536 | this.min_ *= Math.pow(1024, unit); 537 | this.max_ *= Math.pow(1024, unit); 538 | }, 539 | 540 | /** 541 | * Same as layoutLabels_, but ignores units. |maxDecimalDigits| is the 542 | * maximum number of decimal digits allowed. The minimum allowed 543 | * difference between two adjacent labels is 10^-|maxDecimalDigits|. 544 | */ 545 | layoutLabelsBasic_: function(minValue, maxValue, maxDecimalDigits) { 546 | this.labels_ = []; 547 | let range = maxValue - minValue; 548 | // No labels if the range is 0. 549 | if (range === 0) { 550 | this.min_ = this.max_ = maxValue; 551 | return; 552 | } 553 | 554 | // The maximum number of equally spaced labels allowed. |fontHeight_| 555 | // is doubled because the top two labels are both drawn in the same 556 | // gap. 557 | let minLabelSpacing = 2 * this.fontHeight_ + LABEL_VERTICAL_SPACING; 558 | 559 | // The + 1 is for the top label. 560 | let maxLabels = 1 + this.height_ / minLabelSpacing; 561 | if (maxLabels < 2) { 562 | maxLabels = 2; 563 | } else if (maxLabels > MAX_VERTICAL_LABELS) { 564 | maxLabels = MAX_VERTICAL_LABELS; 565 | } 566 | 567 | // Initial try for step size between conecutive labels. 568 | let stepSize = Math.pow(10, -maxDecimalDigits); 569 | // Number of digits to the right of the decimal of |stepSize|. 570 | // Used for formating label strings. 571 | let stepSizeDecimalDigits = maxDecimalDigits; 572 | 573 | // Pick a reasonable step size. 574 | while (true) { 575 | // If we use a step size of |stepSize| between labels, we'll need: 576 | // 577 | // Math.ceil(range / stepSize) + 1 578 | // 579 | // labels. The + 1 is because we need labels at both at 0 and at 580 | // the top of the graph. 581 | 582 | // Check if we can use steps of size |stepSize|. 583 | if (Math.ceil(range / stepSize) + 1 <= maxLabels) { 584 | break; 585 | } 586 | // Check |stepSize| * 2. 587 | if (Math.ceil(range / (stepSize * 2)) + 1 <= maxLabels) { 588 | stepSize *= 2; 589 | break; 590 | } 591 | // Check |stepSize| * 5. 592 | if (Math.ceil(range / (stepSize * 5)) + 1 <= maxLabels) { 593 | stepSize *= 5; 594 | break; 595 | } 596 | stepSize *= 10; 597 | if (stepSizeDecimalDigits > 0) { 598 | --stepSizeDecimalDigits; 599 | } 600 | } 601 | 602 | // Set the min/max so it's an exact multiple of the chosen step size. 603 | this.max_ = Math.ceil(maxValue / stepSize) * stepSize; 604 | this.min_ = Math.floor(minValue / stepSize) * stepSize; 605 | 606 | // Create labels. 607 | for (let label = this.max_; label >= this.min_; label -= stepSize) { 608 | this.labels_.push(label.toFixed(stepSizeDecimalDigits)); 609 | } 610 | }, 611 | 612 | /** 613 | * Draws tick marks for each of the labels in |labels_|. 614 | */ 615 | drawTicks: function(context) { 616 | let x1; 617 | let x2; 618 | x1 = this.width_ - 1; 619 | x2 = this.width_ - 1 - Y_AXIS_TICK_LENGTH; 620 | 621 | context.fillStyle = GRID_COLOR; 622 | context.beginPath(); 623 | for (let i = 1; i < this.labels_.length - 1; ++i) { 624 | // The rounding is needed to avoid ugly 2-pixel wide anti-aliased 625 | // lines. 626 | let y = Math.round(this.height_ * i / (this.labels_.length - 1)); 627 | context.moveTo(x1, y); 628 | context.lineTo(x2, y); 629 | } 630 | context.stroke(); 631 | }, 632 | 633 | /** 634 | * Draws a graph line for each of the data series. 635 | */ 636 | drawLines: function(context) { 637 | // Factor by which to scale all values to convert them to a number from 638 | // 0 to height - 1. 639 | let scale = 0; 640 | let bottom = this.height_ - 1; 641 | if (this.max_) { 642 | scale = bottom / (this.max_ - this.min_); 643 | } 644 | 645 | // Draw in reverse order, so earlier data series are drawn on top of 646 | // subsequent ones. 647 | for (let i = this.dataSeries_.length - 1; i >= 0; --i) { 648 | let values = this.getValues(this.dataSeries_[i]); 649 | if (!values) { 650 | continue; 651 | } 652 | context.strokeStyle = this.dataSeries_[i].getColor(); 653 | context.beginPath(); 654 | for (let x = 0; x < values.length; ++x) { 655 | // The rounding is needed to avoid ugly 2-pixel wide anti-aliased 656 | // horizontal lines. 657 | context.lineTo( 658 | x, bottom - Math.round((values[x] - this.min_) * scale)); 659 | } 660 | context.stroke(); 661 | } 662 | }, 663 | 664 | /** 665 | * Draw labels in |labels_|. 666 | */ 667 | drawLabels: function(context) { 668 | if (this.labels_.length === 0) { 669 | return; 670 | } 671 | let x = this.width_ - LABEL_HORIZONTAL_SPACING; 672 | 673 | // Set up the context. 674 | context.fillStyle = TEXT_COLOR; 675 | context.textAlign = 'right'; 676 | 677 | // Draw top label, which is the only one that appears below its tick 678 | // mark. 679 | context.textBaseline = 'top'; 680 | context.fillText(this.labels_[0], x, 0); 681 | 682 | // Draw all the other labels. 683 | context.textBaseline = 'bottom'; 684 | let step = (this.height_ - 1) / (this.labels_.length - 1); 685 | for (let i = 1; i < this.labels_.length; ++i) { 686 | context.fillText(this.labels_[i], x, step * i); 687 | } 688 | } 689 | }; 690 | 691 | return Graph; 692 | })(); 693 | 694 | return TimelineGraphView; 695 | })(); 696 | -------------------------------------------------------------------------------- /19_chat/chat_new/server.js: -------------------------------------------------------------------------------- 1 | 'use strict' 2 | 3 | var log4js = require('log4js'); 4 | var http = require('http'); 5 | var https = require('https'); 6 | var fs = require('fs'); 7 | var socketIo = require('socket.io'); 8 | 9 | var express = require('express'); 10 | var serveIndex = require('serve-index'); 11 | 12 | var USERCOUNT = 3; 13 | 14 | log4js.configure({ 15 | appenders: { 16 | file: { 17 | type: 'file', 18 | filename: 'app.log', 19 | layout: { 20 | type: 'pattern', 21 | pattern: '%r %p - %m', 22 | } 23 | } 24 | }, 25 | categories: { 26 | default: { 27 | appenders: ['file'], 28 | level: 'debug' 29 | } 30 | } 31 | }); 32 | 33 | var logger = log4js.getLogger(); 34 | 35 | var app = express(); 36 | app.use(serveIndex('./public')); 37 | app.use(express.static('./public')); 38 | 39 | 40 | 41 | //http server 42 | var http_server = http.createServer(app); 43 | http_server.listen(80, '0.0.0.0'); 44 | 45 | var options = { 46 | key : fs.readFileSync('./cert/1557605_www.learningrtc.cn.key'), 47 | cert: fs.readFileSync('./cert/1557605_www.learningrtc.cn.pem') 48 | } 49 | 50 | //https server 51 | var https_server = https.createServer(options, app); 52 | var io = socketIo.listen(https_server); 53 | 54 | io.sockets.on('connection', (socket)=> { 55 | 56 | socket.on('message', (room, data)=>{ 57 | logger.debug('message, room: ' + room + ", data, type:" + data.type); 58 | socket.to(room).emit('message',room, data); 59 | }); 60 | 61 | /* 62 | socket.on('message', (room)=>{ 63 | logger.debug('message, room: ' + room ); 64 | socket.to(room).emit('message',room); 65 | }); 66 | */ 67 | 68 | socket.on('join', (room)=>{ 69 | socket.join(room); 70 | var myRoom = io.sockets.adapter.rooms[room]; 71 | var users = (myRoom)? Object.keys(myRoom.sockets).length : 0; 72 | logger.debug('the user number of room (' + room + ') is: ' + users); 73 | 74 | if(users < USERCOUNT){ 75 | socket.emit('joined', room, socket.id); //发给除自己之外的房间内的所有人 76 | if(users > 1){ 77 | socket.to(room).emit('otherjoin', room, socket.id); 78 | } 79 | 80 | }else{ 81 | socket.leave(room); 82 | socket.emit('full', room, socket.id); 83 | } 84 | //socket.emit('joined', room, socket.id); //发给自己 85 | //socket.broadcast.emit('joined', room, socket.id); //发给除自己之外的这个节点上的所有人 86 | //io.in(room).emit('joined', room, socket.id); //发给房间内的所有人 87 | }); 88 | 89 | socket.on('leave', (room)=>{ 90 | 91 | socket.leave(room); 92 | 93 | var myRoom = io.sockets.adapter.rooms[room]; 94 | var users = (myRoom)? Object.keys(myRoom.sockets).length : 0; 95 | logger.debug('the user number of room is: ' + users); 96 | 97 | //socket.emit('leaved', room, socket.id); 98 | //socket.broadcast.emit('leaved', room, socket.id); 99 | socket.to(room).emit('bye', room, socket.id); 100 | socket.emit('leaved', room, socket.id); 101 | //io.in(room).emit('leaved', room, socket.id); 102 | }); 103 | 104 | }); 105 | 106 | https_server.listen(443, '0.0.0.0'); 107 | 108 | 109 | 110 | 111 | -------------------------------------------------------------------------------- /23_living/css/main.css: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2015 The WebRTC project authors. All Rights Reserved. 3 | * 4 | * Use of this source code is governed by a BSD-style license 5 | * that can be found in the LICENSE file in the root of the source 6 | * tree. 7 | */ 8 | 9 | button { 10 | margin: 10px 20px 25px 0; 11 | vertical-align: top; 12 | width: 134px; 13 | } 14 | 15 | table { 16 | margin: 200px (50% - 100) 0 0; 17 | } 18 | 19 | textarea { 20 | color: #444; 21 | font-size: 0.9em; 22 | font-weight: 300; 23 | height: 20.0em; 24 | padding: 5px; 25 | width: calc(100% - 10px); 26 | } 27 | 28 | div#getUserMedia { 29 | padding: 0 0 8px 0; 30 | } 31 | 32 | div.input { 33 | display: inline-block; 34 | margin: 0 4px 0 0; 35 | vertical-align: top; 36 | width: 310px; 37 | } 38 | 39 | div.input > div { 40 | margin: 0 0 20px 0; 41 | vertical-align: top; 42 | } 43 | 44 | div.output { 45 | background-color: #eee; 46 | display: inline-block; 47 | font-family: 'Inconsolata', 'Courier New', monospace; 48 | font-size: 0.9em; 49 | padding: 10px 10px 10px 25px; 50 | position: relative; 51 | top: 10px; 52 | white-space: pre; 53 | width: 270px; 54 | } 55 | 56 | div#preview { 57 | border-bottom: 1px solid #eee; 58 | margin: 0 0 1em 0; 59 | padding: 0 0 0.5em 0; 60 | } 61 | 62 | div#preview > div { 63 | display: inline-block; 64 | vertical-align: top; 65 | width: calc(50% - 12px); 66 | } 67 | 68 | section#statistics div { 69 | display: inline-block; 70 | font-family: 'Inconsolata', 'Courier New', monospace; 71 | vertical-align: top; 72 | width: 308px; 73 | } 74 | 75 | section#statistics div#senderStats { 76 | margin: 0 20px 0 0; 77 | } 78 | 79 | section#constraints > div { 80 | margin: 0 0 20px 0; 81 | } 82 | 83 | h2 { 84 | margin: 0 0 1em 0; 85 | } 86 | 87 | 88 | section#constraints label { 89 | display: inline-block; 90 | width: 156px; 91 | } 92 | 93 | section { 94 | margin: 0 0 20px 0; 95 | padding: 0 0 15px 0; 96 | } 97 | 98 | video { 99 | background: #222; 100 | margin: 0 0 0 0; 101 | --width: 100%; 102 | width: var(--width); 103 | height: 225px; 104 | } 105 | 106 | @media screen and (max-width: 720px) { 107 | button { 108 | font-weight: 500; 109 | height: 56px; 110 | line-height: 1.3em; 111 | width: 90px; 112 | } 113 | 114 | div#getUserMedia { 115 | padding: 0 0 40px 0; 116 | } 117 | 118 | section#statistics div { 119 | width: calc(50% - 14px); 120 | } 121 | 122 | } 123 | -------------------------------------------------------------------------------- /23_living/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | really peer connection 4 | 5 | 15 | 16 | 17 | 18 | 22 | 25 |
19 | 20 | 21 |
23 | 24 |
26 | 27 | 28 | -------------------------------------------------------------------------------- /23_living/js/.main.js.swo: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/avdance/webrtc_web/3432c2e4a2f81c6503e423eef6d36c65a6870259/23_living/js/.main.js.swo -------------------------------------------------------------------------------- /23_living/js/.main.js.swp: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/avdance/webrtc_web/3432c2e4a2f81c6503e423eef6d36c65a6870259/23_living/js/.main.js.swp -------------------------------------------------------------------------------- /23_living/js/.main_base.js.swp: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/avdance/webrtc_web/3432c2e4a2f81c6503e423eef6d36c65a6870259/23_living/js/.main_base.js.swp -------------------------------------------------------------------------------- /23_living/js/main.js: -------------------------------------------------------------------------------- 1 | 'use strict' 2 | 3 | var localVideo = document.querySelector('video#localvideo'); 4 | var remoteVideo = document.querySelector('video#remotevideo'); 5 | 6 | var btnConn = document.querySelector('button#connserver'); 7 | var btnLeave = document.querySelector('button#leave'); 8 | 9 | var offer = document.querySelector('textarea#offer'); 10 | var answer = document.querySelector('textarea#answer'); 11 | 12 | var shareDeskBox = document.querySelector('input#shareDesk'); 13 | 14 | var pcConfig = { 15 | 'iceServers': [{ 16 | 'urls': 'turn:stun.al.learningrtc.cn:3478', 17 | 'credential': "mypasswd", 18 | 'username': "lichao" 19 | }] 20 | }; 21 | 22 | var localStream = null; 23 | var remoteStream = null; 24 | 25 | var pc = null; 26 | 27 | var roomid; 28 | var socket = null; 29 | 30 | var offerdesc = null; 31 | var state = 'init'; 32 | 33 | // 以下代码是从网上找的 34 | //========================================================================================= 35 | //如果返回的是false说明当前操作系统是手机端,如果返回的是true则说明当前的操作系统是电脑端 36 | 37 | function IsPC() { 38 | var userAgentInfo = navigator.userAgent; 39 | var Agents = ["Android", "iPhone","SymbianOS", "Windows Phone","iPad", "iPod"]; 40 | var flag = true; 41 | 42 | for (var v = 0; v < Agents.length; v++) { 43 | if (userAgentInfo.indexOf(Agents[v]) > 0) { 44 | flag = false; 45 | break; 46 | } 47 | } 48 | 49 | return flag; 50 | } 51 | 52 | //如果返回true 则说明是Android false是ios 53 | function is_android() { 54 | var u = navigator.userAgent, app = navigator.appVersion; 55 | var isAndroid = u.indexOf('Android') > -1 || u.indexOf('Linux') > -1; //g 56 | var isIOS = !!u.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/); //ios终端 57 | if (isAndroid) { 58 | //这个是安卓操作系统 59 | return true; 60 | } 61 | 62 | if (isIOS) { 63 |   //这个是ios操作系统 64 |    return false; 65 | } 66 | } 67 | 68 | //获取url参数 69 | function getQueryVariable(variable) 70 | { 71 | var query = window.location.search.substring(1); 72 | var vars = query.split("&"); 73 | for (var i=0;i { 96 | console.log('receive joined message!', roomid, id); 97 | state = 'joined' 98 | 99 | //如果是多人的话,第一个人不该在这里创建peerConnection 100 | //都等到收到一个otherjoin时再创建 101 | //所以,在这个消息里应该带当前房间的用户数 102 | // 103 | //create conn and bind media track 104 | createPeerConnection(); 105 | bindTracks(); 106 | 107 | btnConn.disabled = true; 108 | btnLeave.disabled = false; 109 | console.log('receive joined message, state=', state); 110 | }); 111 | 112 | socket.on('otherjoin', (roomid) => { 113 | console.log('receive joined message:', roomid, state); 114 | 115 | //如果是多人的话,每上来一个人都要创建一个新的 peerConnection 116 | // 117 | if(state === 'joined_unbind'){ 118 | createPeerConnection(); 119 | bindTracks(); 120 | } 121 | 122 | state = 'joined_conn'; 123 | call(); 124 | 125 | console.log('receive other_join message, state=', state); 126 | }); 127 | 128 | socket.on('full', (roomid, id) => { 129 | console.log('receive full message', roomid, id); 130 | socket.disconnect(); 131 | hangup(); 132 | closeLocalMedia(); 133 | state = 'leaved'; 134 | console.log('receive full message, state=', state); 135 | alert('the room is full!'); 136 | }); 137 | 138 | socket.on('leaved', (roomid, id) => { 139 | console.log('receive leaved message', roomid, id); 140 | state='leaved' 141 | socket.disconnect(); 142 | console.log('receive leaved message, state=', state); 143 | 144 | btnConn.disabled = false; 145 | btnLeave.disabled = true; 146 | }); 147 | 148 | socket.on('bye', (room, id) => { 149 | console.log('receive bye message', roomid, id); 150 | //state = 'created'; 151 | //当是多人通话时,应该带上当前房间的用户数 152 | //如果当前房间用户不小于 2, 则不用修改状态 153 | //并且,关闭的应该是对应用户的peerconnection 154 | //在客户端应该维护一张peerconnection表,它是 155 | //一个key:value的格式,key=userid, value=peerconnection 156 | state = 'joined_unbind'; 157 | hangup(); 158 | offer.value = ''; 159 | answer.value = ''; 160 | console.log('receive bye message, state=', state); 161 | }); 162 | 163 | socket.on('disconnect', (socket) => { 164 | console.log('receive disconnect message!', roomid); 165 | if(!(state === 'leaved')){ 166 | hangup(); 167 | closeLocalMedia(); 168 | 169 | } 170 | state = 'leaved'; 171 | 172 | }); 173 | 174 | socket.on('message', (roomid, data) => { 175 | console.log('receive message!', roomid, data); 176 | 177 | if(data === null || data === undefined){ 178 | console.error('the message is invalid!'); 179 | return; 180 | } 181 | 182 | if(data.hasOwnProperty('type') && data.type === 'offer') { 183 | 184 | offer.value = data.sdp; 185 | 186 | pc.setRemoteDescription(new RTCSessionDescription(data)); 187 | 188 | //create answer 189 | pc.createAnswer() 190 | .then(getAnswer) 191 | .catch(handleAnswerError); 192 | 193 | }else if(data.hasOwnProperty('type') && data.type == 'answer'){ 194 | answer.value = data.sdp; 195 | pc.setRemoteDescription(new RTCSessionDescription(data)); 196 | 197 | }else if (data.hasOwnProperty('type') && data.type === 'candidate'){ 198 | var candidate = new RTCIceCandidate({ 199 | sdpMLineIndex: data.label, 200 | candidate: data.candidate 201 | }); 202 | pc.addIceCandidate(candidate); 203 | 204 | }else{ 205 | console.log('the message is invalid!', data); 206 | 207 | } 208 | 209 | }); 210 | 211 | 212 | roomid = getQueryVariable('room'); 213 | socket.emit('join', roomid); 214 | 215 | return true; 216 | } 217 | 218 | function connSignalServer(){ 219 | 220 | //开启本地视频 221 | start(); 222 | 223 | return true; 224 | } 225 | 226 | function getMediaStream(stream){ 227 | 228 | if(localStream){ 229 | stream.getAudioTracks().forEach((track)=>{ 230 | localStream.addTrack(track); 231 | stream.removeTrack(track); 232 | }); 233 | }else{ 234 | localStream = stream; 235 | } 236 | 237 | localVideo.srcObject = localStream; 238 | 239 | //这个函数的位置特别重要, 240 | //一定要放到getMediaStream之后再调用 241 | //否则就会出现绑定失败的情况 242 | // 243 | //setup connection 244 | conn(); 245 | 246 | //btnStart.disabled = true; 247 | //btnCall.disabled = true; 248 | //btnHangup.disabled = true; 249 | } 250 | 251 | function getDeskStream(stream){ 252 | localStream = stream; 253 | } 254 | 255 | function handleError(err){ 256 | console.error('Failed to get Media Stream!', err); 257 | } 258 | 259 | function shareDesk(){ 260 | 261 | if(IsPC()){ 262 | navigator.mediaDevices.getDisplayMedia({video: true}) 263 | .then(getDeskStream) 264 | .catch(handleError); 265 | 266 | return true; 267 | } 268 | 269 | return false; 270 | 271 | } 272 | 273 | function start(){ 274 | 275 | if(!navigator.mediaDevices || 276 | !navigator.mediaDevices.getUserMedia){ 277 | console.error('the getUserMedia is not supported!'); 278 | return; 279 | }else { 280 | 281 | var constraints; 282 | 283 | if( shareDeskBox.checked && shareDesk()){ 284 | 285 | constraints = { 286 | video: false, 287 | audio: { 288 | echoCancellation: true, 289 | noiseSuppression: true, 290 | autoGainControl: true 291 | } 292 | } 293 | 294 | }else{ 295 | constraints = { 296 | video: { 297 | width:640, 298 | height:480 299 | }, 300 | audio: { 301 | echoCancellation: true, 302 | noiseSuppression: true, 303 | autoGainControl: true 304 | } 305 | } 306 | } 307 | 308 | navigator.mediaDevices.getUserMedia(constraints) 309 | .then(getMediaStream) 310 | .catch(handleError); 311 | } 312 | 313 | } 314 | 315 | function getRemoteStream(e){ 316 | remoteStream = e.streams[0]; 317 | remoteVideo.srcObject = e.streams[0]; 318 | } 319 | 320 | function handleOfferError(err){ 321 | console.error('Failed to create offer:', err); 322 | } 323 | 324 | function handleAnswerError(err){ 325 | console.error('Failed to create answer:', err); 326 | } 327 | 328 | function getAnswer(desc){ 329 | pc.setLocalDescription(desc); 330 | answer.value = desc.sdp; 331 | 332 | //send answer sdp 333 | sendMessage(roomid, desc); 334 | } 335 | 336 | function getOffer(desc){ 337 | pc.setLocalDescription(desc); 338 | offer.value = desc.sdp; 339 | offerdesc = desc; 340 | 341 | //send offer sdp 342 | sendMessage(roomid, offerdesc); 343 | 344 | } 345 | 346 | function createPeerConnection(){ 347 | 348 | //如果是多人的话,在这里要创建一个新的连接. 349 | //新创建好的要放到一个map表中。 350 | //key=userid, value=peerconnection 351 | console.log('create RTCPeerConnection!'); 352 | if(!pc){ 353 | pc = new RTCPeerConnection(pcConfig); 354 | 355 | pc.onicecandidate = (e)=>{ 356 | 357 | if(e.candidate) { 358 | sendMessage(roomid, { 359 | type: 'candidate', 360 | label:event.candidate.sdpMLineIndex, 361 | id:event.candidate.sdpMid, 362 | candidate: event.candidate.candidate 363 | }); 364 | }else{ 365 | console.log('this is the end candidate'); 366 | } 367 | } 368 | 369 | pc.ontrack = getRemoteStream; 370 | }else { 371 | console.log('the pc have be created!'); 372 | } 373 | 374 | return; 375 | } 376 | 377 | //绑定永远与 peerconnection在一起, 378 | //所以没必要再单独做成一个函数 379 | function bindTracks(){ 380 | 381 | console.log('bind tracks into RTCPeerConnection!'); 382 | 383 | if( pc === null || localStream === undefined) { 384 | console.error('pc is null or undefined!'); 385 | return; 386 | } 387 | 388 | if(localStream === null || localStream === undefined) { 389 | console.error('localstream is null or undefined!'); 390 | return; 391 | } 392 | 393 | //add all track into peer connection 394 | localStream.getTracks().forEach((track)=>{ 395 | pc.addTrack(track, localStream); 396 | }); 397 | 398 | } 399 | 400 | function call(){ 401 | 402 | if(state === 'joined_conn'){ 403 | 404 | var offerOptions = { 405 | offerToRecieveAudio: 1, 406 | offerToRecieveVideo: 1 407 | } 408 | 409 | pc.createOffer(offerOptions) 410 | .then(getOffer) 411 | .catch(handleOfferError); 412 | } 413 | } 414 | 415 | function hangup(){ 416 | 417 | if(!pc) { 418 | return; 419 | } 420 | 421 | offerdesc = null; 422 | 423 | pc.close(); 424 | pc = null; 425 | 426 | } 427 | 428 | function closeLocalMedia(){ 429 | 430 | if(!(localStream === null || localStream === undefined)){ 431 | localStream.getTracks().forEach((track)=>{ 432 | track.stop(); 433 | }); 434 | } 435 | localStream = null; 436 | } 437 | 438 | function leave() { 439 | 440 | socket.emit('leave', roomid); //notify server 441 | 442 | hangup(); 443 | closeLocalMedia(); 444 | 445 | offer.value = ''; 446 | answer.value = ''; 447 | btnConn.disabled = false; 448 | btnLeave.disabled = true; 449 | } 450 | 451 | btnConn.onclick = connSignalServer 452 | btnLeave.onclick = leave; 453 | -------------------------------------------------------------------------------- /23_living/room.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | WebRTC PeerConnection 4 | 5 | 6 | 7 | 8 |
9 | 10 | 11 |
12 | 13 | 17 | 18 |
19 | 20 |
21 | 22 |
23 | 24 | 25 |
26 |
27 |

Local:

28 | 29 |

Offer SDP:

30 | 31 |
32 |
33 |

Remote:

34 | 35 |

Answer SDP:

36 | 37 |
38 |
39 |
40 | 41 | 42 | 43 | 44 | 45 | 46 | -------------------------------------------------------------------------------- /23_living/server.js: -------------------------------------------------------------------------------- 1 | 'use strict' 2 | 3 | var log4js = require('log4js'); 4 | var http = require('http'); 5 | var https = require('https'); 6 | var fs = require('fs'); 7 | var socketIo = require('socket.io'); 8 | 9 | var express = require('express'); 10 | var serveIndex = require('serve-index'); 11 | 12 | var USERCOUNT = 3; 13 | 14 | log4js.configure({ 15 | appenders: { 16 | file: { 17 | type: 'file', 18 | filename: 'app.log', 19 | layout: { 20 | type: 'pattern', 21 | pattern: '%r %p - %m', 22 | } 23 | } 24 | }, 25 | categories: { 26 | default: { 27 | appenders: ['file'], 28 | level: 'debug' 29 | } 30 | } 31 | }); 32 | 33 | var logger = log4js.getLogger(); 34 | 35 | var app = express(); 36 | app.use(serveIndex('./public')); 37 | app.use(express.static('./public')); 38 | 39 | 40 | 41 | //http server 42 | var http_server = http.createServer(app); 43 | http_server.listen(80, '0.0.0.0'); 44 | 45 | var options = { 46 | key : fs.readFileSync('./cert/1557605_www.learningrtc.cn.key'), 47 | cert: fs.readFileSync('./cert/1557605_www.learningrtc.cn.pem') 48 | } 49 | 50 | //https server 51 | var https_server = https.createServer(options, app); 52 | var io = socketIo.listen(https_server); 53 | 54 | io.sockets.on('connection', (socket)=> { 55 | 56 | socket.on('message', (room, data)=>{ 57 | logger.debug('message, room: ' + room + ", data, type:" + data.type); 58 | socket.to(room).emit('message',room, data); 59 | }); 60 | 61 | /* 62 | socket.on('message', (room)=>{ 63 | logger.debug('message, room: ' + room ); 64 | socket.to(room).emit('message',room); 65 | }); 66 | */ 67 | 68 | socket.on('join', (room)=>{ 69 | socket.join(room); 70 | var myRoom = io.sockets.adapter.rooms[room]; 71 | var users = (myRoom)? Object.keys(myRoom.sockets).length : 0; 72 | logger.debug('the user number of room (' + room + ') is: ' + users); 73 | 74 | if(users < USERCOUNT){ 75 | socket.emit('joined', room, socket.id); //发给除自己之外的房间内的所有人 76 | if(users > 1){ 77 | socket.to(room).emit('otherjoin', room, socket.id); 78 | } 79 | 80 | }else{ 81 | socket.leave(room); 82 | socket.emit('full', room, socket.id); 83 | } 84 | //socket.emit('joined', room, socket.id); //发给自己 85 | //socket.broadcast.emit('joined', room, socket.id); //发给除自己之外的这个节点上的所有人 86 | //io.in(room).emit('joined', room, socket.id); //发给房间内的所有人 87 | }); 88 | 89 | socket.on('leave', (room)=>{ 90 | 91 | socket.leave(room); 92 | 93 | var myRoom = io.sockets.adapter.rooms[room]; 94 | var users = (myRoom)? Object.keys(myRoom.sockets).length : 0; 95 | logger.debug('the user number of room is: ' + users); 96 | 97 | //socket.emit('leaved', room, socket.id); 98 | //socket.broadcast.emit('leaved', room, socket.id); 99 | socket.to(room).emit('bye', room, socket.id); 100 | socket.emit('leaved', room, socket.id); 101 | //io.in(room).emit('leaved', room, socket.id); 102 | }); 103 | 104 | }); 105 | 106 | https_server.listen(443, '0.0.0.0'); 107 | 108 | 109 | 110 | 111 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 3, 29 June 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU General Public License is a free, copyleft license for 11 | software and other kinds of works. 12 | 13 | The licenses for most software and other practical works are designed 14 | to take away your freedom to share and change the works. By contrast, 15 | the GNU General Public License is intended to guarantee your freedom to 16 | share and change all versions of a program--to make sure it remains free 17 | software for all its users. We, the Free Software Foundation, use the 18 | GNU General Public License for most of our software; it applies also to 19 | any other work released this way by its authors. You can apply it to 20 | your programs, too. 21 | 22 | When we speak of free software, we are referring to freedom, not 23 | price. Our General Public Licenses are designed to make sure that you 24 | have the freedom to distribute copies of free software (and charge for 25 | them if you wish), that you receive source code or can get it if you 26 | want it, that you can change the software or use pieces of it in new 27 | free programs, and that you know you can do these things. 28 | 29 | To protect your rights, we need to prevent others from denying you 30 | these rights or asking you to surrender the rights. Therefore, you have 31 | certain responsibilities if you distribute copies of the software, or if 32 | you modify it: responsibilities to respect the freedom of others. 33 | 34 | For example, if you distribute copies of such a program, whether 35 | gratis or for a fee, you must pass on to the recipients the same 36 | freedoms that you received. You must make sure that they, too, receive 37 | or can get the source code. And you must show them these terms so they 38 | know their rights. 39 | 40 | Developers that use the GNU GPL protect your rights with two steps: 41 | (1) assert copyright on the software, and (2) offer you this License 42 | giving you legal permission to copy, distribute and/or modify it. 43 | 44 | For the developers' and authors' protection, the GPL clearly explains 45 | that there is no warranty for this free software. For both users' and 46 | authors' sake, the GPL requires that modified versions be marked as 47 | changed, so that their problems will not be attributed erroneously to 48 | authors of previous versions. 49 | 50 | Some devices are designed to deny users access to install or run 51 | modified versions of the software inside them, although the manufacturer 52 | can do so. This is fundamentally incompatible with the aim of 53 | protecting users' freedom to change the software. The systematic 54 | pattern of such abuse occurs in the area of products for individuals to 55 | use, which is precisely where it is most unacceptable. Therefore, we 56 | have designed this version of the GPL to prohibit the practice for those 57 | products. If such problems arise substantially in other domains, we 58 | stand ready to extend this provision to those domains in future versions 59 | of the GPL, as needed to protect the freedom of users. 60 | 61 | Finally, every program is threatened constantly by software patents. 62 | States should not allow patents to restrict development and use of 63 | software on general-purpose computers, but in those that do, we wish to 64 | avoid the special danger that patents applied to a free program could 65 | make it effectively proprietary. To prevent this, the GPL assures that 66 | patents cannot be used to render the program non-free. 67 | 68 | The precise terms and conditions for copying, distribution and 69 | modification follow. 70 | 71 | TERMS AND CONDITIONS 72 | 73 | 0. Definitions. 74 | 75 | "This License" refers to version 3 of the GNU General Public License. 76 | 77 | "Copyright" also means copyright-like laws that apply to other kinds of 78 | works, such as semiconductor masks. 79 | 80 | "The Program" refers to any copyrightable work licensed under this 81 | License. Each licensee is addressed as "you". "Licensees" and 82 | "recipients" may be individuals or organizations. 83 | 84 | To "modify" a work means to copy from or adapt all or part of the work 85 | in a fashion requiring copyright permission, other than the making of an 86 | exact copy. The resulting work is called a "modified version" of the 87 | earlier work or a work "based on" the earlier work. 88 | 89 | A "covered work" means either the unmodified Program or a work based 90 | on the Program. 91 | 92 | To "propagate" a work means to do anything with it that, without 93 | permission, would make you directly or secondarily liable for 94 | infringement under applicable copyright law, except executing it on a 95 | computer or modifying a private copy. Propagation includes copying, 96 | distribution (with or without modification), making available to the 97 | public, and in some countries other activities as well. 98 | 99 | To "convey" a work means any kind of propagation that enables other 100 | parties to make or receive copies. Mere interaction with a user through 101 | a computer network, with no transfer of a copy, is not conveying. 102 | 103 | An interactive user interface displays "Appropriate Legal Notices" 104 | to the extent that it includes a convenient and prominently visible 105 | feature that (1) displays an appropriate copyright notice, and (2) 106 | tells the user that there is no warranty for the work (except to the 107 | extent that warranties are provided), that licensees may convey the 108 | work under this License, and how to view a copy of this License. If 109 | the interface presents a list of user commands or options, such as a 110 | menu, a prominent item in the list meets this criterion. 111 | 112 | 1. Source Code. 113 | 114 | The "source code" for a work means the preferred form of the work 115 | for making modifications to it. "Object code" means any non-source 116 | form of a work. 117 | 118 | A "Standard Interface" means an interface that either is an official 119 | standard defined by a recognized standards body, or, in the case of 120 | interfaces specified for a particular programming language, one that 121 | is widely used among developers working in that language. 122 | 123 | The "System Libraries" of an executable work include anything, other 124 | than the work as a whole, that (a) is included in the normal form of 125 | packaging a Major Component, but which is not part of that Major 126 | Component, and (b) serves only to enable use of the work with that 127 | Major Component, or to implement a Standard Interface for which an 128 | implementation is available to the public in source code form. A 129 | "Major Component", in this context, means a major essential component 130 | (kernel, window system, and so on) of the specific operating system 131 | (if any) on which the executable work runs, or a compiler used to 132 | produce the work, or an object code interpreter used to run it. 133 | 134 | The "Corresponding Source" for a work in object code form means all 135 | the source code needed to generate, install, and (for an executable 136 | work) run the object code and to modify the work, including scripts to 137 | control those activities. However, it does not include the work's 138 | System Libraries, or general-purpose tools or generally available free 139 | programs which are used unmodified in performing those activities but 140 | which are not part of the work. For example, Corresponding Source 141 | includes interface definition files associated with source files for 142 | the work, and the source code for shared libraries and dynamically 143 | linked subprograms that the work is specifically designed to require, 144 | such as by intimate data communication or control flow between those 145 | subprograms and other parts of the work. 146 | 147 | The Corresponding Source need not include anything that users 148 | can regenerate automatically from other parts of the Corresponding 149 | Source. 150 | 151 | The Corresponding Source for a work in source code form is that 152 | same work. 153 | 154 | 2. Basic Permissions. 155 | 156 | All rights granted under this License are granted for the term of 157 | copyright on the Program, and are irrevocable provided the stated 158 | conditions are met. This License explicitly affirms your unlimited 159 | permission to run the unmodified Program. The output from running a 160 | covered work is covered by this License only if the output, given its 161 | content, constitutes a covered work. This License acknowledges your 162 | rights of fair use or other equivalent, as provided by copyright law. 163 | 164 | You may make, run and propagate covered works that you do not 165 | convey, without conditions so long as your license otherwise remains 166 | in force. You may convey covered works to others for the sole purpose 167 | of having them make modifications exclusively for you, or provide you 168 | with facilities for running those works, provided that you comply with 169 | the terms of this License in conveying all material for which you do 170 | not control copyright. Those thus making or running the covered works 171 | for you must do so exclusively on your behalf, under your direction 172 | and control, on terms that prohibit them from making any copies of 173 | your copyrighted material outside their relationship with you. 174 | 175 | Conveying under any other circumstances is permitted solely under 176 | the conditions stated below. Sublicensing is not allowed; section 10 177 | makes it unnecessary. 178 | 179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 180 | 181 | No covered work shall be deemed part of an effective technological 182 | measure under any applicable law fulfilling obligations under article 183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 184 | similar laws prohibiting or restricting circumvention of such 185 | measures. 186 | 187 | When you convey a covered work, you waive any legal power to forbid 188 | circumvention of technological measures to the extent such circumvention 189 | is effected by exercising rights under this License with respect to 190 | the covered work, and you disclaim any intention to limit operation or 191 | modification of the work as a means of enforcing, against the work's 192 | users, your or third parties' legal rights to forbid circumvention of 193 | technological measures. 194 | 195 | 4. Conveying Verbatim Copies. 196 | 197 | You may convey verbatim copies of the Program's source code as you 198 | receive it, in any medium, provided that you conspicuously and 199 | appropriately publish on each copy an appropriate copyright notice; 200 | keep intact all notices stating that this License and any 201 | non-permissive terms added in accord with section 7 apply to the code; 202 | keep intact all notices of the absence of any warranty; and give all 203 | recipients a copy of this License along with the Program. 204 | 205 | You may charge any price or no price for each copy that you convey, 206 | and you may offer support or warranty protection for a fee. 207 | 208 | 5. Conveying Modified Source Versions. 209 | 210 | You may convey a work based on the Program, or the modifications to 211 | produce it from the Program, in the form of source code under the 212 | terms of section 4, provided that you also meet all of these conditions: 213 | 214 | a) The work must carry prominent notices stating that you modified 215 | it, and giving a relevant date. 216 | 217 | b) The work must carry prominent notices stating that it is 218 | released under this License and any conditions added under section 219 | 7. This requirement modifies the requirement in section 4 to 220 | "keep intact all notices". 221 | 222 | c) You must license the entire work, as a whole, under this 223 | License to anyone who comes into possession of a copy. This 224 | License will therefore apply, along with any applicable section 7 225 | additional terms, to the whole of the work, and all its parts, 226 | regardless of how they are packaged. This License gives no 227 | permission to license the work in any other way, but it does not 228 | invalidate such permission if you have separately received it. 229 | 230 | d) If the work has interactive user interfaces, each must display 231 | Appropriate Legal Notices; however, if the Program has interactive 232 | interfaces that do not display Appropriate Legal Notices, your 233 | work need not make them do so. 234 | 235 | A compilation of a covered work with other separate and independent 236 | works, which are not by their nature extensions of the covered work, 237 | and which are not combined with it such as to form a larger program, 238 | in or on a volume of a storage or distribution medium, is called an 239 | "aggregate" if the compilation and its resulting copyright are not 240 | used to limit the access or legal rights of the compilation's users 241 | beyond what the individual works permit. Inclusion of a covered work 242 | in an aggregate does not cause this License to apply to the other 243 | parts of the aggregate. 244 | 245 | 6. Conveying Non-Source Forms. 246 | 247 | You may convey a covered work in object code form under the terms 248 | of sections 4 and 5, provided that you also convey the 249 | machine-readable Corresponding Source under the terms of this License, 250 | in one of these ways: 251 | 252 | a) Convey the object code in, or embodied in, a physical product 253 | (including a physical distribution medium), accompanied by the 254 | Corresponding Source fixed on a durable physical medium 255 | customarily used for software interchange. 256 | 257 | b) Convey the object code in, or embodied in, a physical product 258 | (including a physical distribution medium), accompanied by a 259 | written offer, valid for at least three years and valid for as 260 | long as you offer spare parts or customer support for that product 261 | model, to give anyone who possesses the object code either (1) a 262 | copy of the Corresponding Source for all the software in the 263 | product that is covered by this License, on a durable physical 264 | medium customarily used for software interchange, for a price no 265 | more than your reasonable cost of physically performing this 266 | conveying of source, or (2) access to copy the 267 | Corresponding Source from a network server at no charge. 268 | 269 | c) Convey individual copies of the object code with a copy of the 270 | written offer to provide the Corresponding Source. This 271 | alternative is allowed only occasionally and noncommercially, and 272 | only if you received the object code with such an offer, in accord 273 | with subsection 6b. 274 | 275 | d) Convey the object code by offering access from a designated 276 | place (gratis or for a charge), and offer equivalent access to the 277 | Corresponding Source in the same way through the same place at no 278 | further charge. You need not require recipients to copy the 279 | Corresponding Source along with the object code. If the place to 280 | copy the object code is a network server, the Corresponding Source 281 | may be on a different server (operated by you or a third party) 282 | that supports equivalent copying facilities, provided you maintain 283 | clear directions next to the object code saying where to find the 284 | Corresponding Source. Regardless of what server hosts the 285 | Corresponding Source, you remain obligated to ensure that it is 286 | available for as long as needed to satisfy these requirements. 287 | 288 | e) Convey the object code using peer-to-peer transmission, provided 289 | you inform other peers where the object code and Corresponding 290 | Source of the work are being offered to the general public at no 291 | charge under subsection 6d. 292 | 293 | A separable portion of the object code, whose source code is excluded 294 | from the Corresponding Source as a System Library, need not be 295 | included in conveying the object code work. 296 | 297 | A "User Product" is either (1) a "consumer product", which means any 298 | tangible personal property which is normally used for personal, family, 299 | or household purposes, or (2) anything designed or sold for incorporation 300 | into a dwelling. In determining whether a product is a consumer product, 301 | doubtful cases shall be resolved in favor of coverage. For a particular 302 | product received by a particular user, "normally used" refers to a 303 | typical or common use of that class of product, regardless of the status 304 | of the particular user or of the way in which the particular user 305 | actually uses, or expects or is expected to use, the product. A product 306 | is a consumer product regardless of whether the product has substantial 307 | commercial, industrial or non-consumer uses, unless such uses represent 308 | the only significant mode of use of the product. 309 | 310 | "Installation Information" for a User Product means any methods, 311 | procedures, authorization keys, or other information required to install 312 | and execute modified versions of a covered work in that User Product from 313 | a modified version of its Corresponding Source. The information must 314 | suffice to ensure that the continued functioning of the modified object 315 | code is in no case prevented or interfered with solely because 316 | modification has been made. 317 | 318 | If you convey an object code work under this section in, or with, or 319 | specifically for use in, a User Product, and the conveying occurs as 320 | part of a transaction in which the right of possession and use of the 321 | User Product is transferred to the recipient in perpetuity or for a 322 | fixed term (regardless of how the transaction is characterized), the 323 | Corresponding Source conveyed under this section must be accompanied 324 | by the Installation Information. But this requirement does not apply 325 | if neither you nor any third party retains the ability to install 326 | modified object code on the User Product (for example, the work has 327 | been installed in ROM). 328 | 329 | The requirement to provide Installation Information does not include a 330 | requirement to continue to provide support service, warranty, or updates 331 | for a work that has been modified or installed by the recipient, or for 332 | the User Product in which it has been modified or installed. Access to a 333 | network may be denied when the modification itself materially and 334 | adversely affects the operation of the network or violates the rules and 335 | protocols for communication across the network. 336 | 337 | Corresponding Source conveyed, and Installation Information provided, 338 | in accord with this section must be in a format that is publicly 339 | documented (and with an implementation available to the public in 340 | source code form), and must require no special password or key for 341 | unpacking, reading or copying. 342 | 343 | 7. Additional Terms. 344 | 345 | "Additional permissions" are terms that supplement the terms of this 346 | License by making exceptions from one or more of its conditions. 347 | Additional permissions that are applicable to the entire Program shall 348 | be treated as though they were included in this License, to the extent 349 | that they are valid under applicable law. If additional permissions 350 | apply only to part of the Program, that part may be used separately 351 | under those permissions, but the entire Program remains governed by 352 | this License without regard to the additional permissions. 353 | 354 | When you convey a copy of a covered work, you may at your option 355 | remove any additional permissions from that copy, or from any part of 356 | it. (Additional permissions may be written to require their own 357 | removal in certain cases when you modify the work.) You may place 358 | additional permissions on material, added by you to a covered work, 359 | for which you have or can give appropriate copyright permission. 360 | 361 | Notwithstanding any other provision of this License, for material you 362 | add to a covered work, you may (if authorized by the copyright holders of 363 | that material) supplement the terms of this License with terms: 364 | 365 | a) Disclaiming warranty or limiting liability differently from the 366 | terms of sections 15 and 16 of this License; or 367 | 368 | b) Requiring preservation of specified reasonable legal notices or 369 | author attributions in that material or in the Appropriate Legal 370 | Notices displayed by works containing it; or 371 | 372 | c) Prohibiting misrepresentation of the origin of that material, or 373 | requiring that modified versions of such material be marked in 374 | reasonable ways as different from the original version; or 375 | 376 | d) Limiting the use for publicity purposes of names of licensors or 377 | authors of the material; or 378 | 379 | e) Declining to grant rights under trademark law for use of some 380 | trade names, trademarks, or service marks; or 381 | 382 | f) Requiring indemnification of licensors and authors of that 383 | material by anyone who conveys the material (or modified versions of 384 | it) with contractual assumptions of liability to the recipient, for 385 | any liability that these contractual assumptions directly impose on 386 | those licensors and authors. 387 | 388 | All other non-permissive additional terms are considered "further 389 | restrictions" within the meaning of section 10. If the Program as you 390 | received it, or any part of it, contains a notice stating that it is 391 | governed by this License along with a term that is a further 392 | restriction, you may remove that term. If a license document contains 393 | a further restriction but permits relicensing or conveying under this 394 | License, you may add to a covered work material governed by the terms 395 | of that license document, provided that the further restriction does 396 | not survive such relicensing or conveying. 397 | 398 | If you add terms to a covered work in accord with this section, you 399 | must place, in the relevant source files, a statement of the 400 | additional terms that apply to those files, or a notice indicating 401 | where to find the applicable terms. 402 | 403 | Additional terms, permissive or non-permissive, may be stated in the 404 | form of a separately written license, or stated as exceptions; 405 | the above requirements apply either way. 406 | 407 | 8. Termination. 408 | 409 | You may not propagate or modify a covered work except as expressly 410 | provided under this License. Any attempt otherwise to propagate or 411 | modify it is void, and will automatically terminate your rights under 412 | this License (including any patent licenses granted under the third 413 | paragraph of section 11). 414 | 415 | However, if you cease all violation of this License, then your 416 | license from a particular copyright holder is reinstated (a) 417 | provisionally, unless and until the copyright holder explicitly and 418 | finally terminates your license, and (b) permanently, if the copyright 419 | holder fails to notify you of the violation by some reasonable means 420 | prior to 60 days after the cessation. 421 | 422 | Moreover, your license from a particular copyright holder is 423 | reinstated permanently if the copyright holder notifies you of the 424 | violation by some reasonable means, this is the first time you have 425 | received notice of violation of this License (for any work) from that 426 | copyright holder, and you cure the violation prior to 30 days after 427 | your receipt of the notice. 428 | 429 | Termination of your rights under this section does not terminate the 430 | licenses of parties who have received copies or rights from you under 431 | this License. If your rights have been terminated and not permanently 432 | reinstated, you do not qualify to receive new licenses for the same 433 | material under section 10. 434 | 435 | 9. Acceptance Not Required for Having Copies. 436 | 437 | You are not required to accept this License in order to receive or 438 | run a copy of the Program. Ancillary propagation of a covered work 439 | occurring solely as a consequence of using peer-to-peer transmission 440 | to receive a copy likewise does not require acceptance. However, 441 | nothing other than this License grants you permission to propagate or 442 | modify any covered work. These actions infringe copyright if you do 443 | not accept this License. Therefore, by modifying or propagating a 444 | covered work, you indicate your acceptance of this License to do so. 445 | 446 | 10. Automatic Licensing of Downstream Recipients. 447 | 448 | Each time you convey a covered work, the recipient automatically 449 | receives a license from the original licensors, to run, modify and 450 | propagate that work, subject to this License. You are not responsible 451 | for enforcing compliance by third parties with this License. 452 | 453 | An "entity transaction" is a transaction transferring control of an 454 | organization, or substantially all assets of one, or subdividing an 455 | organization, or merging organizations. If propagation of a covered 456 | work results from an entity transaction, each party to that 457 | transaction who receives a copy of the work also receives whatever 458 | licenses to the work the party's predecessor in interest had or could 459 | give under the previous paragraph, plus a right to possession of the 460 | Corresponding Source of the work from the predecessor in interest, if 461 | the predecessor has it or can get it with reasonable efforts. 462 | 463 | You may not impose any further restrictions on the exercise of the 464 | rights granted or affirmed under this License. For example, you may 465 | not impose a license fee, royalty, or other charge for exercise of 466 | rights granted under this License, and you may not initiate litigation 467 | (including a cross-claim or counterclaim in a lawsuit) alleging that 468 | any patent claim is infringed by making, using, selling, offering for 469 | sale, or importing the Program or any portion of it. 470 | 471 | 11. Patents. 472 | 473 | A "contributor" is a copyright holder who authorizes use under this 474 | License of the Program or a work on which the Program is based. The 475 | work thus licensed is called the contributor's "contributor version". 476 | 477 | A contributor's "essential patent claims" are all patent claims 478 | owned or controlled by the contributor, whether already acquired or 479 | hereafter acquired, that would be infringed by some manner, permitted 480 | by this License, of making, using, or selling its contributor version, 481 | but do not include claims that would be infringed only as a 482 | consequence of further modification of the contributor version. For 483 | purposes of this definition, "control" includes the right to grant 484 | patent sublicenses in a manner consistent with the requirements of 485 | this License. 486 | 487 | Each contributor grants you a non-exclusive, worldwide, royalty-free 488 | patent license under the contributor's essential patent claims, to 489 | make, use, sell, offer for sale, import and otherwise run, modify and 490 | propagate the contents of its contributor version. 491 | 492 | In the following three paragraphs, a "patent license" is any express 493 | agreement or commitment, however denominated, not to enforce a patent 494 | (such as an express permission to practice a patent or covenant not to 495 | sue for patent infringement). To "grant" such a patent license to a 496 | party means to make such an agreement or commitment not to enforce a 497 | patent against the party. 498 | 499 | If you convey a covered work, knowingly relying on a patent license, 500 | and the Corresponding Source of the work is not available for anyone 501 | to copy, free of charge and under the terms of this License, through a 502 | publicly available network server or other readily accessible means, 503 | then you must either (1) cause the Corresponding Source to be so 504 | available, or (2) arrange to deprive yourself of the benefit of the 505 | patent license for this particular work, or (3) arrange, in a manner 506 | consistent with the requirements of this License, to extend the patent 507 | license to downstream recipients. "Knowingly relying" means you have 508 | actual knowledge that, but for the patent license, your conveying the 509 | covered work in a country, or your recipient's use of the covered work 510 | in a country, would infringe one or more identifiable patents in that 511 | country that you have reason to believe are valid. 512 | 513 | If, pursuant to or in connection with a single transaction or 514 | arrangement, you convey, or propagate by procuring conveyance of, a 515 | covered work, and grant a patent license to some of the parties 516 | receiving the covered work authorizing them to use, propagate, modify 517 | or convey a specific copy of the covered work, then the patent license 518 | you grant is automatically extended to all recipients of the covered 519 | work and works based on it. 520 | 521 | A patent license is "discriminatory" if it does not include within 522 | the scope of its coverage, prohibits the exercise of, or is 523 | conditioned on the non-exercise of one or more of the rights that are 524 | specifically granted under this License. You may not convey a covered 525 | work if you are a party to an arrangement with a third party that is 526 | in the business of distributing software, under which you make payment 527 | to the third party based on the extent of your activity of conveying 528 | the work, and under which the third party grants, to any of the 529 | parties who would receive the covered work from you, a discriminatory 530 | patent license (a) in connection with copies of the covered work 531 | conveyed by you (or copies made from those copies), or (b) primarily 532 | for and in connection with specific products or compilations that 533 | contain the covered work, unless you entered into that arrangement, 534 | or that patent license was granted, prior to 28 March 2007. 535 | 536 | Nothing in this License shall be construed as excluding or limiting 537 | any implied license or other defenses to infringement that may 538 | otherwise be available to you under applicable patent law. 539 | 540 | 12. No Surrender of Others' Freedom. 541 | 542 | If conditions are imposed on you (whether by court order, agreement or 543 | otherwise) that contradict the conditions of this License, they do not 544 | excuse you from the conditions of this License. If you cannot convey a 545 | covered work so as to satisfy simultaneously your obligations under this 546 | License and any other pertinent obligations, then as a consequence you may 547 | not convey it at all. For example, if you agree to terms that obligate you 548 | to collect a royalty for further conveying from those to whom you convey 549 | the Program, the only way you could satisfy both those terms and this 550 | License would be to refrain entirely from conveying the Program. 551 | 552 | 13. Use with the GNU Affero General Public License. 553 | 554 | Notwithstanding any other provision of this License, you have 555 | permission to link or combine any covered work with a work licensed 556 | under version 3 of the GNU Affero General Public License into a single 557 | combined work, and to convey the resulting work. The terms of this 558 | License will continue to apply to the part which is the covered work, 559 | but the special requirements of the GNU Affero General Public License, 560 | section 13, concerning interaction through a network will apply to the 561 | combination as such. 562 | 563 | 14. Revised Versions of this License. 564 | 565 | The Free Software Foundation may publish revised and/or new versions of 566 | the GNU General Public License from time to time. Such new versions will 567 | be similar in spirit to the present version, but may differ in detail to 568 | address new problems or concerns. 569 | 570 | Each version is given a distinguishing version number. If the 571 | Program specifies that a certain numbered version of the GNU General 572 | Public License "or any later version" applies to it, you have the 573 | option of following the terms and conditions either of that numbered 574 | version or of any later version published by the Free Software 575 | Foundation. If the Program does not specify a version number of the 576 | GNU General Public License, you may choose any version ever published 577 | by the Free Software Foundation. 578 | 579 | If the Program specifies that a proxy can decide which future 580 | versions of the GNU General Public License can be used, that proxy's 581 | public statement of acceptance of a version permanently authorizes you 582 | to choose that version for the Program. 583 | 584 | Later license versions may give you additional or different 585 | permissions. However, no additional obligations are imposed on any 586 | author or copyright holder as a result of your choosing to follow a 587 | later version. 588 | 589 | 15. Disclaimer of Warranty. 590 | 591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 599 | 600 | 16. Limitation of Liability. 601 | 602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 610 | SUCH DAMAGES. 611 | 612 | 17. Interpretation of Sections 15 and 16. 613 | 614 | If the disclaimer of warranty and limitation of liability provided 615 | above cannot be given local legal effect according to their terms, 616 | reviewing courts shall apply local law that most closely approximates 617 | an absolute waiver of all civil liability in connection with the 618 | Program, unless a warranty or assumption of liability accompanies a 619 | copy of the Program in return for a fee. 620 | 621 | END OF TERMS AND CONDITIONS 622 | 623 | How to Apply These Terms to Your New Programs 624 | 625 | If you develop a new program, and you want it to be of the greatest 626 | possible use to the public, the best way to achieve this is to make it 627 | free software which everyone can redistribute and change under these terms. 628 | 629 | To do so, attach the following notices to the program. It is safest 630 | to attach them to the start of each source file to most effectively 631 | state the exclusion of warranty; and each file should have at least 632 | the "copyright" line and a pointer to where the full notice is found. 633 | 634 | 635 | Copyright (C) 636 | 637 | This program is free software: you can redistribute it and/or modify 638 | it under the terms of the GNU General Public License as published by 639 | the Free Software Foundation, either version 3 of the License, or 640 | (at your option) any later version. 641 | 642 | This program is distributed in the hope that it will be useful, 643 | but WITHOUT ANY WARRANTY; without even the implied warranty of 644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 645 | GNU General Public License for more details. 646 | 647 | You should have received a copy of the GNU General Public License 648 | along with this program. If not, see . 649 | 650 | Also add information on how to contact you by electronic and paper mail. 651 | 652 | If the program does terminal interaction, make it output a short 653 | notice like this when it starts in an interactive mode: 654 | 655 | Copyright (C) 656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 657 | This is free software, and you are welcome to redistribute it 658 | under certain conditions; type `show c' for details. 659 | 660 | The hypothetical commands `show w' and `show c' should show the appropriate 661 | parts of the General Public License. Of course, your program's commands 662 | might be different; for a GUI interface, you would use an "about box". 663 | 664 | You should also get your employer (if you work as a programmer) or school, 665 | if any, to sign a "copyright disclaimer" for the program, if necessary. 666 | For more information on this, and how to apply and follow the GNU GPL, see 667 | . 668 | 669 | The GNU General Public License does not permit incorporating your program 670 | into proprietary programs. If your program is a subroutine library, you 671 | may consider it more useful to permit linking proprietary applications with 672 | the library. If this is what you want to do, use the GNU Lesser General 673 | Public License instead of this License. But first, please read 674 | . 675 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # webrtc_web 2 | for geek time 3 | --------------------------------------------------------------------------------