forked from quiet/quiet-js
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathquiet.js.html
630 lines (541 loc) · 22.7 KB
/
quiet.js.html
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>JSDoc: Source: quiet.js</title>
<script src="scripts/prettify/prettify.js"> </script>
<script src="scripts/prettify/lang-css.js"> </script>
<!--[if lt IE 9]>
<script src="//html5shiv.googlecode.com/svn/trunk/html5.js"></script>
<![endif]-->
<link type="text/css" rel="stylesheet" href="styles/prettify-tomorrow.css">
<link type="text/css" rel="stylesheet" href="styles/jsdoc-default.css">
</head>
<body>
<div id="main">
<h1 class="page-title">Source: quiet.js</h1>
<section>
<article>
<pre class="prettyprint source"><code>/* Copyright 2016, Brian Armstrong
* quiet.js includes compiled portions from other sources
* - liquid DSP, Copyright (c) 2007-2016 Joseph Gaeddert
* - libjansson, Copyright (c) 2009-2016 Petri Lehtinen
* - emscripten, Copyright (c) 2010-2016 Emscripten authors
*/
/** @namespace */
var Quiet = (function() {
// sampleBufferSize is the number of audio samples we'll write per onaudioprocess call
// must be a power of two. we choose the absolute largest permissible value
// we implicitly assume that the browser will play back a written buffer without any gaps
var sampleBufferSize = 16384;
// initialization flags
var emscriptenInitialized = false;
var profilesFetched = false;
// profiles is the string content of quiet-profiles.json
var profiles;
// our local instance of window.AudioContext
var audioCtx;
// consumer callbacks. these fire once quiet is ready to create transmitter/receiver
var readyCallbacks = [];
var readyErrbacks = [];
var failReason = "";
// these are used for receiver only
var gUM;
var audioInput;
var audioInputFailedReason = "";
var audioInputReadyCallbacks = [];
var audioInputFailedCallbacks = [];
var frameBufferSize = Math.pow(2, 14);
// anti-gc
var receivers = [];
// isReady tells us if we can start creating transmitters and receivers
// we need the emscripten portion to be running and we need our
// async fetch of the profiles to be completed
function isReady() {
return emscriptenInitialized && profilesFetched;
};
function isFailed() {
return failReason !== "";
};
// start gets our AudioContext and notifies consumers that quiet can be used
function start() {
audioCtx = new (window.AudioContext || window.webkitAudioContext)();
console.log(audioCtx.sampleRate);
var len = readyCallbacks.length;
for (var i = 0; i < len; i++) {
readyCallbacks[i]();
}
};
function fail(reason) {
failReason = reason;
var len = readyErrbacks.length;
for (var i = 0; i < len; i++) {
readyErrbacks[i](reason);
}
};
function checkInitState() {
if (isReady()) {
start();
}
};
function onProfilesFetch(p) {
profiles = p;
profilesFetched = true;
checkInitState();
};
// this is intended to be called only by emscripten
function onEmscriptenInitialized() {
emscriptenInitialized = true;
checkInitState();
};
/**
* Set the path prefix of quiet-profiles.json and do an async fetch of that path.
* This file is used to configure transmitter and receiver parameters.
* <br><br>
* This function must be called before creating a transmitter or receiver.
* @function setProfilesPrefix
* @memberof Quiet
* @param {string} prefix - The path prefix where Quiet will fetch quiet-profiles.json
* @example
* setProfilesPrefix("/js/"); // fetches /js/quiet-profiles.json
*/
function setProfilesPrefix(prefix) {
if (profilesFetched) {
return;
}
if (!prefix.endsWith("/")) {
prefix += "/";
}
var profilesPath = prefix + "quiet-profiles.json";
var fetch = new Promise(function(resolve, reject) {
var xhr = new XMLHttpRequest();
xhr.overrideMimeType("application/json");
xhr.open("GET", profilesPath, true);
xhr.onload = function() {
if (this.status >= 200 && this.status < 300) {
resolve(this.responseText);
} else {
reject(this.statusText);
}
};
xhr.onerror = function() {
reject(this.statusText);
};
xhr.send();
});
fetch.then(function(body) {
onProfilesFetch(body);
}, function(err) {
fail("fetch of quiet-profiles.json failed: " + err);
});
};
/**
* Set the path prefix of quiet-emscripten.js.mem.
* This file is used to initialize the memory state of emscripten.
* <br><br>
* This function must be called before quiet-emscripten.js has started loading.
* If it is not called first, then emscripten will default to a prefix of "".
* @function setMemoryInitializerPrefix
* @memberof Quiet
* @param {string} prefix - The path prefix where emscripten will fetch quiet-emscripten.js.mem
* @example
* setMemoryInitializerPrefix("/"); // fetches /quiet-emscripten.js.mem
*/
function setMemoryInitializerPrefix(prefix) {
Module.memoryInitializerPrefixURL = prefix;
}
/**
* Set the path prefix of libfec.js.
* Although not strictly required, it is highly recommended to include this library.
* <br><br>
* This function, if used, must be called before quiet-emscripten.js has started loading.
* If it is not called first, then emscripten will not load libfec.js.
* @function setLibfecPrefix
* @memberof Quiet
* @param {string} prefix - The path prefix where emscripten will fetch libfec.js
* @example
* setLibfecPrefix("/"); // fetches /libfec.js
*/
function setLibfecPrefix(prefix) {
Module.dynamicLibraries = Module.dynamicLibraries || [];
Module.dynamicLibraries.push(prefix + "libfec.js");
}
/**
* Callback to notify user that quiet.js failed to initialize
*
* @callback onError
* @memberof Quiet
* @param {string} reason - error message related to failure
*/
/**
* Add a callback to be called when Quiet is ready for use, e.g. when transmitters and receivers can be created.
* @function addReadyCallback
* @memberof Quiet
* @param {function} c - The user function which will be called
* @param {onError} [onError] - User errback function
* @example
* addReadyCallback(function() { console.log("ready!"); });
*/
function addReadyCallback(c, errback) {
if (isReady()) {
c();
return;
}
readyCallbacks.push(c);
if (errback !== undefined) {
if (isFailed()) {
errback(failReason);
return;
}
readyErrbacks.push(errback);
}
}
/**
* Callback used by transmit to notify user that transmission has finished
* @callback onTransmitFinish
* @memberof Quiet
*/
/**
* Callback for user to provide data to a Quiet transmitter
* <br><br>
* This callback may be used multiple times, but the user must wait for the finished callback between subsequent calls.
* @callback transmit
* @memberof Quiet
* @param {ArrayBuffer} payload - bytes which will be encoded and sent to speaker
* @param {onTransmitFinish} [done] - callback to notify user that transmission has completed
* @example
* transmit(Quiet.str2ab("Hello, World!"), function() { console.log("transmission complete"); });
*/
/**
* Create a new transmitter configured by the given profile name.
* @function transmitter
* @memberof Quiet
* @param {string} profile - name of profile to use, must be a key in quiet-profiles.json
* @returns {transmit} transmit - transmit callback which user calls to start transmission
* @example
* var transmit = transmitter("robust");
* transmit(Quiet.str2ab("Hello, World!"), function() { console.log("transmission complete"); });
*/
function transmitter(profile) {
// get an encoder_options object for our quiet-profiles.json and profile key
var c_profiles = Module.intArrayFromString(profiles);
var c_profile = Module.intArrayFromString(profile);
var opt = Module.ccall('quiet_encoder_profile_str', 'pointer', ['array', 'array'], [c_profiles, c_profile]);
// libquiet internally works at 44.1kHz but the local sound card may be a different rate. we inform quiet about that here
var encoder = Module.ccall('quiet_encoder_create', 'pointer', ['pointer', 'number'], [opt, audioCtx.sampleRate]);
// some profiles have an option called close_frame which prevents data frames from overlapping multiple
// sample buffers. this is very convenient if our system is not fast enough to feed the sound card
// without any gaps between subsequent buffers due to e.g. gc pause. inform quiet about our
// sample buffer size here so that it can reduce the frame length if this profile has close_frame enabled.
var frame_len = Module.ccall('quiet_encoder_clamp_frame_len', 'number', ['pointer', 'number'], [encoder, sampleBufferSize]);
var samples = Module.ccall('malloc', 'pointer', ['number'], [4 * sampleBufferSize]);
// return user transmit function
return function(buf, done) {
var payload = new Uint8Array(buf);
var payloadOffset = 0;
// fill as much of quiet's transmit queue as possible
var writebuf = function() {
if (payloadOffset == payload.length) {
return;
}
for (var i = payloadOffset; i < payload.length; ) {
var frame = payload.subarray(payloadOffset, payloadOffset + frame_len);
var written = Module.ccall('quiet_encoder_send', 'number', ['pointer', 'array', 'number'], [encoder, frame, frame.length]);
if (written === -1) {
break;
}
payloadOffset += frame.length;
i += frame.length;
}
};
writebuf();
// yes, this is pointer arithmetic, in javascript :)
var sample_view = Module.HEAPF32.subarray((samples/4), (samples/4) + sampleBufferSize);
var script_processor = (audioCtx.createScriptProcessor || audioCtx.createJavaScriptNode);
var transmitter = script_processor.call(audioCtx, sampleBufferSize, 1, 2);
var finished = false;
transmitter.onaudioprocess = function(e) {
var output_l = e.outputBuffer.getChannelData(0);
if (finished) {
for (var i = 0; i < sampleBufferSize; i++) {
output_l[i] = 0;
}
return;
}
var written = Module.ccall('quiet_encoder_emit', 'number', ['pointer', 'pointer', 'number'], [encoder, samples, sampleBufferSize]);
output_l.set(sample_view);
// libquiet notifies us that the payload is finished by returning written < number of samples we asked for
if (written < sampleBufferSize) {
// be extra cautious and 0-fill what's left
// (we want the end of transmission to be silence, not potentially loud noise)
for (var i = written; i < sampleBufferSize; i++) {
output_l[i] = 0;
}
// user callback
if (done !== undefined) {
done();
}
finished = true;
window.setTimeout(function() { transmitter.disconnect(); }, 1500);
}
window.setTimeout(writebuf, 0);
};
// put an input node on the graph. some browsers require this to run our script processor
// this oscillator will not actually be used in any way
var dummy_osc = audioCtx.createOscillator();
dummy_osc.type = 'square';
dummy_osc.frequency.value = 420;
dummy_osc.connect(transmitter);
transmitter.connect(audioCtx.destination);
};
};
// receiver functions
function audioInputReady() {
var len = audioInputReadyCallbacks.length;
for (var i = 0; i < len; i++) {
audioInputReadyCallbacks[i]();
}
};
function audioInputFailed(reason) {
audioInputFailedReason = reason;
var len = audioInputFailedCallbacks.length;
for (var i = 0; i < len; i++) {
audioInputFailedCallbacks[i](audioInputFailedReason);
}
};
function addAudioInputReadyCallback(c, errback) {
if (errback !== undefined) {
if (audioInputFailedReason !== "") {
errback(audioInputFailedReason);
return
}
audioInputFailedCallbacks.push(errback);
}
if (audioInput instanceof MediaStreamAudioSourceNode) {
c();
return
}
audioInputReadyCallbacks.push(c);
}
function gUMConstraints() {
if (navigator.webkitGetUserMedia !== undefined) {
return {
audio: {
optional: [
{googAutoGainControl: false},
{googAutoGainControl2: false},
{echoCancellation: false},
{googEchoCancellation: false},
{googEchoCancellation2: false},
{googDAEchoCancellation: false},
{googNoiseSuppression: false},
{googNoiseSuppression2: false},
{googHighpassFilter: false},
{googTypingNoiseDetection: false},
{googAudioMirroring: false}
]
}
};
}
if (navigator.mozGetUserMedia !== undefined) {
return {
audio: {
echoCancellation: false,
mozAutoGainControl: false,
mozNoiseSuppression: false
}
};
}
return {
audio: {
echoCancellation: false
}
};
};
function createAudioInput() {
audioInput = 0; // prevent others from trying to create
gUM.call(navigator, gUMConstraints(),
function(e) {
audioInput = audioCtx.createMediaStreamSource(e);
// stash a very permanent reference so this isn't collected
window.quiet_receiver_anti_gc = audioInput;
audioInputReady();
}, function(reason) {
audioInputFailed(reason.name);
});
};
/**
* Callback used by receiver to notify user that a frame was received but
* failed checksum. Frames that fail checksum are not sent to onReceive.
*
* @callback onReceiveFail
* @memberof Quiet
* @param {number} total - total number of frames failed across lifetime of receiver
*/
/**
* Callback used by receiver to notify user of errors in creating receiver.
* This is a callback because frequently this will result when the user denies
* permission to use the mic, which happens long after the call to create
* the receiver.
*
* @callback onReceiverCreateFail
* @memberof Quiet
* @param {string} reason - error message related to create fail
*/
/**
* Callback used by receiver to notify user of data received via microphone/line-in.
*
* @callback onReceive
* @memberof Quiet
* @param {ArrayBuffer} payload - chunk of data received
*/
/**
* Create a new receiver with the profile specified by profile (should match profile of transmitter).
* @function receiver
* @memberof Quiet
* @param {string} profile - name of profile to use, must be a key in quiet-profiles.json
* @param {onReceive} onReceive - callback which receiver will call to send user received data
* @param {onReceiverCreateFail} [onCreateFail] - callback to notify user that receiver could not be created
* @param {onReceiveFail} [onReceiveFail] - callback to notify user that receiver received corrupted data
* @example
* receiver("robust", function(payload) { console.log("received chunk of data: " + Quiet.ab2str(payload)); });
*/
function receiver(profile, onReceive, onCreateFail, onReceiveFail) {
var c_profiles = Module.intArrayFromString(profiles);
var c_profile = Module.intArrayFromString(profile);
var opt = Module.ccall('quiet_decoder_profile_str', 'pointer', ['array', 'array'], [c_profiles, c_profile]);
// quiet creates audioCtx when it starts but it does not create an audio input
// getting microphone access requires a permission dialog so only ask for it if we need it
if (gUM === undefined) {
gUM = (navigator.getUserMedia || navigator.webkitGetUserMedia || navigator.mozGetUserMedia);
}
if (gUM === undefined) {
// we couldn't find a suitable getUserMedia, so fail fast
if (onCreateFail !== undefined) {
onCreateFail("getUserMedia undefined (mic not supported by browser)");
}
return;
}
if (audioInput === undefined) {
createAudioInput()
}
// TODO investigate if this still needs to be placed on window.
// seems this was done to keep it from being collected
var scriptProcessor = audioCtx.createScriptProcessor(16384, 2, 1);
receivers.push(scriptProcessor);
// inform quiet about our local sound card's sample rate so that it can resample to its internal sample rate
var decoder = Module.ccall('quiet_decoder_create', 'pointer', ['pointer', 'number'], [opt, audioCtx.sampleRate]);
var samples = Module.ccall('malloc', 'pointer', ['number'], [4 * sampleBufferSize]);
var frame = Module.ccall('malloc', 'pointer', ['number'], [frameBufferSize]);
var readbuf = function() {
while (true) {
var read = Module.ccall('quiet_decoder_recv', 'number', ['pointer', 'pointer', 'number'], [decoder, frame, frameBufferSize]);
if (read === -1) {
break;
}
// convert from emscripten bytes to js string. more pointer arithmetic.
var frameArray = Module.HEAP8.slice(frame, frame + read);
onReceive(frameArray);
}
};
var lastChecksumFailCount = 0;
var consume = function() {
Module.ccall('quiet_decoder_consume', 'number', ['pointer', 'pointer', 'number'], [decoder, samples, sampleBufferSize]);
window.setTimeout(readbuf, 0);
var currentChecksumFailCount = Module.ccall('quiet_decoder_checksum_fails', 'number', ['pointer'], [decoder]);
if ((onReceiveFail !== undefined) && (currentChecksumFailCount > lastChecksumFailCount)) {
window.setTimeout(function() { onReceiveFail(currentChecksumFailCount); }, 0);
}
lastChecksumFailCount = currentChecksumFailCount;
}
scriptProcessor.onaudioprocess = function(e) {
var input = e.inputBuffer.getChannelData(0);
var sample_view = Module.HEAPF32.subarray(samples/4, samples/4 + sampleBufferSize);
sample_view.set(input);
window.setTimeout(consume, 0);
}
// if this is the first receiver object created, wait for our input node to be created
addAudioInputReadyCallback(function() {
audioInput.connect(scriptProcessor);
}, onCreateFail);
// more unused nodes in the graph that some browsers insist on having
var fakeGain = audioCtx.createGain();
fakeGain.value = 0;
scriptProcessor.connect(fakeGain);
fakeGain.connect(audioCtx.destination);
};
/**
* Convert a string to array buffer in UTF8
* @function str2ab
* @memberof Quiet
* @param {string} s - string to be converted
* @returns {ArrayBuffer} buf - converted arraybuffer
*/
function str2ab(s) {
var s_utf8 = unescape(encodeURIComponent(s));
var buf = new ArrayBuffer(s_utf8.length);
var bufView = new Uint8Array(buf);
for (var i = 0; i < s_utf8.length; i++) {
bufView[i] = s_utf8.charCodeAt(i);
}
return buf;
};
/**
* Convert an array buffer in UTF8 to string
* @function ab2str
* @memberof Quiet
* @param {ArrayBuffer} ab - array buffer to be converted
* @returns {string} s - converted string
*/
function ab2str(ab) {
return decodeURIComponent(escape(String.fromCharCode.apply(null, new Uint8Array(ab))));
};
/**
* Merge 2 ArrayBuffers
* This is a convenience function to assist user receiver functions that
* want to aggregate multiple payloads.
* @function mergeab
* @memberof Quiet
* @param {ArrayBuffer} ab1 - beginning ArrayBuffer
* @param {ArrayBuffer} ab2 - ending ArrayBuffer
* @returns {ArrayBuffer} buf - ab1 merged with ab2
*/
function mergeab(ab1, ab2) {
var tmp = new Uint8Array(ab1.byteLength + ab2.byteLength);
tmp.set(new Uint8Array(ab1), 0);
tmp.set(new Uint8Array(ab2), ab1.byteLength);
return tmp.buffer;
};
return {
emscriptenInitialized: onEmscriptenInitialized,
setProfilesPrefix: setProfilesPrefix,
setMemoryInitializerPrefix: setMemoryInitializerPrefix,
setLibfecPrefix: setLibfecPrefix,
addReadyCallback: addReadyCallback,
transmitter: transmitter,
receiver: receiver,
str2ab: str2ab,
ab2str: ab2str,
mergeab: mergeab
};
})();
// extend emscripten Module
var Module = {
onRuntimeInitialized: Quiet.emscriptenInitialized,
memoryInitializerPrefixURL: ""
};
</code></pre>
</article>
</section>
</div>
<nav>
<h2><a href="index.html">Index</a></h2><h3>Namespaces</h3><ul><li><a href="Quiet.html">Quiet</a></li></ul>
</nav>
<br clear="both">
<footer>
Documentation generated by <a href="https://github.com/jsdoc3/jsdoc">JSDoc 3.2.2</a> on Tue Mar 15 2016 00:24:30 GMT-0700 (PDT)
</footer>
<script> prettyPrint(); </script>
<script src="scripts/linenumber.js"> </script>
</body>
</html>