├── .gitignore ├── .travis.yml ├── .zuul.yml ├── AUTHORS ├── LICENSE ├── README.md ├── docs.json ├── examples └── file-transfer.js ├── index.js ├── package.json └── test ├── all.js ├── closed-channel.js ├── helpers └── init-channels.js ├── scuttlebutt-sync.js ├── simple-read.js ├── simple-rw.js ├── simple-write.js ├── stream-end.js └── tester-write.js /.gitignore: -------------------------------------------------------------------------------- 1 | .DS_Store 2 | node_modules 3 | npm-debug.log 4 | .travis 5 | -------------------------------------------------------------------------------- /.travis.yml: -------------------------------------------------------------------------------- 1 | sudo: false 2 | services: 3 | - xvfb 4 | language: node_js 5 | node_js: 6 | - 0.10 7 | 8 | env: 9 | matrix: 10 | - BROWSER=chrome BVER=stable 11 | - BROWSER=chrome BVER=beta 12 | - BROWSER=chrome BVER=unstable 13 | - BROWSER=firefox BVER=stable 14 | - BROWSER=firefox BVER=beta 15 | - BROWSER=firefox BVER=unstable 16 | 17 | matrix: 18 | fast_finish: true 19 | 20 | allow_failures: 21 | - env: BROWSER=chrome BVER=unstable 22 | - env: BROWSER=firefox BVER=unstable 23 | 24 | before_script: 25 | - ./node_modules/travis-multirunner/setup.sh 26 | 27 | after_failure: 28 | - for file in *.log; do echo $file; echo "======================"; cat $file; done || true 29 | 30 | notifications: 31 | email: 32 | - nathan+rtcio@coviu.com -------------------------------------------------------------------------------- /.zuul.yml: -------------------------------------------------------------------------------- 1 | ui: tape 2 | browsers: 3 | - name: firefox 4 | version: 30..latest 5 | 6 | - name: chrome 7 | version: [35,36,beta] 8 | -------------------------------------------------------------------------------- /AUTHORS: -------------------------------------------------------------------------------- 1 | Damon Oehlman (https://github.com/DamonOehlman) 2 | Silvia Pfeiffer (https://github.com/silviapfeiffer) 3 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | 2 | Apache License 3 | Version 2.0, January 2004 4 | http://www.apache.org/licenses/ 5 | 6 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 7 | 8 | 1. Definitions. 9 | 10 | "License" shall mean the terms and conditions for use, reproduction, 11 | and distribution as defined by Sections 1 through 9 of this document. 12 | 13 | "Licensor" shall mean the copyright owner or entity authorized by 14 | the copyright owner that is granting the License. 15 | 16 | "Legal Entity" shall mean the union of the acting entity and all 17 | other entities that control, are controlled by, or are under common 18 | control with that entity. For the purposes of this definition, 19 | "control" means (i) the power, direct or indirect, to cause the 20 | direction or management of such entity, whether by contract or 21 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 22 | outstanding shares, or (iii) beneficial ownership of such entity. 23 | 24 | "You" (or "Your") shall mean an individual or Legal Entity 25 | exercising permissions granted by this License. 26 | 27 | "Source" form shall mean the preferred form for making modifications, 28 | including but not limited to software source code, documentation 29 | source, and configuration files. 30 | 31 | "Object" form shall mean any form resulting from mechanical 32 | transformation or translation of a Source form, including but 33 | not limited to compiled object code, generated documentation, 34 | and conversions to other media types. 35 | 36 | "Work" shall mean the work of authorship, whether in Source or 37 | Object form, made available under the License, as indicated by a 38 | copyright notice that is included in or attached to the work 39 | (an example is provided in the Appendix below). 40 | 41 | "Derivative Works" shall mean any work, whether in Source or Object 42 | form, that is based on (or derived from) the Work and for which the 43 | editorial revisions, annotations, elaborations, or other modifications 44 | represent, as a whole, an original work of authorship. For the purposes 45 | of this License, Derivative Works shall not include works that remain 46 | separable from, or merely link (or bind by name) to the interfaces of, 47 | the Work and Derivative Works thereof. 48 | 49 | "Contribution" shall mean any work of authorship, including 50 | the original version of the Work and any modifications or additions 51 | to that Work or Derivative Works thereof, that is intentionally 52 | submitted to Licensor for inclusion in the Work by the copyright owner 53 | or by an individual or Legal Entity authorized to submit on behalf of 54 | the copyright owner. For the purposes of this definition, "submitted" 55 | means any form of electronic, verbal, or written communication sent 56 | to the Licensor or its representatives, including but not limited to 57 | communication on electronic mailing lists, source code control systems, 58 | and issue tracking systems that are managed by, or on behalf of, the 59 | Licensor for the purpose of discussing and improving the Work, but 60 | excluding communication that is conspicuously marked or otherwise 61 | designated in writing by the copyright owner as "Not a Contribution." 62 | 63 | "Contributor" shall mean Licensor and any individual or Legal Entity 64 | on behalf of whom a Contribution has been received by Licensor and 65 | subsequently incorporated within the Work. 66 | 67 | 2. Grant of Copyright License. Subject to the terms and conditions of 68 | this License, each Contributor hereby grants to You a perpetual, 69 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 70 | copyright license to reproduce, prepare Derivative Works of, 71 | publicly display, publicly perform, sublicense, and distribute the 72 | Work and such Derivative Works in Source or Object form. 73 | 74 | 3. Grant of Patent License. Subject to the terms and conditions of 75 | this License, each Contributor hereby grants to You a perpetual, 76 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 77 | (except as stated in this section) patent license to make, have made, 78 | use, offer to sell, sell, import, and otherwise transfer the Work, 79 | where such license applies only to those patent claims licensable 80 | by such Contributor that are necessarily infringed by their 81 | Contribution(s) alone or by combination of their Contribution(s) 82 | with the Work to which such Contribution(s) was submitted. If You 83 | institute patent litigation against any entity (including a 84 | cross-claim or counterclaim in a lawsuit) alleging that the Work 85 | or a Contribution incorporated within the Work constitutes direct 86 | or contributory patent infringement, then any patent licenses 87 | granted to You under this License for that Work shall terminate 88 | as of the date such litigation is filed. 89 | 90 | 4. Redistribution. You may reproduce and distribute copies of the 91 | Work or Derivative Works thereof in any medium, with or without 92 | modifications, and in Source or Object form, provided that You 93 | meet the following conditions: 94 | 95 | (a) You must give any other recipients of the Work or 96 | Derivative Works a copy of this License; and 97 | 98 | (b) You must cause any modified files to carry prominent notices 99 | stating that You changed the files; and 100 | 101 | (c) You must retain, in the Source form of any Derivative Works 102 | that You distribute, all copyright, patent, trademark, and 103 | attribution notices from the Source form of the Work, 104 | excluding those notices that do not pertain to any part of 105 | the Derivative Works; and 106 | 107 | (d) If the Work includes a "NOTICE" text file as part of its 108 | distribution, then any Derivative Works that You distribute must 109 | include a readable copy of the attribution notices contained 110 | within such NOTICE file, excluding those notices that do not 111 | pertain to any part of the Derivative Works, in at least one 112 | of the following places: within a NOTICE text file distributed 113 | as part of the Derivative Works; within the Source form or 114 | documentation, if provided along with the Derivative Works; or, 115 | within a display generated by the Derivative Works, if and 116 | wherever such third-party notices normally appear. The contents 117 | of the NOTICE file are for informational purposes only and 118 | do not modify the License. You may add Your own attribution 119 | notices within Derivative Works that You distribute, alongside 120 | or as an addendum to the NOTICE text from the Work, provided 121 | that such additional attribution notices cannot be construed 122 | as modifying the License. 123 | 124 | You may add Your own copyright statement to Your modifications and 125 | may provide additional or different license terms and conditions 126 | for use, reproduction, or distribution of Your modifications, or 127 | for any such Derivative Works as a whole, provided Your use, 128 | reproduction, and distribution of the Work otherwise complies with 129 | the conditions stated in this License. 130 | 131 | 5. Submission of Contributions. Unless You explicitly state otherwise, 132 | any Contribution intentionally submitted for inclusion in the Work 133 | by You to the Licensor shall be under the terms and conditions of 134 | this License, without any additional terms or conditions. 135 | Notwithstanding the above, nothing herein shall supersede or modify 136 | the terms of any separate license agreement you may have executed 137 | with Licensor regarding such Contributions. 138 | 139 | 6. Trademarks. This License does not grant permission to use the trade 140 | names, trademarks, service marks, or product names of the Licensor, 141 | except as required for reasonable and customary use in describing the 142 | origin of the Work and reproducing the content of the NOTICE file. 143 | 144 | 7. Disclaimer of Warranty. Unless required by applicable law or 145 | agreed to in writing, Licensor provides the Work (and each 146 | Contributor provides its Contributions) on an "AS IS" BASIS, 147 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 148 | implied, including, without limitation, any warranties or conditions 149 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 150 | PARTICULAR PURPOSE. You are solely responsible for determining the 151 | appropriateness of using or redistributing the Work and assume any 152 | risks associated with Your exercise of permissions under this License. 153 | 154 | 8. Limitation of Liability. In no event and under no legal theory, 155 | whether in tort (including negligence), contract, or otherwise, 156 | unless required by applicable law (such as deliberate and grossly 157 | negligent acts) or agreed to in writing, shall any Contributor be 158 | liable to You for damages, including any direct, indirect, special, 159 | incidental, or consequential damages of any character arising as a 160 | result of this License or out of the use or inability to use the 161 | Work (including but not limited to damages for loss of goodwill, 162 | work stoppage, computer failure or malfunction, or any and all 163 | other commercial damages or losses), even if such Contributor 164 | has been advised of the possibility of such damages. 165 | 166 | 9. Accepting Warranty or Additional Liability. While redistributing 167 | the Work or Derivative Works thereof, You may choose to offer, 168 | and charge a fee for, acceptance of support, warranty, indemnity, 169 | or other liability obligations and/or rights consistent with this 170 | License. However, in accepting such obligations, You may act only 171 | on Your own behalf and on Your sole responsibility, not on behalf 172 | of any other Contributor, and only if You agree to indemnify, 173 | defend, and hold each Contributor harmless for any liability 174 | incurred by, or claims asserted against, such Contributor by reason 175 | of your accepting any such warranty or additional liability. 176 | 177 | END OF TERMS AND CONDITIONS 178 | 179 | APPENDIX: How to apply the Apache License to your work. 180 | 181 | To apply the Apache License to your work, attach the following 182 | boilerplate notice, with the fields enclosed by brackets "[]" 183 | replaced with your own identifying information. (Don't include 184 | the brackets!) The text should be enclosed in the appropriate 185 | comment syntax for the file format. We also recommend that a 186 | file or class name and description of purpose be included on the 187 | same "printed page" as the copyright notice for easier 188 | identification within third-party archives. 189 | 190 | Copyright 2013 National ICT Australia Limited (NICTA) 191 | 192 | Licensed under the Apache License, Version 2.0 (the "License"); 193 | you may not use this file except in compliance with the License. 194 | You may obtain a copy of the License at 195 | 196 | http://www.apache.org/licenses/LICENSE-2.0 197 | 198 | Unless required by applicable law or agreed to in writing, software 199 | distributed under the License is distributed on an "AS IS" BASIS, 200 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 201 | See the License for the specific language governing permissions and 202 | limitations under the License. -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # rtc-dcstream 2 | 3 | Node streams2 interface for working with WebRTC data channels. This stream 4 | implementation will cater for current data size limits in the WebRTC 5 | data channels. 6 | 7 | 8 | [![NPM](https://nodei.co/npm/rtc-dcstream.png)](https://nodei.co/npm/rtc-dcstream/) 9 | 10 | [![unstable](https://img.shields.io/badge/stability-unstable-yellowgreen.svg)](https://github.com/dominictarr/stability#unstable) [![Build Status](https://img.shields.io/travis/rtc-io/rtc-dcstream.svg?branch=master)](https://travis-ci.org/rtc-io/rtc-dcstream) [![bitHound Score](https://www.bithound.io/github/rtc-io/rtc-dcstream/badges/score.svg)](https://www.bithound.io/github/rtc-io/rtc-dcstream) 11 | 12 | ## Example Usage 13 | 14 | The example below shows how to use the `rtc-dcstream` module to stream data 15 | via a datachannel to *n* remote participants. In this case we are using 16 | the W3C FileReader API and streaming dropped data files over the data 17 | channel: 18 | 19 | ```js 20 | var crel = require('crel'); 21 | var dropkick = require('dropkick'); 22 | var quickconnect = require('rtc-quickconnect'); 23 | var fileReader = require('filestream/read'); 24 | var fileReceiver = require('filestream/write'); 25 | var multiplex = require('multiplex'); 26 | var createDataStream = require('rtc-dcstream'); 27 | var channels = []; 28 | var peers = []; 29 | var inbound = {}; 30 | 31 | function prepStream(dc, id) { 32 | var plex = multiplex(); 33 | 34 | plex.pipe(createDataStream(dc)).pipe(multiplex(function(stream, type) { 35 | stream.pipe(fileReceiver(function(file) { 36 | document.body.appendChild(crel('img', { src: URL.createObjectURL(file) })); 37 | }, { type: type })); 38 | })); 39 | 40 | return plex; 41 | } 42 | 43 | quickconnect('http://rtc.io/switchboard', { room: 'filetx-test' }) 44 | .createDataChannel('files') 45 | .on('channel:opened:files', function(id, dc) { 46 | peers.push(id); 47 | channels.push(prepStream(dc, id)); 48 | }) 49 | .on('peer:leave', function(id) { 50 | var peerIdx = peers.indexOf(id); 51 | if (peerIdx >= 0) { 52 | peers.splice(peerIdx, 1); 53 | channels.splice(peerIdx, 1); 54 | } 55 | }) 56 | 57 | dropkick(document.body).on('file', function(file) { 58 | channels.forEach(function(plex) { 59 | fileReader(file).pipe(plex.createStream(file.type)); 60 | }); 61 | }); 62 | 63 | // give the document some size so we can drag and drop stuff 64 | document.body.style.width = '100vw'; 65 | document.body.style.height = '100vw'; 66 | 67 | ``` 68 | 69 | ## Alternative Implementations 70 | 71 | In addition to this module, the following are other modules that wrap 72 | WebRTC data channel communication via a node streaming interface: 73 | 74 | - [rtc-data-stream](https://github.com/kumavis/rtc-data-stream) 75 | 76 | ## Reference 77 | 78 | To be completed. 79 | 80 | ## License(s) 81 | 82 | ### Apache 2.0 83 | 84 | Copyright 2015 National ICT Australia Limited (NICTA) 85 | 86 | Licensed under the Apache License, Version 2.0 (the "License"); 87 | you may not use this file except in compliance with the License. 88 | You may obtain a copy of the License at 89 | 90 | http://www.apache.org/licenses/LICENSE-2.0 91 | 92 | Unless required by applicable law or agreed to in writing, software 93 | distributed under the License is distributed on an "AS IS" BASIS, 94 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 95 | See the License for the specific language governing permissions and 96 | limitations under the License. 97 | -------------------------------------------------------------------------------- /docs.json: -------------------------------------------------------------------------------- 1 | { 2 | "license": { 3 | "holder": "National ICT Australia Limited (NICTA)" 4 | } 5 | } 6 | -------------------------------------------------------------------------------- /examples/file-transfer.js: -------------------------------------------------------------------------------- 1 | var crel = require('crel'); 2 | var dropkick = require('dropkick'); 3 | var quickconnect = require('rtc-quickconnect'); 4 | var fileReader = require('filestream/read'); 5 | var fileReceiver = require('filestream/write'); 6 | var multiplex = require('multiplex'); 7 | var createDataStream = require('..'); 8 | var channels = []; 9 | var peers = []; 10 | var inbound = {}; 11 | 12 | function prepStream(dc, id) { 13 | var plex = multiplex(); 14 | 15 | plex.pipe(createDataStream(dc)).pipe(multiplex(function(stream, type) { 16 | stream.pipe(fileReceiver(function(file) { 17 | document.body.appendChild(crel('img', { src: URL.createObjectURL(file) })); 18 | }, { type: type })); 19 | })); 20 | 21 | return plex; 22 | } 23 | 24 | quickconnect('http://rtc.io/switchboard', { room: 'filetx-test' }) 25 | .createDataChannel('files') 26 | .on('channel:opened:files', function(id, dc) { 27 | peers.push(id); 28 | channels.push(prepStream(dc, id)); 29 | }) 30 | .on('peer:leave', function(id) { 31 | var peerIdx = peers.indexOf(id); 32 | if (peerIdx >= 0) { 33 | peers.splice(peerIdx, 1); 34 | channels.splice(peerIdx, 1); 35 | } 36 | }) 37 | 38 | dropkick(document.body).on('file', function(file) { 39 | channels.forEach(function(plex) { 40 | fileReader(file).pipe(plex.createStream(file.type)); 41 | }); 42 | }); 43 | 44 | // give the document some size so we can drag and drop stuff 45 | document.body.style.width = '100vw'; 46 | document.body.style.height = '100vw'; 47 | -------------------------------------------------------------------------------- /index.js: -------------------------------------------------------------------------------- 1 | /* jshint node: true */ 2 | 'use strict'; 3 | 4 | var debug = require('cog/logger')('rtc-dcstream'); 5 | var stream = require('stream'); 6 | var toBuffer = require('typedarray-to-buffer'); 7 | var util = require('util'); 8 | var closingStates = ['closing', 'closed']; 9 | var ENDOFSTREAM = '::endofstream'; 10 | var MAX_CHUNK_SIZE = 1024 * 64; 11 | 12 | /** 13 | # rtc-dcstream 14 | 15 | Node streams2 interface for working with WebRTC data channels. This stream 16 | implementation will cater for current data size limits in the WebRTC 17 | data channels. 18 | 19 | ## Example Usage 20 | 21 | The example below shows how to use the `rtc-dcstream` module to stream data 22 | via a datachannel to *n* remote participants. In this case we are using 23 | the W3C FileReader API and streaming dropped data files over the data 24 | channel: 25 | 26 | <<< examples/file-transfer.js 27 | 28 | ## Alternative Implementations 29 | 30 | In addition to this module, the following are other modules that wrap 31 | WebRTC data channel communication via a node streaming interface: 32 | 33 | - [rtc-data-stream](https://github.com/kumavis/rtc-data-stream) 34 | 35 | ## Reference 36 | 37 | To be completed. 38 | 39 | **/ 40 | 41 | function RTCChannelStream(channel) { 42 | if (! (this instanceof RTCChannelStream)) { 43 | return new RTCChannelStream(channel); 44 | } 45 | 46 | // super 47 | stream.Duplex.call(this, { 48 | decodeStrings: false, 49 | objectMode: true 50 | }); 51 | 52 | // create the internal read and write queues 53 | this._rq = []; 54 | this._wq = []; 55 | 56 | this._bytesWritten = 0; 57 | 58 | // initialise the closed state 59 | this._closed = channel.readyState === 'closed'; 60 | 61 | // save a reference to the channel 62 | this.channel = channel; 63 | 64 | // set the channel binaryType to arraybuffer 65 | channel.binaryType = 'arraybuffer'; 66 | 67 | // initialise the message handlers 68 | this._handlers = { 69 | message: this._handleMessage.bind(this), 70 | close: this._handleClose.bind(this), 71 | open: this._handleOpen.bind(this) 72 | }; 73 | 74 | // attach channel listeners 75 | if (typeof channel.addEventListener == 'function') { 76 | channel.addEventListener('message', this._handlers.message); 77 | channel.addEventListener('close', this._handlers.close); 78 | channel.addEventListener('open', this._handlers.open); 79 | } else { 80 | channel.onmessage = this._handlers.message; 81 | channel.onclose = this._handlers.close; 82 | channel.onopen = this._handlers.open; 83 | } 84 | 85 | // Check if the channel is already open, and if it is, fire the open handler 86 | if (channel.readyState === 'open') { 87 | this._handlers.open(); 88 | } 89 | 90 | // send an ENDOFSTREAM marker on finish 91 | this.once('finish', this._dcsend.bind(this, ENDOFSTREAM)); 92 | } 93 | 94 | module.exports = RTCChannelStream; 95 | util.inherits(RTCChannelStream, stream.Duplex); 96 | 97 | var prot = RTCChannelStream.prototype; 98 | 99 | prot._checkClear = function() { 100 | var peer = this; 101 | var bufferedAmount = this.channel.bufferedAmount; 102 | var bytesWritten = this._bytesWritten; 103 | 104 | if (bufferedAmount === 0) { 105 | clearInterval(this._clearTimer); 106 | this._clearTimer = undefined; 107 | this._handleOpen(); 108 | } 109 | // Detect any errors with the data channel whereby it just 110 | // stops writing and the buffer never clears 111 | else if (!this._bufferWriteTimer) { 112 | this._bufferWriteTimer = setTimeout(function() { 113 | // Check if our buffer is empty now 114 | var currentBuffer = peer.channel.bufferedAmount; 115 | if (currentBuffer === 0) return peer._checkClear(); 116 | 117 | // Raise an exception 118 | var err = new Error('Buffer write timer failed. State at start: [Buffered] ' + bufferedAmount + ', [Written] ' + bytesWritten + '. State now: [Buffered] ' + peer.channel.bufferedAmount + ', [Written] ' + peer._bytesWritten); 119 | err.name = 'BufferWriteError'; 120 | peer.emit('error', err); 121 | }, 10000); 122 | } 123 | }; 124 | 125 | prot._ensureClearCheck = function() { 126 | if (this._clearTimer) return; 127 | this._clearTimer = setInterval(this._checkClear.bind(this), 100); 128 | }; 129 | 130 | prot._debindChannel = function() { 131 | var channel = this.channel; 132 | 133 | // remove the message listener 134 | if (typeof channel.removeEventListener == 'function') { 135 | channel.removeEventListener('message', this._handlers.message); 136 | channel.removeEventListener('close', this._handlers.close); 137 | channel.removeEventListener('open', this._handlers.message); 138 | } else { 139 | channel.onmessage = null; 140 | channel.onclose = null; 141 | channel.onopen = null; 142 | } 143 | }; 144 | 145 | prot._isChannelClosed = function() { 146 | return (! this.channel) || closingStates.indexOf(this.channel.readyState) >= 0; 147 | }; 148 | 149 | prot._read = function(n) { 150 | var ready = true; 151 | var next; 152 | 153 | // if we have no data queued, then wait until we have been told we 154 | // do as _read will not be called again until we have pushed something 155 | if (this._rq.length === 0) { 156 | return this.once('readable', this._read.bind(this, n)); 157 | } 158 | 159 | // TODO: honour the request for a particular number of bytes 160 | // this.push(evt.data); 161 | while (ready && this._rq.length > 0) { 162 | // get the next chunk 163 | next = this._rq.shift(); 164 | 165 | // if the next chunk is an array buffer, convert to a node buffer 166 | if (next instanceof ArrayBuffer) { 167 | this.push(toBuffer(new Uint8Array(next))); 168 | } 169 | else { 170 | this.push(next); 171 | } 172 | } 173 | 174 | return ready; 175 | }; 176 | 177 | prot._write = function(chunk, encoding, callback) { 178 | var closed = this._isChannelClosed(); 179 | 180 | // if closed then abort 181 | if (closed) { 182 | return false; 183 | } 184 | 185 | // process in chunks of an appropriate size for the data channel 186 | var length = chunk.length || chunk.byteLength || chunk.size; 187 | var numChunks = Math.ceil(length / MAX_CHUNK_SIZE); 188 | var _returned = false; 189 | // debug('_write ' + length + ' in ' + numChunks + ' chunks'); 190 | 191 | function progressiveCallback(e) { 192 | if (_returned || !e) return; 193 | // Capture errors for writes that are split into multiple chunks and 194 | // return to the root callback 195 | _returned = true; 196 | return callback(e); 197 | } 198 | 199 | var result; 200 | // To prevent overwhelming the data channel with a large write 201 | // we ensure that writes are only for chunks within the MAX_CHUNK_SIZE 202 | // If not, we split it up further into smaller chunks 203 | for (var i = 0; i < numChunks; i++) { 204 | var offset = i * MAX_CHUNK_SIZE; 205 | var until = offset + MAX_CHUNK_SIZE; 206 | var currentChunk = (numChunks === 1 ? chunk : chunk.slice(offset, until)); 207 | var ccLength = currentChunk.length || currentChunk.byteLength || currentChunk.size; 208 | 209 | // Only callback after the entire attempted chunk is written 210 | var currentCallback = (i + 1 === numChunks) ? callback : progressiveCallback; 211 | // if we are connecting, then wait 212 | if (this._wq.length || this.channel.readyState === 'connecting') { 213 | result = this._wq.push([ currentChunk, encoding, currentCallback ]); 214 | } 215 | // if the channel is buffering, let's give it a rest 216 | else if (this.channel.bufferedAmount > 0) { 217 | debug('data channel buffering ' + this.channel.bufferedAmount + ', backing off'); 218 | this._ensureClearCheck(); 219 | result = this._wq.push([ currentChunk, encoding, currentCallback ]); 220 | } else { 221 | result = this._dcsend(currentChunk, encoding, currentCallback); 222 | } 223 | } 224 | return result; 225 | }; 226 | 227 | /** 228 | ### `_dcsend(chunk, encoding, callback)` 229 | 230 | The internal function that is responsible for sending the data over the 231 | underlying datachannel. 232 | 233 | **/ 234 | prot._dcsend = function(chunk, encoding, callback) { 235 | this._clearBufferWriteTimer(); 236 | // ensure we have a callback to use if not supplied 237 | callback = callback || function() {}; 238 | 239 | // if the channel is closed, then return false 240 | if (this._closed || this.channel.readyState !== 'open') { 241 | return false; 242 | } 243 | 244 | var size = chunk.length || chunk.byteLength || chunk.size || 0; 245 | 246 | try { 247 | this.channel.send(chunk); 248 | } 249 | catch (e) { 250 | // handle closed streams where we didn't get the memo 251 | if (e.name == 'NetworkError') { 252 | return this._handleClose(); 253 | } 254 | return callback(e); 255 | } 256 | 257 | this._bytesWritten += size; 258 | return callback(); 259 | }; 260 | 261 | /* event handlers */ 262 | 263 | prot._handleClose = function(evt) { 264 | // flag the channel as closed 265 | this._closed = true; 266 | 267 | // emit the close and end events 268 | this.emit('close'); 269 | this.emit('end'); 270 | 271 | return false; 272 | }; 273 | 274 | prot._handleMessage = function(evt) { 275 | /* jshint validthis: true */ 276 | var data = evt && evt.data; 277 | 278 | // if we have an end of stream marker, end 279 | if (typeof data == 'string' && data === ENDOFSTREAM) { 280 | // remove the channel event bindings 281 | this._debindChannel(); 282 | 283 | // emit the end 284 | return this.emit('end'); 285 | } 286 | 287 | this._rq.push(data); 288 | this.emit('readable'); 289 | }; 290 | 291 | prot._clearBufferWriteTimer = function() { 292 | if (!this._bufferWriteTimer) return; 293 | clearTimeout(this._bufferWriteTimer); 294 | this._bufferWriteTimer = undefined; 295 | } 296 | 297 | prot._handleOpen = function(evt) { 298 | var peer = this; 299 | var queue = this._wq; 300 | 301 | // If the buffer write timer was active, we can now clear it 302 | this._clearBufferWriteTimer(); 303 | 304 | function sendNext() { 305 | // Check if the channel is closed in which case, cancel the attempt to send 306 | if (peer._isChannelClosed()) { 307 | debug('Channel has closed, queued writes are being discarded'); 308 | queue = []; 309 | return; 310 | } 311 | 312 | // Check that we are ready to send, if not, restart the timer 313 | if (peer.channel.readyState !== 'open' || peer.channel.bufferedAmount > 0) { 314 | debug('Not yet ready to resume sending queued write, backing off'); 315 | return peer._ensureClearCheck(); 316 | } 317 | 318 | var args = queue.shift(); 319 | var callback; 320 | 321 | // if we have no args, then abort 322 | if (! args) { 323 | return queue.length ? sendNext() : null; 324 | } 325 | 326 | // save the callback 327 | callback = args[2]; 328 | 329 | // replace with a new callback 330 | args[2] = function() { 331 | 332 | // Queue up the next clearing of the queue 333 | setTimeout(sendNext, 0); 334 | 335 | // trigger the callback 336 | if (typeof callback == 'function') { 337 | callback(); 338 | } 339 | }; 340 | 341 | peer._dcsend.apply(peer, args); 342 | } 343 | 344 | // send the queued messages 345 | debug('channel open, sending queued ' + queue.length + ' messages'); 346 | sendNext(); 347 | }; 348 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "rtc-dcstream", 3 | "version": "2.3.0", 4 | "description": "Streams interface for the WebRTC data channel", 5 | "main": "index.js", 6 | "stability": "unstable", 7 | "scripts": { 8 | "test": "browserify test/all.js | broth start | tap-spec", 9 | "gendocs": "gendocs > README.md" 10 | }, 11 | "repository": { 12 | "type": "git", 13 | "url": "https://github.com/rtc-io/rtc-dcstream.git" 14 | }, 15 | "keywords": [ 16 | "webrtc", 17 | "rtc.io", 18 | "datachannel", 19 | "stream" 20 | ], 21 | "author": "Damon Oehlman ", 22 | "license": "Apache-2.0", 23 | "bugs": { 24 | "url": "https://github.com/rtc-io/rtc-dcstream/issues" 25 | }, 26 | "homepage": "https://github.com/rtc-io/rtc-dcstream", 27 | "devDependencies": { 28 | "broth": "^2.0.0", 29 | "browserify": "^9.0.3", 30 | "crel": "^2.1.6", 31 | "dropkick": "~0.1", 32 | "filestream": "^3.0.2", 33 | "mime-component": "0.0.1", 34 | "multiplex": "^4.0.1", 35 | "peerpair": "^1.0.0", 36 | "rtc-quickconnect": "^4.0.0", 37 | "scuttlebutt": "^5", 38 | "stream-spec": "~0.3", 39 | "stream-tester": "0.0.5", 40 | "tap-spec": "^3.0.0", 41 | "tape": "^3.0.3", 42 | "through": "^2", 43 | "travis-multirunner": "^4.3.1" 44 | }, 45 | "dependencies": { 46 | "cog": "^1.0.0", 47 | "typedarray-to-buffer": "^3.0.0" 48 | }, 49 | "testling": { 50 | "files": "test/all.js" 51 | } 52 | } 53 | -------------------------------------------------------------------------------- /test/all.js: -------------------------------------------------------------------------------- 1 | require('./simple-read'); 2 | require('./simple-write'); 3 | require('./simple-rw'); 4 | require('./scuttlebutt-sync'); 5 | require('./stream-end'); 6 | require('./tester-write'); 7 | require('./closed-channel'); 8 | -------------------------------------------------------------------------------- /test/closed-channel.js: -------------------------------------------------------------------------------- 1 | var Model = require('scuttlebutt/model'); 2 | var Duplex = require('stream').Duplex; 3 | var initChannels = require('./helpers/init-channels'); 4 | var test = require('tape'); 5 | var channelstream = require('..'); 6 | var dcs; 7 | var streams; 8 | var models = []; 9 | 10 | test('initialize channels', function(t) { 11 | t.plan(2); 12 | initChannels(function(err, channels) { 13 | t.ifError(err); 14 | dcs = channels; 15 | t.equal(dcs.length, 2); 16 | }); 17 | }); 18 | 19 | test('create streams', function(t) { 20 | t.plan(2); 21 | 22 | // create the streams 23 | streams = dcs.map(channelstream); 24 | 25 | // check we have valid streams 26 | t.ok(streams[0] instanceof Duplex, 'stream:0 valid'); 27 | t.ok(streams[1] instanceof Duplex, 'stream:1 valid'); 28 | }); 29 | 30 | test('write a buffer from 0 -> 1', function(t) { 31 | function handleData(buffer) { 32 | streams[1].removeListener('data', handleData); 33 | t.equal(buffer.toString(), 'hello', 'matched expected'); 34 | } 35 | 36 | 37 | t.plan(1); 38 | streams[1].on('data', handleData); 39 | streams[0].write(new Buffer('hello')); 40 | }); 41 | 42 | test('close the underlying data channel and attempt to write', function(t) { 43 | t.plan(2); 44 | 45 | dcs[0].close(); 46 | streams[1].once('end', t.pass.bind(t, 'stream ended')); 47 | t.doesNotThrow(function() { 48 | streams[0].write(new Buffer('hello')); 49 | }); 50 | }); 51 | -------------------------------------------------------------------------------- /test/helpers/init-channels.js: -------------------------------------------------------------------------------- 1 | var peerpair = require('peerpair'); 2 | 3 | module.exports = function(callback) { 4 | var peers = peerpair(); 5 | return peers.createChannelsAndConnect(['dc:test'], callback); 6 | }; -------------------------------------------------------------------------------- /test/scuttlebutt-sync.js: -------------------------------------------------------------------------------- 1 | var Model = require('scuttlebutt/model'); 2 | var Duplex = require('stream').Duplex; 3 | var initChannels = require('./helpers/init-channels'); 4 | var test = require('tape'); 5 | var channelstream = require('..'); 6 | var dcs; 7 | var streams; 8 | var models = []; 9 | 10 | test('initialize channels', function(t) { 11 | t.plan(2); 12 | initChannels(function(err, channels) { 13 | t.ifError(err); 14 | dcs = channels; 15 | t.equal(dcs.length, 2); 16 | }); 17 | }); 18 | 19 | test('create streams', function(t) { 20 | t.plan(2); 21 | 22 | // create the streams 23 | streams = dcs.map(channelstream); 24 | 25 | // check we have valid streams 26 | t.ok(streams[0] instanceof Duplex, 'stream:0 valid'); 27 | t.ok(streams[1] instanceof Duplex, 'stream:1 valid'); 28 | }); 29 | 30 | test('create model:0', function(t) { 31 | t.plan(1); 32 | 33 | models[0] = new Model(); 34 | streams[0].pipe(models[0].createStream()).pipe(streams[0]); 35 | t.ok(models[0] instanceof Model); 36 | }); 37 | 38 | test('create model:1', function(t) { 39 | t.plan(1); 40 | 41 | models[1] = new Model(); 42 | streams[1].pipe(models[1].createStream()).pipe(streams[1]); 43 | t.ok(models[1] instanceof Model); 44 | }); 45 | 46 | test('update model:0, observe model:1 change', function(t) { 47 | t.plan(2); 48 | 49 | models[1].on('update', function() { 50 | t.equal(models[1].get('name'), 'Bob', 'model 1 has synced (name == Bob)'); 51 | }); 52 | 53 | t.equal(models[1].get('name'), undefined, 'model 1 has no name'); 54 | models[0].set('name', 'Bob'); 55 | }); -------------------------------------------------------------------------------- /test/simple-read.js: -------------------------------------------------------------------------------- 1 | var initChannels = require('./helpers/init-channels'); 2 | var test = require('tape'); 3 | var Duplex = require('stream').Duplex; 4 | var through = require('through'); 5 | var channelstream = require('..'); 6 | var dcs; 7 | var stream; 8 | 9 | test('initialize channels', function(t) { 10 | t.plan(2); 11 | initChannels(function(err, channels) { 12 | t.ifError(err); 13 | dcs = channels; 14 | t.equal(dcs.length, 2); 15 | }); 16 | }); 17 | 18 | test('create a data stream on dc:1', function(t) { 19 | t.plan(1); 20 | stream = channelstream(dcs[1]); 21 | t.ok(stream instanceof Duplex, 'created stream object'); 22 | }); 23 | 24 | test('can read (non flowing mode)', function(t) { 25 | t.plan(1); 26 | 27 | function readData() { 28 | var data = stream.read(); 29 | 30 | if (data) { 31 | stream.removeListener('readable', readData); 32 | t.equal(data.toString(), 'hello1'); 33 | } 34 | } 35 | 36 | stream.on('readable', readData); 37 | dcs[0].send('hello1'); 38 | }); 39 | 40 | test('can read from the stream', function(t) { 41 | t.plan(1); 42 | 43 | stream.once('data', function handleData(buffer) { 44 | t.equal(buffer.toString(), 'hello2'); 45 | }); 46 | 47 | dcs[0].send('hello2'); 48 | }); 49 | 50 | test('can read through', function(t) { 51 | t.plan(1); 52 | 53 | stream.pipe(through()).once('data', function(buffer) { 54 | t.equal(buffer.toString(), 'hello3'); 55 | }); 56 | 57 | dcs[0].send('hello3'); 58 | }); 59 | 60 | test('can read binary data', function(t) { 61 | t.plan(4); 62 | 63 | stream.once('data', function handleData(buffer) { 64 | // validate that the buffer is a buffer instance 65 | t.ok(Buffer.isBuffer(buffer), 'got a Buffer instance'); 66 | t.equal(buffer.length, 2, 'buffer is expected length') 67 | t.equal(buffer[0], 0xFF); 68 | t.equal(buffer[1], 0xAA); 69 | }); 70 | 71 | dcs[0].send(new Uint8Array([0xFF, 0xAA])); 72 | }); -------------------------------------------------------------------------------- /test/simple-rw.js: -------------------------------------------------------------------------------- 1 | var initChannels = require('./helpers/init-channels'); 2 | var test = require('tape'); 3 | var Duplex = require('stream').Duplex; 4 | var through = require('through'); 5 | var channelstream = require('..'); 6 | var dcs; 7 | var streams; 8 | 9 | test('initialize channels', function(t) { 10 | t.plan(2); 11 | initChannels(function(err, channels) { 12 | t.ifError(err); 13 | dcs = channels; 14 | t.equal(dcs.length, 2); 15 | }); 16 | }); 17 | 18 | test('create a data stream on dc:0', function(t) { 19 | t.plan(2); 20 | 21 | // create the streams 22 | streams = dcs.map(channelstream); 23 | 24 | // check we have valid streams 25 | t.ok(streams[0] instanceof Duplex, 'stream:0 valid'); 26 | t.ok(streams[1] instanceof Duplex, 'stream:1 valid'); 27 | }); 28 | 29 | test('can write to stream:0 and read through stream:1', function(t) { 30 | t.plan(1); 31 | 32 | streams[1].once('data', function(buffer) { 33 | t.equal(buffer.toString(), 'helo', 'stream:1 received helo'); 34 | }); 35 | 36 | streams[0].write('helo'); 37 | }); 38 | 39 | test('can write to stream:1 and read through stream:0', function(t) { 40 | t.plan(1); 41 | 42 | streams[0].once('data', function(buffer) { 43 | t.equal(buffer.toString(), 'ehlo', 'stream:0 received ehlo'); 44 | }); 45 | 46 | streams[1].write('ehlo'); 47 | }); 48 | 49 | test('can write buffer to stream:1 and read through stream:0', function(t) { 50 | t.plan(4); 51 | 52 | streams[0].once('data', function(buffer) { 53 | t.ok(Buffer.isBuffer(buffer), 'got a Buffer instance'); 54 | t.equal(buffer.length, 2, 'got 2 length buffer'); 55 | t.equal(buffer[0], 0xFF); 56 | t.equal(buffer[1], 0xAA); 57 | }); 58 | 59 | streams[1].write(new Buffer([0xFF, 0xAA])); 60 | }); -------------------------------------------------------------------------------- /test/simple-write.js: -------------------------------------------------------------------------------- 1 | var initChannels = require('./helpers/init-channels'); 2 | var test = require('tape'); 3 | var Duplex = require('stream').Duplex; 4 | var through = require('through'); 5 | var channelstream = require('..'); 6 | var dcs; 7 | var stream; 8 | 9 | test('initialize channels', function(t) { 10 | t.plan(2); 11 | initChannels(function(err, channels) { 12 | t.ifError(err); 13 | dcs = channels; 14 | t.equal(dcs.length, 2); 15 | }); 16 | }); 17 | 18 | test('set the data channels to arraybuffer binary mode', function(t) { 19 | t.plan(2); 20 | dcs[0].binaryType = 'arraybuffer'; 21 | dcs[1].binaryType = 'arraybuffer'; 22 | 23 | t.equal(dcs[0].binaryType, 'arraybuffer'); 24 | t.equal(dcs[1].binaryType, 'arraybuffer'); 25 | }); 26 | 27 | test('create a data stream on dc:0', function(t) { 28 | t.plan(1); 29 | stream = channelstream(dcs[0]); 30 | t.ok(stream instanceof Duplex, 'created stream object'); 31 | }); 32 | 33 | test('can write a string to the stream', function(t) { 34 | t.plan(2); 35 | 36 | function handleMessage(evt) { 37 | t.ok(evt && evt.data); 38 | t.equal(evt.data, 'hello', 'got expected message'); 39 | dcs[1].removeEventListener('message', handleMessage); 40 | } 41 | 42 | dcs[1].addEventListener('message', handleMessage); 43 | stream.write('hello'); 44 | }); 45 | 46 | test('can write a buffer to the stream', function(t) { 47 | var chunk = new Buffer([0xFF, 0xAA]); 48 | 49 | t.plan(4); 50 | 51 | function handleMessage(evt) { 52 | var view; 53 | 54 | t.ok(evt && evt.data, 'got data'); 55 | t.ok(evt.data instanceof ArrayBuffer, 'got an array buffer of data'); 56 | view = new Uint8Array(evt.data); 57 | 58 | t.equal(view[0], 0xFF); 59 | t.equal(view[1], 0xAA); 60 | 61 | dcs[1].removeEventListener('message', handleMessage); 62 | } 63 | 64 | dcs[1].addEventListener('message', handleMessage); 65 | // console.log('writing new chunk, is buffer = ', chunk instanceof Buffer); 66 | stream.write(chunk); 67 | }); -------------------------------------------------------------------------------- /test/stream-end.js: -------------------------------------------------------------------------------- 1 | var Model = require('scuttlebutt/model'); 2 | var Duplex = require('stream').Duplex; 3 | var initChannels = require('./helpers/init-channels'); 4 | var test = require('tape'); 5 | var channelstream = require('..'); 6 | var dcs; 7 | var streams; 8 | var models = []; 9 | 10 | test('initialize channels', function(t) { 11 | t.plan(2); 12 | initChannels(function(err, channels) { 13 | t.ifError(err); 14 | dcs = channels; 15 | t.equal(dcs.length, 2); 16 | }); 17 | }); 18 | 19 | test('create streams', function(t) { 20 | t.plan(2); 21 | 22 | // create the streams 23 | streams = dcs.map(channelstream); 24 | 25 | // check we have valid streams 26 | t.ok(streams[0] instanceof Duplex, 'stream:0 valid'); 27 | t.ok(streams[1] instanceof Duplex, 'stream:1 valid'); 28 | }); 29 | 30 | test('streams transmit end events across the wire', function(t) { 31 | t.plan(2); 32 | 33 | streams[0].pipe(streams[1]); 34 | streams[1].once('data', function(buffer) { 35 | t.equal(buffer.toString(), 'hello'); 36 | }); 37 | 38 | streams[1].once('end', t.pass.bind(t, 'stream ended')); 39 | streams[0].end('hello'); 40 | }); -------------------------------------------------------------------------------- /test/tester-write.js: -------------------------------------------------------------------------------- 1 | var initChannels = require('./helpers/init-channels'); 2 | var test = require('tape'); 3 | var Duplex = require('stream').Duplex; 4 | var tester = require('stream-tester'); 5 | var channelstream = require('..'); 6 | var dcs; 7 | var stream; 8 | var LIPSUM = 'Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry\'s standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.' 9 | 10 | test('initialize channels', function(t) { 11 | t.plan(2); 12 | initChannels(function(err, channels) { 13 | t.ifError(err); 14 | dcs = channels; 15 | t.equal(dcs.length, 2); 16 | }); 17 | }); 18 | 19 | test('set binary type of dc:1 to arraybuffer', function(t) { 20 | t.plan(1); 21 | dcs[1].binaryType = 'arraybuffer'; 22 | t.equal(dcs[1].binaryType, 'arraybuffer'); 23 | }); 24 | 25 | test('create a data stream on dc:0', function(t) { 26 | t.plan(1); 27 | stream = channelstream(dcs[0]); 28 | t.ok(stream instanceof Duplex, 'created stream object'); 29 | }); 30 | 31 | test('push through 5000 text updates', function(t) { 32 | var max = 5000; 33 | var progressInterval = max / 10; 34 | var received = 0; 35 | var parts = []; 36 | 37 | function checkParts() { 38 | var match = true; 39 | for (var ii = parts.length; match && ii--; ) { 40 | match = parts[ii] === LIPSUM; 41 | if (! match) { 42 | console.log(parts[ii], ii); 43 | } 44 | } 45 | 46 | t.ok(match, 'all strings matched expected output'); 47 | } 48 | 49 | function handleMessage(evt) { 50 | parts[received++] = evt.data; 51 | if (received >= max) { 52 | t.pass('received ' + max + ' messages'); 53 | 54 | // check the messages match 55 | checkParts(); 56 | dcs[1].removeEventListener('message', handleMessage); 57 | dcs[1].removeEventListener('close', handleClose); 58 | } 59 | 60 | if (received % progressInterval === 0) { 61 | t.pass('received ' + received + ' messages'); 62 | } 63 | } 64 | 65 | function handleClose(evt) { 66 | t.fail('broke the datachannel - it closed'); 67 | } 68 | 69 | t.plan(12); 70 | dcs[1].addEventListener('message', handleMessage); 71 | dcs[1].addEventListener('close', handleClose); 72 | 73 | tester.createRandomStream(function() { 74 | return LIPSUM; 75 | }, max).pipe(stream); 76 | }); 77 | 78 | test('create a new stream on dc:0', function(t) { 79 | t.plan(1); 80 | stream = channelstream(dcs[0]); 81 | t.ok(stream instanceof Duplex, 'created stream object'); 82 | }); 83 | 84 | test('push through 5000 buffer updates', function(t) { 85 | var max = 5000; 86 | var progressInterval = max / 10; 87 | var received = 0; 88 | var parts = []; 89 | 90 | function checkParts() { 91 | var match = true; 92 | var view; 93 | var ii; 94 | 95 | for (ii = parts.length; match && ii--; ) { 96 | try { 97 | view = new Uint8Array(parts[ii]); 98 | match = view[0] === 0xFF && view[1] === 0xAA; 99 | if (! match) { 100 | console.log('failed at part: ' + ii, view); 101 | } 102 | } 103 | catch (e) { 104 | console.error('Could not create Uint8Array from data', e); 105 | match = false; 106 | } 107 | } 108 | 109 | t.ok(match, 'all buffers matched expected'); 110 | } 111 | 112 | function handleMessage(evt) { 113 | // ignore ::endofstream markers from the text stream tests 114 | if (evt.data === '::endofstream') { 115 | return; 116 | } 117 | 118 | parts[received++] = evt.data; 119 | if (received >= max) { 120 | t.pass('received ' + max + ' messages'); 121 | 122 | // check the messages match 123 | checkParts(); 124 | dcs[1].removeEventListener('message', handleMessage); 125 | dcs[1].removeEventListener('close', handleClose); 126 | } 127 | 128 | if (received % progressInterval === 0) { 129 | t.pass('received ' + received + ' messages'); 130 | } 131 | } 132 | 133 | function handleClose(evt) { 134 | t.fail('broke the datachannel - it closed'); 135 | } 136 | 137 | t.plan(12); 138 | dcs[1].addEventListener('message', handleMessage); 139 | dcs[1].addEventListener('close', handleClose); 140 | 141 | tester.createRandomStream(function() { 142 | return new Buffer([0xFF, 0xAA]); 143 | }, max).pipe(stream); 144 | }); 145 | --------------------------------------------------------------------------------