Compare commits
19 Commits
feature/si
...
master
Author | SHA1 | Date | |
---|---|---|---|
c4bb684b41 | |||
bf4749499e | |||
f025675b9b | |||
614eb52224 | |||
131c9b3bf1 | |||
90565985ae | |||
4f3ae7abd6 | |||
834031dca7 | |||
225a307ac7 | |||
a3528ec43e | |||
3f393d8dc2 | |||
6300f20407 | |||
c4cddaaefd | |||
5669593cb1 | |||
01446ba255 | |||
581978335e | |||
cc5a882392 | |||
a18ccfd393 | |||
602a3c0d8c |
9
.gitmodules
vendored
Normal file
9
.gitmodules
vendored
Normal file
|
@ -0,0 +1,9 @@
|
|||
[submodule "external/LZMA-JS"]
|
||||
path = external/LZMA-JS
|
||||
url = https://github.com/LZMA-JS/LZMA-JS.git
|
||||
[submodule "external/base64.js"]
|
||||
path = external/base64.js
|
||||
url = https://gist.github.com/72c423f727d395eeaa09697058238727.git
|
||||
[submodule "external/qr-scanner"]
|
||||
path = external/qr-scanner
|
||||
url = https://github.com/nimiq/qr-scanner.git
|
|
@ -4,5 +4,5 @@ from . import consumers
|
|||
|
||||
websocket_urlpatterns = [
|
||||
re_path(r'camera/ws/(?P<kind>host|client)/(?P<room_name>\w+)/$',
|
||||
consumers.VideoConsumer),
|
||||
consumers.VideoConsumer.as_asgi()),
|
||||
]
|
||||
|
|
1
camera/static/js/base64.js
Symbolic link
1
camera/static/js/base64.js
Symbolic link
|
@ -0,0 +1 @@
|
|||
../../../external/base64.js/base64.js
|
1
camera/static/js/lzma_worker.js
Symbolic link
1
camera/static/js/lzma_worker.js
Symbolic link
|
@ -0,0 +1 @@
|
|||
../../../external/LZMA-JS/src/lzma_worker.js
|
175
camera/static/js/prefix
Normal file
175
camera/static/js/prefix
Normal file
|
@ -0,0 +1,175 @@
|
|||
{"description":{"type":"answer","sdp":"v=0
|
||||
o=- 0 2 IN IP4 127.0.0.1
|
||||
s=-
|
||||
t=0 0
|
||||
a=group:BUNDLE 0
|
||||
a=msid-semantic: WMS
|
||||
m=audio 9 UDP/TLS/RTP/SAVPF 109 9 0 8 101
|
||||
c=IN IP4 0.0.0.0
|
||||
a=rtcp:9 IN IP4 0.0.0.0
|
||||
a=candidate:0 1 udp 0 a.local 0 typ host generation 0 network-cost 999
|
||||
a=ice-ufrag:
|
||||
a=ice-pwd:
|
||||
a=ice-options:trickle
|
||||
a=fingerprint:sha-256 000:01:12:23:34:45:56:67:78:89:9A:AB:BC:CD:DE:EF:F0:02:03:04:05:06:07:08:09:0A:0B:0C:0D:0E:0F
|
||||
a=setup:active
|
||||
a=mid:0
|
||||
a=extmap:1 urn:ietf:params:rtp-hdrext:ssrc-audio-level
|
||||
a=extmap:3 urn:ietf:params:rtp-hdrext:sdes:mid
|
||||
a=recvonly
|
||||
a=rtcp-mux
|
||||
a=rtpmap:109 opus/48000/2
|
||||
a=fmtp:109 minptime=10;useinbandfec=1
|
||||
a=rtpmap:9 G722/8000
|
||||
a=rtpmap:0 PCMU/8000
|
||||
a=rtpmap:8 PCMA/8000
|
||||
a=rtpmap:101 telephone-event/8000
|
||||
"}}
|
||||
{"description":{"type":"offer","sdp":"v=0
|
||||
o=mozilla...THIS_IS_SDPARTA-68.8.1 0 0 IN IP4 0.0.0.0
|
||||
s=-
|
||||
t=0 0
|
||||
a=sendrecv
|
||||
a=fingerprint:sha-256 0:10:11:12:13:14:15:16:17:18:19:1A:1B:1C:1D:1E:1F:20:21:22:23:24:25:26:27:28:29:2A:2B:2C:2D
|
||||
a=group:BUNDLE 0
|
||||
a=ice-options:trickle
|
||||
a=msid-semantic:WMS *
|
||||
m=audio 40000 UDP/TLS/RTP/SAVPF 109 9 0 8 101
|
||||
c=IN IP4 192.168.0.0
|
||||
a=candidate:0 1 UDP 2100000000 192.168.0.0 40000 typ host
|
||||
a=candidate:1 1 UDP 2100000000 ::1 40000 typ host
|
||||
a=candidate:2 1 TCP 2100000000 192.168.0.0 40000 typ host tcptype passive
|
||||
a=candidate:2 1 TCP 2100000000 192.168.0.0 9 typ host tcptype active
|
||||
a=candidate:3 1 TCP 2100000000 ::1 40000 typ host tcptype passive
|
||||
a=candidate:3 1 TCP 2100000000 ::1 9 typ host tcptype active
|
||||
a=candidate:0 2 UDP 2100000000 192.168.0.0 40000 typ host
|
||||
a=candidate:1 2 UDP 2100000000 ::1 40000 typ host
|
||||
a=candidate:2 2 TCP 2100000000 192.168.0.0 40000 typ host tcptype passive
|
||||
a=candidate:2 2 TCP 2100000000 192.168.0.0 9 typ host tcptype active
|
||||
a=candidate:3 2 TCP 2100000000 ::1 40000 typ host tcptype passive
|
||||
a=candidate:3 2 TCP 2100000000 ::1 9 typ host tcptype active
|
||||
a=sendrecv
|
||||
a=end-of-candidates
|
||||
a=extmap:1 urn:ietf:params:rtp-hdrext:ssrc-audio-level
|
||||
a=extmap:2/recvonly urn:ietf:params:rtp-hdrext:csrc-audio-level
|
||||
a=extmap:3 urn:ietf:params:rtp-hdrext:sdes:mid
|
||||
a=fmtp:109 maxplaybackrate=48000;stereo=1;useinbandfec=1
|
||||
a=fmtp:101 0-15
|
||||
a=ice-pwd:
|
||||
a=ice-ufrag:
|
||||
a=mid:0
|
||||
a=msid:{}
|
||||
a=rtcp:40000 IN IP4 192.168.0.0
|
||||
a=rtcp-mux
|
||||
a=rtpmap:109 opus/48000/2
|
||||
a=rtpmap:9 G722/8000/1
|
||||
a=rtpmap:0 PCMU/8000
|
||||
a=rtpmap:8 PCMA/8000
|
||||
a=rtpmap:101 telephone-event/8000
|
||||
a=setup:actpass
|
||||
a=ssrc:0 cname:{}
|
||||
"}}
|
||||
{"description":{"type":"answer","sdp":"v=0
|
||||
o=- 0 2 IN IP4 127.0.0.1
|
||||
s=-
|
||||
t=0 0
|
||||
a=group:BUNDLE 0
|
||||
a=msid-semantic: WMS
|
||||
m=video 9 UDP/TLS/RTP/SAVPF 120 121
|
||||
c=IN IP4 0.0.0.0
|
||||
a=rtcp:9 IN IP4 0.0.0.0
|
||||
a=candidate:0 1 udp 2100000000 abc.local 40000 typ host generation 0 network-cost 999
|
||||
a=ice-ufrag:
|
||||
a=ice-pwd:
|
||||
a=ice-options:trickle
|
||||
a=fingerprint:sha-256 0:2E:2F:30:31:32:33:34:35:36:37:38:39:3A:3B:3C:3D:3E:3F:40:41:42:43:44:45:46:47:48:49:4A:4B
|
||||
a=setup:active
|
||||
a=mid:0
|
||||
a=extmap:5 urn:ietf:params:rtp-hdrext:toffset
|
||||
a=extmap:4 http://www.webrtc.org/experiments/rtp-hdrext/abs-send-time
|
||||
a=extmap:3 urn:ietf:params:rtp-hdrext:sdes:mid
|
||||
a=recvonly
|
||||
a=rtcp-mux
|
||||
a=rtpmap:120 VP8/90000
|
||||
a=rtcp-fb:120 goog-remb
|
||||
a=rtcp-fb:120 ccm fir
|
||||
a=rtcp-fb:120 nack
|
||||
a=rtcp-fb:120 nack pli
|
||||
a=rtpmap:121 VP9/90000
|
||||
a=rtcp-fb:121 goog-remb
|
||||
a=rtcp-fb:121 ccm fir
|
||||
a=rtcp-fb:121 nack
|
||||
a=rtcp-fb:121 nack pli
|
||||
a=fmtp:121 profile-id=0
|
||||
"}}
|
||||
{"description":{"type":"offer","sdp":"v=0
|
||||
o=mozilla...THIS_IS_SDPARTA-68.8.1 0 0 IN IP4 0.0.0.0
|
||||
s=-
|
||||
t=0 0
|
||||
a=sendrecv
|
||||
a=fingerprint:sha-256 0:4C:4D:4E:4F:50:51:52:53:54:55:56:57:58:59:5A:5B:5C:5D:5E:5F:60:61:62:63:64:65:66:67:68:69
|
||||
a=group:BUNDLE 0
|
||||
a=ice-options:trickle
|
||||
a=msid-semantic:WMS *
|
||||
m=video 40000 UDP/TLS/RTP/SAVPF 120 121
|
||||
c=IN IP4 192.168.0.0
|
||||
a=candidate:0 1 UDP 2100000000 192.168.0.0 40000 typ host
|
||||
a=candidate:1 1 UDP 2100000000 ::1 40000 typ host
|
||||
a=candidate:2 1 TCP 2100000000 192.168.0.0 40000 typ host tcptype passive
|
||||
a=candidate:2 1 TCP 2100000000 192.168.0.0 9 typ host tcptype active
|
||||
a=candidate:3 1 TCP 2100000000 ::1 40000 typ host tcptype passive
|
||||
a=candidate:3 1 TCP 2100000000 ::1 9 typ host tcptype active
|
||||
a=candidate:0 2 UDP 2100000000 192.168.0.0 40000 typ host
|
||||
a=candidate:1 2 UDP 2100000000 ::1 40000 typ host
|
||||
a=candidate:2 2 TCP 2100000000 192.168.0.0 40000 typ host tcptype passive
|
||||
a=candidate:2 2 TCP 2100000000 192.168.0.0 9 typ host tcptype active
|
||||
a=candidate:3 2 TCP 2100000000 ::1 40000 typ host tcptype passive
|
||||
a=candidate:3 2 TCP 2100000000 ::1 9 typ host tcptype active
|
||||
a=sendrecv
|
||||
a=end-of-candidates
|
||||
a=extmap:3 urn:ietf:params:rtp-hdrext:sdes:mid
|
||||
a=extmap:4 http://www.webrtc.org/experiments/rtp-hdrext/abs-send-time
|
||||
a=extmap:5 urn:ietf:params:rtp-hdrext:toffset
|
||||
a=fmtp:120 max-fs=12288;max-fr=60
|
||||
a=fmtp:121 max-fs=12288;max-fr=60
|
||||
a=ice-pwd:
|
||||
a=ice-ufrag:
|
||||
a=mid:0
|
||||
a=msid:{}
|
||||
a=rtcp:40000 IN IP4 192.168.0.0
|
||||
a=rtcp-fb:120 nack
|
||||
a=rtcp-fb:120 nack pli
|
||||
a=rtcp-fb:120 ccm fir
|
||||
a=rtcp-fb:120 goog-remb
|
||||
a=rtcp-fb:121 nack
|
||||
a=rtcp-fb:121 nack pli
|
||||
a=rtcp-fb:121 ccm fir
|
||||
a=rtcp-fb:121 goog-remb
|
||||
a=rtcp-mux
|
||||
a=rtpmap:120 VP8/90000
|
||||
a=rtpmap:121 VP9/90000
|
||||
a=setup:actpass
|
||||
a=ssrc:0 cname:{}
|
||||
"}}
|
||||
{"description":{"type":"offer","sdp":"v=0
|
||||
o=mozilla...THIS_IS_SDPARTA-75.0 0 0 IN IP4 0.0.0.0
|
||||
s=-
|
||||
t=0 0
|
||||
a=sendrecv
|
||||
a=fingerprint:sha-256 6A:6B:6C:6D:6E:6F:70:71:72:73:74:75:76:77:78:79:7A:7B:7C:7D:7E:7F:80:81:82:83:84:85:86:87:88:89
|
||||
a=group:BUNDLE 0
|
||||
a=ice-options:trickle
|
||||
a=msid-semantic:WMS *
|
||||
m=application 9 UDP/DTLS/SCTP webrtc-datachannel
|
||||
c=IN IP4 0.0.0.0
|
||||
a=candidate:0 1 UDP 2100000000 0.local 40000 typ host
|
||||
a=candidate:1 1 TCP 2100000000 0.local 9 typ host tcptype active
|
||||
a=sendrecv
|
||||
a=end-of-candidates
|
||||
a=ice-pwd:
|
||||
a=ice-ufrag:
|
||||
a=mid:0
|
||||
a=setup:actpass
|
||||
a=sctp-port:5000
|
||||
a=max-message-size:
|
||||
"}}
|
47
camera/static/js/prefixCompressor.js
Normal file
47
camera/static/js/prefixCompressor.js
Normal file
|
@ -0,0 +1,47 @@
|
|||
async function loadLZMAPrefixCompressor(prefixFilename) {
|
||||
class PrefixCompressor {
|
||||
constructor(prefix, compress, decompress, bytesToIgnore) {
|
||||
this.prefix = prefix;
|
||||
this.prefixCompressed = compress(prefix);
|
||||
this.bytesToIgnore = bytesToIgnore;
|
||||
this.baseCompress = compress;
|
||||
this.baseDecompress = decompress;
|
||||
}
|
||||
|
||||
compress(str) {
|
||||
const c = this.baseCompress(this.prefix + str);
|
||||
for (var i = this.bytesToIgnore;
|
||||
i < this.prefixCompressed.length
|
||||
&& this.prefixCompressed[i] == c[i];
|
||||
i++) { }
|
||||
const omittedBytes = this.prefixCompressed.length - i;
|
||||
const res = c.subarray(i - 1);
|
||||
res[0] = omittedBytes;
|
||||
return res;
|
||||
}
|
||||
|
||||
decompress(arr) {
|
||||
const omittedBytes = arr[0];
|
||||
const prefixBytes = this.prefixCompressed.length-omittedBytes;
|
||||
const c = new Uint8Array(prefixBytes + arr.length-1);
|
||||
c.set(this.prefixCompressed.subarray(0, prefixBytes));
|
||||
c.set(arr.subarray(1), prefixBytes);
|
||||
const d = this.baseDecompress(c);
|
||||
return d.substring(this.prefix.length);
|
||||
}
|
||||
}
|
||||
async function loadDictionary() {
|
||||
const response = await fetch(prefixFilename);
|
||||
return await response.text();
|
||||
}
|
||||
const prefix = await loadDictionary();
|
||||
|
||||
return new PrefixCompressor(prefix, str => {
|
||||
const res = new Uint8Array(LZMA.compress(str, 9));
|
||||
// Clear uncompressed size as it will be invalid.
|
||||
for (var i = 5; i < 13; i++) res[i] = 255;
|
||||
return res;
|
||||
}, arr => {
|
||||
return LZMA.decompress(arr).toString();
|
||||
}, 12);
|
||||
}
|
1
camera/static/js/qr-scanner-worker.min.js
vendored
Symbolic link
1
camera/static/js/qr-scanner-worker.min.js
vendored
Symbolic link
|
@ -0,0 +1 @@
|
|||
../../../external/qr-scanner-binaryData/qr-scanner-worker.min.js
|
1
camera/static/js/qr-scanner-worker.min.js.map
Symbolic link
1
camera/static/js/qr-scanner-worker.min.js.map
Symbolic link
|
@ -0,0 +1 @@
|
|||
../../../external/qr-scanner/qr-scanner-worker.min.js.map
|
1
camera/static/js/qr-scanner.min.js
vendored
Symbolic link
1
camera/static/js/qr-scanner.min.js
vendored
Symbolic link
|
@ -0,0 +1 @@
|
|||
../../../external/qr-scanner/qr-scanner.min.js
|
1
camera/static/js/qr-scanner.min.js.map
Symbolic link
1
camera/static/js/qr-scanner.min.js.map
Symbolic link
|
@ -0,0 +1 @@
|
|||
../../../external/qr-scanner/qr-scanner.min.js.map
|
1
camera/static/js/qrcodegen.js
Symbolic link
1
camera/static/js/qrcodegen.js
Symbolic link
|
@ -0,0 +1 @@
|
|||
../../../external/qr-code-generator/qrcodegen.js
|
|
@ -3,18 +3,23 @@
|
|||
<head>
|
||||
<meta charset="utf-8"/>
|
||||
<title>Minimal WebRTC</title>
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1, minimum-scale=1, maximum-scale=1">
|
||||
<style>
|
||||
body.justVideo {
|
||||
margin: 0;
|
||||
overflow: hidden;
|
||||
}
|
||||
#qrcodelink {
|
||||
body.justVideo #status, body.justVideo form {
|
||||
display: none;
|
||||
}
|
||||
.qrcontainer {
|
||||
position: sticky;
|
||||
top: 0;
|
||||
right: 0;
|
||||
float: right;
|
||||
}
|
||||
#qrcode {
|
||||
.qrcontainer svg path {
|
||||
min-width: 30vw;
|
||||
max-width: 100vw;
|
||||
max-height: 50vh;
|
||||
}
|
||||
|
@ -51,17 +56,37 @@ form label {
|
|||
background: lightyellow;
|
||||
}
|
||||
</style>
|
||||
<script type="text/javascript" src="static/js/qrcodegen.js"></script>
|
||||
<script type="text/javascript" src="static/js/lzma_worker.js"></script>
|
||||
<script type="text/javascript" src="static/js/prefixCompressor.js"></script>
|
||||
</head>
|
||||
<body>
|
||||
<a id="qrcodelink" style="display:none;"><img id="qrcode" /></a>
|
||||
<a class="qrcontainer" id="qrcodelink" style="display:none;">
|
||||
<svg xmlns="http://www.w3.org/2000/svg" id="qrcode" style="width:20em; height:20em;" stroke="none">
|
||||
<rect width="100%" height="100%" fill="#FFFFFF"/>
|
||||
<path d="" fill="#000000"/>
|
||||
</svg>
|
||||
</a>
|
||||
<div class="qrcontainer" id="qrcodeObjContainer" style="display:none;">
|
||||
<svg xmlns="http://www.w3.org/2000/svg" id="qrcodeObj" style="width:20em; height:20em;" stroke="none">
|
||||
<rect width="100%" height="100%" fill="#FFFFFF"/>
|
||||
<path d="" fill="#000000"/>
|
||||
</svg> <br/>
|
||||
<textarea id="localOffer" readonly></textarea>
|
||||
<button id="copyLocalOffer">Copy</button>
|
||||
</div>
|
||||
<form name="settings">
|
||||
<label>
|
||||
Serverless mode:
|
||||
<input name="serverless" type="checkbox" value="true" />
|
||||
</label>
|
||||
<label>
|
||||
Recieve remote video:
|
||||
<select name="client-video">
|
||||
<option value="none">none</option>
|
||||
<option value="true">any camera</option>
|
||||
<option value="environment" selected>rear camera</option>
|
||||
<option value="user">front camera</option>
|
||||
<option value="true" selected>any camera</option>
|
||||
<option value="screen">screen share</option>
|
||||
</select>
|
||||
</label>
|
||||
|
@ -74,6 +99,8 @@ form label {
|
|||
<select name="host-video">
|
||||
<option value="none" selected>none</option>
|
||||
<option value="true">any camera</option>
|
||||
<option value="environment">rear camera</option>
|
||||
<option value="user">front camera</option>
|
||||
<option value="screen">screen share</option>
|
||||
</select>
|
||||
</label>
|
||||
|
@ -81,6 +108,17 @@ form label {
|
|||
Transmit audio:
|
||||
<input name="host-audio" type="checkbox" value="true" />
|
||||
</label>
|
||||
<label>
|
||||
Debug mode (show log even after starting video):
|
||||
<input name="debug" type="checkbox" value="true" />
|
||||
</label>
|
||||
</form>
|
||||
<form id="serverlessOffer" style="display: none;" onsubmit="return false;">
|
||||
<label>
|
||||
Paste offer here:
|
||||
<textarea name="remoteOffer"></textarea>
|
||||
<button id="remoteOfferScan">Scan QR code</button>
|
||||
</label>
|
||||
</form>
|
||||
<div id="status"></div>
|
||||
<div id="videos">
|
||||
|
@ -88,19 +126,42 @@ form label {
|
|||
<button id="start" style="display:none;">Start Streaming</button>
|
||||
<video id="remoteView" width="100%" autoplay muted style="display:none;"></video>
|
||||
<video id="selfView" width="200" height="150" autoplay muted style="display:none;"></video>
|
||||
<video id="qrscan" width="100%" autoplay muted style="display:none;"></video>
|
||||
</div>
|
||||
<script >
|
||||
<script type="module" >
|
||||
import * as b64 from "./static/js/base64.js";
|
||||
import QrScanner from "./static/js/qr-scanner.min.js";
|
||||
QrScanner.WORKER_PATH = "./static/js/qr-scanner-worker.min.js"
|
||||
|
||||
async function initialize() {
|
||||
const create = (container, type) => container.appendChild(document.createElement(type));
|
||||
const QRGen = qrcodegen.QrCode;
|
||||
|
||||
var compressor = null;
|
||||
async function getCompressor() {
|
||||
if (compressor == null) {
|
||||
compressor = await loadLZMAPrefixCompressor('static/js/prefix');
|
||||
}
|
||||
return compressor;
|
||||
}
|
||||
|
||||
const body = document.querySelector("body");
|
||||
const out = document.getElementById("status");
|
||||
const qrcode = document.getElementById("qrcode");
|
||||
const qrcodelink = document.getElementById("qrcodelink");
|
||||
const qrcodeObjContainer = document.getElementById("qrcodeObjContainer");
|
||||
const qrcodeObj = document.getElementById("qrcodeObj");
|
||||
const remoteView = document.getElementById("remoteView");
|
||||
const selfView = document.getElementById("selfView");
|
||||
const qrscan = document.getElementById("qrscan");
|
||||
const start = document.getElementById("start");
|
||||
const unmute = document.getElementById("unmute");
|
||||
const form = document.forms["settings"];
|
||||
const remoteOfferForm = document.forms["serverlessOffer"];
|
||||
const remoteOffer = remoteOfferForm.elements["remoteOffer"];
|
||||
const remoteOfferScan = document.getElementById("remoteOfferScan");
|
||||
const localOfferArea = document.getElementById("localOffer");
|
||||
const localOfferCopyButton = document.getElementById("copyLocalOffer");
|
||||
|
||||
function _log(str, tag) {
|
||||
const logEntry = document.createElement(tag);
|
||||
|
@ -134,18 +195,64 @@ form label {
|
|||
}
|
||||
|
||||
for (const el of form.elements) {
|
||||
el.addEventListener("change", _ => {
|
||||
el.addEventListener("change", e => {
|
||||
window.location.hash = JSON.stringify(readSettingsForm(false));
|
||||
if (e.target.name == 'serverless') {
|
||||
window.location.reload(false);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
function getRoomName() {
|
||||
JSON.parse(document.getElementById('room-name').textContent);
|
||||
function isServerless() {
|
||||
return settings && 'serverless' in settings && settings.serverless;
|
||||
}
|
||||
|
||||
function withHash(hash) {
|
||||
return window.location.href.split('#')[0] + '#' + hash;
|
||||
}
|
||||
function displayQR(qrcode, val) {
|
||||
const encodeFunc = val instanceof Uint8Array
|
||||
? QRGen.encodeBinary
|
||||
: QRGen.encodeText;
|
||||
const qr = encodeFunc(val, QRGen.Ecc.MEDIUM);
|
||||
const code = qr.toSvgString(1);
|
||||
const viewBox = (/ viewBox="([^"]*)"/.exec(code))[1];
|
||||
const pathD = (/ d="([^"]*)"/.exec(code))[1];
|
||||
qrcode.setAttribute("viewBox", viewBox);
|
||||
qrcode.querySelector("path").setAttribute("d", pathD);
|
||||
}
|
||||
function displayQRUrl(url) {
|
||||
qrcodelink.href = url;
|
||||
displayQR(qrcode, url);
|
||||
qrcodelink.style.display = '';
|
||||
}
|
||||
function displayQRUrlForObj(obj) {
|
||||
const json = JSON.stringify(obj);
|
||||
log("Encoding message in QR code/link:");
|
||||
logPre(json);
|
||||
const compressed = compressor.compress(json);
|
||||
const encoded = b64.bytesToBase64(compressed);
|
||||
displayQRUrl(withHash('^' + encoded));
|
||||
}
|
||||
function displayQRCodeForObj(obj) {
|
||||
const json = JSON.stringify(obj);
|
||||
log("Encoding message in QR code for copy/paste:");
|
||||
logPre(json);
|
||||
const compressed = compressor.compress(json);
|
||||
const encoded = b64.bytesToBase64(compressed);
|
||||
displayQR(qrcodeObj, compressed);
|
||||
localOfferArea.value = encoded;
|
||||
localOfferCopyButton.onclick = _ => {
|
||||
localOfferArea.focus();
|
||||
localOfferArea.select();
|
||||
document.execCommand('copy');
|
||||
};
|
||||
qrcodeObjContainer.style.display = '';
|
||||
}
|
||||
|
||||
let roomName = window.location.hash;
|
||||
let isHost = roomName === undefined || !roomName;
|
||||
if (roomName.startsWith("#{")) {
|
||||
if (roomName && roomName.startsWith("#{")) {
|
||||
roomName = undefined;
|
||||
isHost = true;
|
||||
|
||||
|
@ -167,6 +274,25 @@ form label {
|
|||
log("Failed to read settings from hash: " + error);
|
||||
}
|
||||
}
|
||||
var firstMessage = undefined;
|
||||
if (roomName && roomName.startsWith("#^")) {
|
||||
roomName = undefined;
|
||||
isHost = false;
|
||||
|
||||
try {
|
||||
const hash = decodeURI(window.location.hash);
|
||||
log("Reading first message from hash:");
|
||||
logPre(hash);
|
||||
log("Decoded base64:");
|
||||
const decoded = (await getCompressor()).decompress(b64.base64ToBytes(hash.substring(2)));
|
||||
logPre(decoded);
|
||||
firstMessage = decoded;
|
||||
settings = {serverless: true};
|
||||
} catch (error) {
|
||||
log("Failed to read message from hash: " + error);
|
||||
}
|
||||
}
|
||||
|
||||
if (isHost) {
|
||||
// From https://stackoverflow.com/a/1349426
|
||||
function makeid(length) {
|
||||
|
@ -179,41 +305,79 @@ form label {
|
|||
return result;
|
||||
}
|
||||
|
||||
roomName = makeid(8);
|
||||
qrcodelink.href = window.location.href.split('#')[0] + '#' + roomName;
|
||||
qrcode.src = window.location.href.split('#')[0] + roomName + '/qr';
|
||||
qrcodelink.style.display = '';
|
||||
if (!isServerless()) {
|
||||
roomName = makeid(8);
|
||||
displayQRUrl(withHash(roomName));
|
||||
}
|
||||
} else {
|
||||
roomName = roomName.substring(1);
|
||||
if (!isServerless()) {
|
||||
roomName = roomName.substring(1);
|
||||
}
|
||||
qrcodelink.style.display = 'none';
|
||||
form.style.display = 'none';
|
||||
}
|
||||
|
||||
log("Room: " + roomName);
|
||||
if (isServerless()) {
|
||||
log("In serverless mode.");
|
||||
} else {
|
||||
log("Room: " + roomName);
|
||||
}
|
||||
|
||||
var webSocket = undefined;
|
||||
|
||||
function sendJson(data) {
|
||||
const toSend = JSON.stringify(data);
|
||||
log("Sending message...");
|
||||
const dcReady = dc && dc.readyState == "open";
|
||||
const method = dcReady ? "dataConnection" : "webSocket";
|
||||
log("Sending message via " + method + "...");
|
||||
logPre(toSend);
|
||||
webSocket.send(toSend);
|
||||
if (isServerless() && !dcReady) {
|
||||
log("ERROR: Attempted to use webSocket in serverless mode.");
|
||||
return;
|
||||
}
|
||||
(dcReady ? dc : webSocket).send(toSend);
|
||||
}
|
||||
|
||||
var pc = undefined;
|
||||
var dc = undefined;
|
||||
|
||||
function sendOffer() {
|
||||
if (pc.iceGatheringState == "complete") {
|
||||
const sendFunc = !isServerless() || dc && dc.readyState == "open"
|
||||
? sendJson
|
||||
: isHost
|
||||
? displayQRUrlForObj
|
||||
: displayQRCodeForObj;
|
||||
sendFunc({
|
||||
description: pc.localDescription
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
function createRTCPeerConnection() {
|
||||
const pc = new RTCPeerConnection();
|
||||
log("Created RTCPeerConnection.");
|
||||
|
||||
pc.onicecandidate = ({candidate}) => sendJson({candidate});
|
||||
pc.onsignalingstatechange = e => {
|
||||
log("pc.onsignalingstatechange: " + pc.signalingState);
|
||||
}
|
||||
pc.oniceconnectionstatechange = e => {
|
||||
log("pc.oniceconnectionstatechange: " + pc.iceConnectionState);
|
||||
}
|
||||
pc.onicegatheringstatechange = async function(e) {
|
||||
log("pc.onicegatheringstatechange: " + pc.iceGatheringState);
|
||||
sendOffer();
|
||||
}
|
||||
|
||||
// let the "negotiationneeded" event trigger offer generation
|
||||
// ... but only once icegathering is complete.
|
||||
pc.onnegotiationneeded = async function () {
|
||||
log("In pc.onnegotiationneeded...");
|
||||
await pc.setLocalDescription(await pc.createOffer());
|
||||
sendJson({
|
||||
description: pc.localDescription
|
||||
});
|
||||
const useOffer = (!settings || !('separateIce' in settings)
|
||||
|| !settings.separateIce);
|
||||
await pc.setLocalDescription(
|
||||
await (useOffer ? pc.createOffer() : pc.createAnswer()));
|
||||
sendOffer();
|
||||
}
|
||||
|
||||
pc.ontrack = ({streams: [stream]}) => {
|
||||
|
@ -225,18 +389,43 @@ form label {
|
|||
|
||||
if (stream.getVideoTracks().length > 0) {
|
||||
remoteView.style.display = '';
|
||||
out.style.display = 'none';
|
||||
form.style.display = 'none';
|
||||
videos.style.display = '';
|
||||
body.classList.add('justVideo');
|
||||
if (!settings.debug) {
|
||||
body.classList.add('justVideo');
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
pc.ondatachannel = e => {
|
||||
dc = e.channel;
|
||||
dc.onmessage = e => {
|
||||
receiveMessage({source: "dataChannel", data: e.data});
|
||||
}
|
||||
log('Data channel initialized.');
|
||||
qrcodeObjContainer.style.display = 'none';
|
||||
}
|
||||
|
||||
if (isHost) {
|
||||
dc = pc.createDataChannel('data');
|
||||
dc.onmessage = e => {
|
||||
receiveMessage({source: "dataChannel", data: e.data});
|
||||
}
|
||||
dc.onopen = e => {
|
||||
remoteOffer.disabled = true;
|
||||
remoteOfferScan.disabled = true;
|
||||
log("Data channel open, sending settings...")
|
||||
settings = readSettingsForm(true);
|
||||
sendJson({settings});
|
||||
startStreamingWithErorrHandling(false);
|
||||
}
|
||||
}
|
||||
|
||||
return pc;
|
||||
}
|
||||
|
||||
// get a local stream, show it in a self-view and add it to be sent
|
||||
async function startStreaming(fromButton) {
|
||||
log('In startStreaming(fromButton=' + fromButton + ')...');
|
||||
const otherAudioSettings = isHost
|
||||
? settings['client-audio']
|
||||
: settings['host-audio'];
|
||||
|
@ -259,21 +448,12 @@ form label {
|
|||
}
|
||||
start.style.display = 'none';
|
||||
|
||||
if (isHost) {
|
||||
sendJson({
|
||||
settings: settings
|
||||
});
|
||||
}
|
||||
|
||||
if (pc !== undefined) return;
|
||||
pc = createRTCPeerConnection();
|
||||
|
||||
const videoConstraints = videoSettings == 'none'
|
||||
? false
|
||||
: videoSettings == 'true'
|
||||
? true
|
||||
: { advanced: [{facingMode: videoSettings}] };
|
||||
log("Created videoConstraints.");
|
||||
log("Created videoConstraints: " + JSON.stringify(videoConstraints));
|
||||
if (!videoConstraints && !audioSettings) return;
|
||||
|
||||
const stream = videoSettings == 'screen'
|
||||
|
@ -294,44 +474,56 @@ form label {
|
|||
log("Added track.");
|
||||
pc.addTrack(track, stream);
|
||||
}
|
||||
log('End of startStreaming(), creating answer...');
|
||||
if (settings && 'separateIce' in settings && settings.separateIce) {
|
||||
await pc.setLocalDescription(await pc.createAnswer());
|
||||
}
|
||||
}
|
||||
function startStartingWithErorrHandling(fromButton) {
|
||||
startStreaming(fromButton)
|
||||
.then(() => {
|
||||
log("startStreaming() finished.");
|
||||
})
|
||||
.catch(e => {
|
||||
log("startStreaming() errored: " + e.message);
|
||||
});
|
||||
function startStreamingWithErorrHandling(fromButton) {
|
||||
try {
|
||||
startStreaming(fromButton)
|
||||
.then(() => {
|
||||
log("startStreaming() finished.");
|
||||
})
|
||||
.catch(e => {
|
||||
log("startStreaming() errored: " + e.message);
|
||||
});
|
||||
} catch (e) {
|
||||
log("Error in startStreaming(): " + e);
|
||||
}
|
||||
}
|
||||
|
||||
start.addEventListener("click", _ => {
|
||||
startStartingWithErorrHandling(true)
|
||||
startStreamingWithErorrHandling(true)
|
||||
});
|
||||
|
||||
async function receiveMessage(e) {
|
||||
qrcode.style.display = 'none';
|
||||
log("In webSocket.onmessage...");
|
||||
log("In receiveMessage from " + e.source + "...");
|
||||
logPre(e.data);
|
||||
const data = JSON.parse(e.data);
|
||||
if (data.requestSettings) {
|
||||
settings = readSettingsForm(true);
|
||||
startStartingWithErorrHandling(false);
|
||||
if (data.ready) {
|
||||
// Ready message means client is open and ready for connection.
|
||||
pc = createRTCPeerConnection();
|
||||
} else if (data.settings) {
|
||||
settings = data.settings;
|
||||
startStartingWithErorrHandling(false);
|
||||
startStreamingWithErorrHandling(false);
|
||||
} else if (data.description) {
|
||||
await pc.setRemoteDescription(data.description);
|
||||
if (data.description.type == "offer") {
|
||||
log("Got an offer...");
|
||||
await pc.setLocalDescription(await pc.createAnswer());
|
||||
sendJson({
|
||||
description: pc.localDescription
|
||||
});
|
||||
try {
|
||||
if (pc == undefined) pc = createRTCPeerConnection();
|
||||
await pc.setRemoteDescription(data.description);
|
||||
if (data.description.type == "offer") {
|
||||
log("Got an offer...");
|
||||
if (!settings || !('separateIce' in settings) || !settings.separateIce) {
|
||||
await pc.setLocalDescription(await pc.createAnswer());
|
||||
sendOffer();
|
||||
} else {
|
||||
log("separateIce mode, so delaying answer.");
|
||||
}
|
||||
}
|
||||
} catch (e) {
|
||||
log("Error accepting remote offer/answer: " + e);
|
||||
}
|
||||
} else if (data.candidate) {
|
||||
log("Adding ice candidate...");
|
||||
await pc.addIceCandidate(data.candidate);
|
||||
}
|
||||
};
|
||||
|
||||
|
@ -352,18 +544,58 @@ form label {
|
|||
log('WebSocket error: ' + e);
|
||||
};
|
||||
|
||||
webSocket.onmessage = receiveMessage;
|
||||
webSocket.onmessage = e => {
|
||||
receiveMessage({source: "webSocket", data: e.data});
|
||||
}
|
||||
|
||||
return webSocket;
|
||||
}
|
||||
|
||||
webSocket = createWebSocket();
|
||||
if (!isServerless()) {
|
||||
webSocket = createWebSocket();
|
||||
|
||||
if (!isHost) {
|
||||
webSocket.onopen = _ => sendJson({requestSettings: true});
|
||||
if (!isHost) {
|
||||
// To make serverless and server mode more similar,
|
||||
// always make the first RTCPeerConnection offer from the host,
|
||||
// so here just notify the host to start the process.
|
||||
webSocket.onopen = _ => sendJson({ready: true});
|
||||
}
|
||||
} else if (isHost) {
|
||||
await getCompressor();
|
||||
pc = createRTCPeerConnection();
|
||||
remoteOffer.value = '';
|
||||
remoteOffer.onchange = _ => {
|
||||
try {
|
||||
const decoded = b64.base64ToBytes(remoteOffer.value);
|
||||
const decompressed = compressor.decompress(decoded);
|
||||
receiveMessage({source: 'textarea', data: decompressed});
|
||||
} catch (e) {
|
||||
log("Error decoding remote offer: " + e);
|
||||
}
|
||||
};
|
||||
remoteOfferScan.onclick = _ => {
|
||||
qrscan.style.display = '';
|
||||
const qrScanner = new QrScanner(qrscan, (result) => {
|
||||
qrscan.style.display = 'none';
|
||||
log('Decoded qr code.');
|
||||
try {
|
||||
const decompressed = compressor.decompress(new Uint8Array(result.binaryData));
|
||||
receiveMessage({source: 'qr', data: decompressed});
|
||||
qrScanner.destroy();
|
||||
} catch(error) {
|
||||
log('Error interpreting QR code: ' + error);
|
||||
}
|
||||
});
|
||||
qrScanner.start();
|
||||
};
|
||||
remoteOfferForm.style.display = '';
|
||||
} else {
|
||||
receiveMessage({source: 'URL', data: firstMessage});
|
||||
}
|
||||
|
||||
log("Finished <script> block.");
|
||||
}
|
||||
initialize();
|
||||
</script>
|
||||
</body>
|
||||
</html>
|
||||
|
|
|
@ -79,7 +79,7 @@ USE_TZ = True
|
|||
# Static files (CSS, JavaScript, Images)
|
||||
# https://docs.djangoproject.com/en/3.0/howto/static-files/
|
||||
|
||||
STATIC_URL = '/static/'
|
||||
STATIC_URL = '/camera/static/'
|
||||
|
||||
ASGI_APPLICATION = 'camera_site.routing.application'
|
||||
CHANNEL_LAYERS = {
|
||||
|
|
1
external/LZMA-JS
vendored
Submodule
1
external/LZMA-JS
vendored
Submodule
|
@ -0,0 +1 @@
|
|||
Subproject commit 8f98fe85a1ef78ab6e9d26ab85ce338f50095a23
|
1
external/base64.js
vendored
Submodule
1
external/base64.js
vendored
Submodule
|
@ -0,0 +1 @@
|
|||
Subproject commit 74d3cbf82481545bc26c104de2419f4ee30c7dd7
|
4
external/qr-code-generator/README
vendored
Normal file
4
external/qr-code-generator/README
vendored
Normal file
|
@ -0,0 +1,4 @@
|
|||
Source: https://github.com/nayuki/QR-Code-generator
|
||||
Downloaded from https://www.nayuki.io/res/qr-code-generator-library/qrcodegen.js
|
||||
|
||||
MIT Licensed
|
902
external/qr-code-generator/qrcodegen.js
vendored
Normal file
902
external/qr-code-generator/qrcodegen.js
vendored
Normal file
|
@ -0,0 +1,902 @@
|
|||
/*
|
||||
* QR Code generator library (compiled from TypeScript)
|
||||
*
|
||||
* Copyright (c) 2019 Project Nayuki. (MIT License)
|
||||
* https://www.nayuki.io/page/qr-code-generator-library
|
||||
*
|
||||
* Permission is hereby granted, free of charge, to any person obtaining a copy of
|
||||
* this software and associated documentation files (the "Software"), to deal in
|
||||
* the Software without restriction, including without limitation the rights to
|
||||
* use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
|
||||
* the Software, and to permit persons to whom the Software is furnished to do so,
|
||||
* subject to the following conditions:
|
||||
* - The above copyright notice and this permission notice shall be included in
|
||||
* all copies or substantial portions of the Software.
|
||||
* - The Software is provided "as is", without warranty of any kind, express or
|
||||
* implied, including but not limited to the warranties of merchantability,
|
||||
* fitness for a particular purpose and noninfringement. In no event shall the
|
||||
* authors or copyright holders be liable for any claim, damages or other
|
||||
* liability, whether in an action of contract, tort or otherwise, arising from,
|
||||
* out of or in connection with the Software or the use or other dealings in the
|
||||
* Software.
|
||||
*/
|
||||
"use strict";
|
||||
var qrcodegen;
|
||||
(function (qrcodegen) {
|
||||
/*---- QR Code symbol class ----*/
|
||||
/*
|
||||
* A QR Code symbol, which is a type of two-dimension barcode.
|
||||
* Invented by Denso Wave and described in the ISO/IEC 18004 standard.
|
||||
* Instances of this class represent an immutable square grid of black and white cells.
|
||||
* The class provides static factory functions to create a QR Code from text or binary data.
|
||||
* The class covers the QR Code Model 2 specification, supporting all versions (sizes)
|
||||
* from 1 to 40, all 4 error correction levels, and 4 character encoding modes.
|
||||
*
|
||||
* Ways to create a QR Code object:
|
||||
* - High level: Take the payload data and call QrCode.encodeText() or QrCode.encodeBinary().
|
||||
* - Mid level: Custom-make the list of segments and call QrCode.encodeSegments().
|
||||
* - Low level: Custom-make the array of data codeword bytes (including
|
||||
* segment headers and final padding, excluding error correction codewords),
|
||||
* supply the appropriate version number, and call the QrCode() constructor.
|
||||
* (Note that all ways require supplying the desired error correction level.)
|
||||
*/
|
||||
var QrCode = /** @class */ (function () {
|
||||
/*-- Constructor (low level) and fields --*/
|
||||
// Creates a new QR Code with the given version number,
|
||||
// error correction level, data codeword bytes, and mask number.
|
||||
// This is a low-level API that most users should not use directly.
|
||||
// A mid-level API is the encodeSegments() function.
|
||||
function QrCode(
|
||||
// The version number of this QR Code, which is between 1 and 40 (inclusive).
|
||||
// This determines the size of this barcode.
|
||||
version,
|
||||
// The error correction level used in this QR Code.
|
||||
errorCorrectionLevel, dataCodewords,
|
||||
// The index of the mask pattern used in this QR Code, which is between 0 and 7 (inclusive).
|
||||
// Even if a QR Code is created with automatic masking requested (mask = -1),
|
||||
// the resulting object still has a mask value between 0 and 7.
|
||||
mask) {
|
||||
this.version = version;
|
||||
this.errorCorrectionLevel = errorCorrectionLevel;
|
||||
this.mask = mask;
|
||||
// The modules of this QR Code (false = white, true = black).
|
||||
// Immutable after constructor finishes. Accessed through getModule().
|
||||
this.modules = [];
|
||||
// Indicates function modules that are not subjected to masking. Discarded when constructor finishes.
|
||||
this.isFunction = [];
|
||||
// Check scalar arguments
|
||||
if (version < QrCode.MIN_VERSION || version > QrCode.MAX_VERSION)
|
||||
throw "Version value out of range";
|
||||
if (mask < -1 || mask > 7)
|
||||
throw "Mask value out of range";
|
||||
this.size = version * 4 + 17;
|
||||
// Initialize both grids to be size*size arrays of Boolean false
|
||||
var row = [];
|
||||
for (var i = 0; i < this.size; i++)
|
||||
row.push(false);
|
||||
for (var i = 0; i < this.size; i++) {
|
||||
this.modules.push(row.slice()); // Initially all white
|
||||
this.isFunction.push(row.slice());
|
||||
}
|
||||
// Compute ECC, draw modules
|
||||
this.drawFunctionPatterns();
|
||||
var allCodewords = this.addEccAndInterleave(dataCodewords);
|
||||
this.drawCodewords(allCodewords);
|
||||
// Do masking
|
||||
if (mask == -1) { // Automatically choose best mask
|
||||
var minPenalty = 1000000000;
|
||||
for (var i = 0; i < 8; i++) {
|
||||
this.applyMask(i);
|
||||
this.drawFormatBits(i);
|
||||
var penalty = this.getPenaltyScore();
|
||||
if (penalty < minPenalty) {
|
||||
mask = i;
|
||||
minPenalty = penalty;
|
||||
}
|
||||
this.applyMask(i); // Undoes the mask due to XOR
|
||||
}
|
||||
}
|
||||
if (mask < 0 || mask > 7)
|
||||
throw "Assertion error";
|
||||
this.mask = mask;
|
||||
this.applyMask(mask); // Apply the final choice of mask
|
||||
this.drawFormatBits(mask); // Overwrite old format bits
|
||||
this.isFunction = [];
|
||||
}
|
||||
/*-- Static factory functions (high level) --*/
|
||||
// Returns a QR Code representing the given Unicode text string at the given error correction level.
|
||||
// As a conservative upper bound, this function is guaranteed to succeed for strings that have 738 or fewer
|
||||
// Unicode code points (not UTF-16 code units) if the low error correction level is used. The smallest possible
|
||||
// QR Code version is automatically chosen for the output. The ECC level of the result may be higher than the
|
||||
// ecl argument if it can be done without increasing the version.
|
||||
QrCode.encodeText = function (text, ecl) {
|
||||
var segs = qrcodegen.QrSegment.makeSegments(text);
|
||||
return QrCode.encodeSegments(segs, ecl);
|
||||
};
|
||||
// Returns a QR Code representing the given binary data at the given error correction level.
|
||||
// This function always encodes using the binary segment mode, not any text mode. The maximum number of
|
||||
// bytes allowed is 2953. The smallest possible QR Code version is automatically chosen for the output.
|
||||
// The ECC level of the result may be higher than the ecl argument if it can be done without increasing the version.
|
||||
QrCode.encodeBinary = function (data, ecl) {
|
||||
var seg = qrcodegen.QrSegment.makeBytes(data);
|
||||
return QrCode.encodeSegments([seg], ecl);
|
||||
};
|
||||
/*-- Static factory functions (mid level) --*/
|
||||
// Returns a QR Code representing the given segments with the given encoding parameters.
|
||||
// The smallest possible QR Code version within the given range is automatically
|
||||
// chosen for the output. Iff boostEcl is true, then the ECC level of the result
|
||||
// may be higher than the ecl argument if it can be done without increasing the
|
||||
// version. The mask number is either between 0 to 7 (inclusive) to force that
|
||||
// mask, or -1 to automatically choose an appropriate mask (which may be slow).
|
||||
// This function allows the user to create a custom sequence of segments that switches
|
||||
// between modes (such as alphanumeric and byte) to encode text in less space.
|
||||
// This is a mid-level API; the high-level API is encodeText() and encodeBinary().
|
||||
QrCode.encodeSegments = function (segs, ecl, minVersion, maxVersion, mask, boostEcl) {
|
||||
if (minVersion === void 0) { minVersion = 1; }
|
||||
if (maxVersion === void 0) { maxVersion = 40; }
|
||||
if (mask === void 0) { mask = -1; }
|
||||
if (boostEcl === void 0) { boostEcl = true; }
|
||||
if (!(QrCode.MIN_VERSION <= minVersion && minVersion <= maxVersion && maxVersion <= QrCode.MAX_VERSION)
|
||||
|| mask < -1 || mask > 7)
|
||||
throw "Invalid value";
|
||||
// Find the minimal version number to use
|
||||
var version;
|
||||
var dataUsedBits;
|
||||
for (version = minVersion;; version++) {
|
||||
var dataCapacityBits_1 = QrCode.getNumDataCodewords(version, ecl) * 8; // Number of data bits available
|
||||
var usedBits = QrSegment.getTotalBits(segs, version);
|
||||
if (usedBits <= dataCapacityBits_1) {
|
||||
dataUsedBits = usedBits;
|
||||
break; // This version number is found to be suitable
|
||||
}
|
||||
if (version >= maxVersion) // All versions in the range could not fit the given data
|
||||
throw "Data too long";
|
||||
}
|
||||
// Increase the error correction level while the data still fits in the current version number
|
||||
for (var _i = 0, _a = [QrCode.Ecc.MEDIUM, QrCode.Ecc.QUARTILE, QrCode.Ecc.HIGH]; _i < _a.length; _i++) { // From low to high
|
||||
var newEcl = _a[_i];
|
||||
if (boostEcl && dataUsedBits <= QrCode.getNumDataCodewords(version, newEcl) * 8)
|
||||
ecl = newEcl;
|
||||
}
|
||||
// Concatenate all segments to create the data bit string
|
||||
var bb = [];
|
||||
for (var _b = 0, segs_1 = segs; _b < segs_1.length; _b++) {
|
||||
var seg = segs_1[_b];
|
||||
appendBits(seg.mode.modeBits, 4, bb);
|
||||
appendBits(seg.numChars, seg.mode.numCharCountBits(version), bb);
|
||||
for (var _c = 0, _d = seg.getData(); _c < _d.length; _c++) {
|
||||
var b = _d[_c];
|
||||
bb.push(b);
|
||||
}
|
||||
}
|
||||
if (bb.length != dataUsedBits)
|
||||
throw "Assertion error";
|
||||
// Add terminator and pad up to a byte if applicable
|
||||
var dataCapacityBits = QrCode.getNumDataCodewords(version, ecl) * 8;
|
||||
if (bb.length > dataCapacityBits)
|
||||
throw "Assertion error";
|
||||
appendBits(0, Math.min(4, dataCapacityBits - bb.length), bb);
|
||||
appendBits(0, (8 - bb.length % 8) % 8, bb);
|
||||
if (bb.length % 8 != 0)
|
||||
throw "Assertion error";
|
||||
// Pad with alternating bytes until data capacity is reached
|
||||
for (var padByte = 0xEC; bb.length < dataCapacityBits; padByte ^= 0xEC ^ 0x11)
|
||||
appendBits(padByte, 8, bb);
|
||||
// Pack bits into bytes in big endian
|
||||
var dataCodewords = [];
|
||||
while (dataCodewords.length * 8 < bb.length)
|
||||
dataCodewords.push(0);
|
||||
bb.forEach(function (b, i) {
|
||||
return dataCodewords[i >>> 3] |= b << (7 - (i & 7));
|
||||
});
|
||||
// Create the QR Code object
|
||||
return new QrCode(version, ecl, dataCodewords, mask);
|
||||
};
|
||||
/*-- Accessor methods --*/
|
||||
// Returns the color of the module (pixel) at the given coordinates, which is false
|
||||
// for white or true for black. The top left corner has the coordinates (x=0, y=0).
|
||||
// If the given coordinates are out of bounds, then false (white) is returned.
|
||||
QrCode.prototype.getModule = function (x, y) {
|
||||
return 0 <= x && x < this.size && 0 <= y && y < this.size && this.modules[y][x];
|
||||
};
|
||||
/*-- Public instance methods --*/
|
||||
// Draws this QR Code, with the given module scale and border modules, onto the given HTML
|
||||
// canvas element. The canvas's width and height is resized to (this.size + border * 2) * scale.
|
||||
// The drawn image is be purely black and white, and fully opaque.
|
||||
// The scale must be a positive integer and the border must be a non-negative integer.
|
||||
QrCode.prototype.drawCanvas = function (scale, border, canvas) {
|
||||
if (scale <= 0 || border < 0)
|
||||
throw "Value out of range";
|
||||
var width = (this.size + border * 2) * scale;
|
||||
canvas.width = width;
|
||||
canvas.height = width;
|
||||
var ctx = canvas.getContext("2d");
|
||||
for (var y = -border; y < this.size + border; y++) {
|
||||
for (var x = -border; x < this.size + border; x++) {
|
||||
ctx.fillStyle = this.getModule(x, y) ? "#000000" : "#FFFFFF";
|
||||
ctx.fillRect((x + border) * scale, (y + border) * scale, scale, scale);
|
||||
}
|
||||
}
|
||||
};
|
||||
// Returns a string of SVG code for an image depicting this QR Code, with the given number
|
||||
// of border modules. The string always uses Unix newlines (\n), regardless of the platform.
|
||||
QrCode.prototype.toSvgString = function (border) {
|
||||
if (border < 0)
|
||||
throw "Border must be non-negative";
|
||||
var parts = [];
|
||||
for (var y = 0; y < this.size; y++) {
|
||||
for (var x = 0; x < this.size; x++) {
|
||||
if (this.getModule(x, y))
|
||||
parts.push("M" + (x + border) + "," + (y + border) + "h1v1h-1z");
|
||||
}
|
||||
}
|
||||
return "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<!DOCTYPE svg PUBLIC \"-//W3C//DTD SVG 1.1//EN\" \"http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd\">\n<svg xmlns=\"http://www.w3.org/2000/svg\" version=\"1.1\" viewBox=\"0 0 " + (this.size + border * 2) + " " + (this.size + border * 2) + "\" stroke=\"none\">\n\t<rect width=\"100%\" height=\"100%\" fill=\"#FFFFFF\"/>\n\t<path d=\"" + parts.join(" ") + "\" fill=\"#000000\"/>\n</svg>\n";
|
||||
};
|
||||
/*-- Private helper methods for constructor: Drawing function modules --*/
|
||||
// Reads this object's version field, and draws and marks all function modules.
|
||||
QrCode.prototype.drawFunctionPatterns = function () {
|
||||
// Draw horizontal and vertical timing patterns
|
||||
for (var i = 0; i < this.size; i++) {
|
||||
this.setFunctionModule(6, i, i % 2 == 0);
|
||||
this.setFunctionModule(i, 6, i % 2 == 0);
|
||||
}
|
||||
// Draw 3 finder patterns (all corners except bottom right; overwrites some timing modules)
|
||||
this.drawFinderPattern(3, 3);
|
||||
this.drawFinderPattern(this.size - 4, 3);
|
||||
this.drawFinderPattern(3, this.size - 4);
|
||||
// Draw numerous alignment patterns
|
||||
var alignPatPos = this.getAlignmentPatternPositions();
|
||||
var numAlign = alignPatPos.length;
|
||||
for (var i = 0; i < numAlign; i++) {
|
||||
for (var j = 0; j < numAlign; j++) {
|
||||
// Don't draw on the three finder corners
|
||||
if (!(i == 0 && j == 0 || i == 0 && j == numAlign - 1 || i == numAlign - 1 && j == 0))
|
||||
this.drawAlignmentPattern(alignPatPos[i], alignPatPos[j]);
|
||||
}
|
||||
}
|
||||
// Draw configuration data
|
||||
this.drawFormatBits(0); // Dummy mask value; overwritten later in the constructor
|
||||
this.drawVersion();
|
||||
};
|
||||
// Draws two copies of the format bits (with its own error correction code)
|
||||
// based on the given mask and this object's error correction level field.
|
||||
QrCode.prototype.drawFormatBits = function (mask) {
|
||||
// Calculate error correction code and pack bits
|
||||
var data = this.errorCorrectionLevel.formatBits << 3 | mask; // errCorrLvl is uint2, mask is uint3
|
||||
var rem = data;
|
||||
for (var i = 0; i < 10; i++)
|
||||
rem = (rem << 1) ^ ((rem >>> 9) * 0x537);
|
||||
var bits = (data << 10 | rem) ^ 0x5412; // uint15
|
||||
if (bits >>> 15 != 0)
|
||||
throw "Assertion error";
|
||||
// Draw first copy
|
||||
for (var i = 0; i <= 5; i++)
|
||||
this.setFunctionModule(8, i, getBit(bits, i));
|
||||
this.setFunctionModule(8, 7, getBit(bits, 6));
|
||||
this.setFunctionModule(8, 8, getBit(bits, 7));
|
||||
this.setFunctionModule(7, 8, getBit(bits, 8));
|
||||
for (var i = 9; i < 15; i++)
|
||||
this.setFunctionModule(14 - i, 8, getBit(bits, i));
|
||||
// Draw second copy
|
||||
for (var i = 0; i < 8; i++)
|
||||
this.setFunctionModule(this.size - 1 - i, 8, getBit(bits, i));
|
||||
for (var i = 8; i < 15; i++)
|
||||
this.setFunctionModule(8, this.size - 15 + i, getBit(bits, i));
|
||||
this.setFunctionModule(8, this.size - 8, true); // Always black
|
||||
};
|
||||
// Draws two copies of the version bits (with its own error correction code),
|
||||
// based on this object's version field, iff 7 <= version <= 40.
|
||||
QrCode.prototype.drawVersion = function () {
|
||||
if (this.version < 7)
|
||||
return;
|
||||
// Calculate error correction code and pack bits
|
||||
var rem = this.version; // version is uint6, in the range [7, 40]
|
||||
for (var i = 0; i < 12; i++)
|
||||
rem = (rem << 1) ^ ((rem >>> 11) * 0x1F25);
|
||||
var bits = this.version << 12 | rem; // uint18
|
||||
if (bits >>> 18 != 0)
|
||||
throw "Assertion error";
|
||||
// Draw two copies
|
||||
for (var i = 0; i < 18; i++) {
|
||||
var color = getBit(bits, i);
|
||||
var a = this.size - 11 + i % 3;
|
||||
var b = Math.floor(i / 3);
|
||||
this.setFunctionModule(a, b, color);
|
||||
this.setFunctionModule(b, a, color);
|
||||
}
|
||||
};
|
||||
// Draws a 9*9 finder pattern including the border separator,
|
||||
// with the center module at (x, y). Modules can be out of bounds.
|
||||
QrCode.prototype.drawFinderPattern = function (x, y) {
|
||||
for (var dy = -4; dy <= 4; dy++) {
|
||||
for (var dx = -4; dx <= 4; dx++) {
|
||||
var dist = Math.max(Math.abs(dx), Math.abs(dy)); // Chebyshev/infinity norm
|
||||
var xx = x + dx;
|
||||
var yy = y + dy;
|
||||
if (0 <= xx && xx < this.size && 0 <= yy && yy < this.size)
|
||||
this.setFunctionModule(xx, yy, dist != 2 && dist != 4);
|
||||
}
|
||||
}
|
||||
};
|
||||
// Draws a 5*5 alignment pattern, with the center module
|
||||
// at (x, y). All modules must be in bounds.
|
||||
QrCode.prototype.drawAlignmentPattern = function (x, y) {
|
||||
for (var dy = -2; dy <= 2; dy++) {
|
||||
for (var dx = -2; dx <= 2; dx++)
|
||||
this.setFunctionModule(x + dx, y + dy, Math.max(Math.abs(dx), Math.abs(dy)) != 1);
|
||||
}
|
||||
};
|
||||
// Sets the color of a module and marks it as a function module.
|
||||
// Only used by the constructor. Coordinates must be in bounds.
|
||||
QrCode.prototype.setFunctionModule = function (x, y, isBlack) {
|
||||
this.modules[y][x] = isBlack;
|
||||
this.isFunction[y][x] = true;
|
||||
};
|
||||
/*-- Private helper methods for constructor: Codewords and masking --*/
|
||||
// Returns a new byte string representing the given data with the appropriate error correction
|
||||
// codewords appended to it, based on this object's version and error correction level.
|
||||
QrCode.prototype.addEccAndInterleave = function (data) {
|
||||
var ver = this.version;
|
||||
var ecl = this.errorCorrectionLevel;
|
||||
if (data.length != QrCode.getNumDataCodewords(ver, ecl))
|
||||
throw "Invalid argument";
|
||||
// Calculate parameter numbers
|
||||
var numBlocks = QrCode.NUM_ERROR_CORRECTION_BLOCKS[ecl.ordinal][ver];
|
||||
var blockEccLen = QrCode.ECC_CODEWORDS_PER_BLOCK[ecl.ordinal][ver];
|
||||
var rawCodewords = Math.floor(QrCode.getNumRawDataModules(ver) / 8);
|
||||
var numShortBlocks = numBlocks - rawCodewords % numBlocks;
|
||||
var shortBlockLen = Math.floor(rawCodewords / numBlocks);
|
||||
// Split data into blocks and append ECC to each block
|
||||
var blocks = [];
|
||||
var rsDiv = QrCode.reedSolomonComputeDivisor(blockEccLen);
|
||||
for (var i = 0, k = 0; i < numBlocks; i++) {
|
||||
var dat = data.slice(k, k + shortBlockLen - blockEccLen + (i < numShortBlocks ? 0 : 1));
|
||||
k += dat.length;
|
||||
var ecc = QrCode.reedSolomonComputeRemainder(dat, rsDiv);
|
||||
if (i < numShortBlocks)
|
||||
dat.push(0);
|
||||
blocks.push(dat.concat(ecc));
|
||||
}
|
||||
// Interleave (not concatenate) the bytes from every block into a single sequence
|
||||
var result = [];
|
||||
for (var i = 0; i < blocks[0].length; i++) {
|
||||
for (var j = 0; j < blocks.length; j++) {
|
||||
// Skip the padding byte in short blocks
|
||||
if (i != shortBlockLen - blockEccLen || j >= numShortBlocks)
|
||||
result.push(blocks[j][i]);
|
||||
}
|
||||
}
|
||||
if (result.length != rawCodewords)
|
||||
throw "Assertion error";
|
||||
return result;
|
||||
};
|
||||
// Draws the given sequence of 8-bit codewords (data and error correction) onto the entire
|
||||
// data area of this QR Code. Function modules need to be marked off before this is called.
|
||||
QrCode.prototype.drawCodewords = function (data) {
|
||||
if (data.length != Math.floor(QrCode.getNumRawDataModules(this.version) / 8))
|
||||
throw "Invalid argument";
|
||||
var i = 0; // Bit index into the data
|
||||
// Do the funny zigzag scan
|
||||
for (var right = this.size - 1; right >= 1; right -= 2) { // Index of right column in each column pair
|
||||
if (right == 6)
|
||||
right = 5;
|
||||
for (var vert = 0; vert < this.size; vert++) { // Vertical counter
|
||||
for (var j = 0; j < 2; j++) {
|
||||
var x = right - j; // Actual x coordinate
|
||||
var upward = ((right + 1) & 2) == 0;
|
||||
var y = upward ? this.size - 1 - vert : vert; // Actual y coordinate
|
||||
if (!this.isFunction[y][x] && i < data.length * 8) {
|
||||
this.modules[y][x] = getBit(data[i >>> 3], 7 - (i & 7));
|
||||
i++;
|
||||
}
|
||||
// If this QR Code has any remainder bits (0 to 7), they were assigned as
|
||||
// 0/false/white by the constructor and are left unchanged by this method
|
||||
}
|
||||
}
|
||||
}
|
||||
if (i != data.length * 8)
|
||||
throw "Assertion error";
|
||||
};
|
||||
// XORs the codeword modules in this QR Code with the given mask pattern.
|
||||
// The function modules must be marked and the codeword bits must be drawn
|
||||
// before masking. Due to the arithmetic of XOR, calling applyMask() with
|
||||
// the same mask value a second time will undo the mask. A final well-formed
|
||||
// QR Code needs exactly one (not zero, two, etc.) mask applied.
|
||||
QrCode.prototype.applyMask = function (mask) {
|
||||
if (mask < 0 || mask > 7)
|
||||
throw "Mask value out of range";
|
||||
for (var y = 0; y < this.size; y++) {
|
||||
for (var x = 0; x < this.size; x++) {
|
||||
var invert = void 0;
|
||||
switch (mask) {
|
||||
case 0:
|
||||
invert = (x + y) % 2 == 0;
|
||||
break;
|
||||
case 1:
|
||||
invert = y % 2 == 0;
|
||||
break;
|
||||
case 2:
|
||||
invert = x % 3 == 0;
|
||||
break;
|
||||
case 3:
|
||||
invert = (x + y) % 3 == 0;
|
||||
break;
|
||||
case 4:
|
||||
invert = (Math.floor(x / 3) + Math.floor(y / 2)) % 2 == 0;
|
||||
break;
|
||||
case 5:
|
||||
invert = x * y % 2 + x * y % 3 == 0;
|
||||
break;
|
||||
case 6:
|
||||
invert = (x * y % 2 + x * y % 3) % 2 == 0;
|
||||
break;
|
||||
case 7:
|
||||
invert = ((x + y) % 2 + x * y % 3) % 2 == 0;
|
||||
break;
|
||||
default: throw "Assertion error";
|
||||
}
|
||||
if (!this.isFunction[y][x] && invert)
|
||||
this.modules[y][x] = !this.modules[y][x];
|
||||
}
|
||||
}
|
||||
};
|
||||
// Calculates and returns the penalty score based on state of this QR Code's current modules.
|
||||
// This is used by the automatic mask choice algorithm to find the mask pattern that yields the lowest score.
|
||||
QrCode.prototype.getPenaltyScore = function () {
|
||||
var result = 0;
|
||||
// Adjacent modules in row having same color, and finder-like patterns
|
||||
for (var y = 0; y < this.size; y++) {
|
||||
var runColor = false;
|
||||
var runX = 0;
|
||||
var runHistory = [0, 0, 0, 0, 0, 0, 0];
|
||||
var padRun = this.size;
|
||||
for (var x = 0; x < this.size; x++) {
|
||||
if (this.modules[y][x] == runColor) {
|
||||
runX++;
|
||||
if (runX == 5)
|
||||
result += QrCode.PENALTY_N1;
|
||||
else if (runX > 5)
|
||||
result++;
|
||||
}
|
||||
else {
|
||||
QrCode.finderPenaltyAddHistory(runX + padRun, runHistory);
|
||||
padRun = 0;
|
||||
if (!runColor)
|
||||
result += this.finderPenaltyCountPatterns(runHistory) * QrCode.PENALTY_N3;
|
||||
runColor = this.modules[y][x];
|
||||
runX = 1;
|
||||
}
|
||||
}
|
||||
result += this.finderPenaltyTerminateAndCount(runColor, runX + padRun, runHistory) * QrCode.PENALTY_N3;
|
||||
}
|
||||
// Adjacent modules in column having same color, and finder-like patterns
|
||||
for (var x = 0; x < this.size; x++) {
|
||||
var runColor = false;
|
||||
var runY = 0;
|
||||
var runHistory = [0, 0, 0, 0, 0, 0, 0];
|
||||
var padRun = this.size;
|
||||
for (var y = 0; y < this.size; y++) {
|
||||
if (this.modules[y][x] == runColor) {
|
||||
runY++;
|
||||
if (runY == 5)
|
||||
result += QrCode.PENALTY_N1;
|
||||
else if (runY > 5)
|
||||
result++;
|
||||
}
|
||||
else {
|
||||
QrCode.finderPenaltyAddHistory(runY + padRun, runHistory);
|
||||
padRun = 0;
|
||||
if (!runColor)
|
||||
result += this.finderPenaltyCountPatterns(runHistory) * QrCode.PENALTY_N3;
|
||||
runColor = this.modules[y][x];
|
||||
runY = 1;
|
||||
}
|
||||
}
|
||||
result += this.finderPenaltyTerminateAndCount(runColor, runY + padRun, runHistory) * QrCode.PENALTY_N3;
|
||||
}
|
||||
// 2*2 blocks of modules having same color
|
||||
for (var y = 0; y < this.size - 1; y++) {
|
||||
for (var x = 0; x < this.size - 1; x++) {
|
||||
var color = this.modules[y][x];
|
||||
if (color == this.modules[y][x + 1] &&
|
||||
color == this.modules[y + 1][x] &&
|
||||
color == this.modules[y + 1][x + 1])
|
||||
result += QrCode.PENALTY_N2;
|
||||
}
|
||||
}
|
||||
// Balance of black and white modules
|
||||
var black = 0;
|
||||
for (var _i = 0, _a = this.modules; _i < _a.length; _i++) {
|
||||
var row = _a[_i];
|
||||
for (var _b = 0, row_1 = row; _b < row_1.length; _b++) {
|
||||
var color = row_1[_b];
|
||||
if (color)
|
||||
black++;
|
||||
}
|
||||
}
|
||||
var total = this.size * this.size; // Note that size is odd, so black/total != 1/2
|
||||
// Compute the smallest integer k >= 0 such that (45-5k)% <= black/total <= (55+5k)%
|
||||
var k = Math.ceil(Math.abs(black * 20 - total * 10) / total) - 1;
|
||||
result += k * QrCode.PENALTY_N4;
|
||||
return result;
|
||||
};
|
||||
/*-- Private helper functions --*/
|
||||
// Returns an ascending list of positions of alignment patterns for this version number.
|
||||
// Each position is in the range [0,177), and are used on both the x and y axes.
|
||||
// This could be implemented as lookup table of 40 variable-length lists of integers.
|
||||
QrCode.prototype.getAlignmentPatternPositions = function () {
|
||||
if (this.version == 1)
|
||||
return [];
|
||||
else {
|
||||
var numAlign = Math.floor(this.version / 7) + 2;
|
||||
var step = (this.version == 32) ? 26 :
|
||||
Math.ceil((this.size - 13) / (numAlign * 2 - 2)) * 2;
|
||||
var result = [6];
|
||||
for (var pos = this.size - 7; result.length < numAlign; pos -= step)
|
||||
result.splice(1, 0, pos);
|
||||
return result;
|
||||
}
|
||||
};
|
||||
// Returns the number of data bits that can be stored in a QR Code of the given version number, after
|
||||
// all function modules are excluded. This includes remainder bits, so it might not be a multiple of 8.
|
||||
|