osc.js
======
osc.js is a library for reading and writing [Open Sound Control](http://opensoundcontrol.org) messages in JavaScript. It works in both Node.js and in a web browser.
osc.js is maintained by [Colin Clark](https://colinclark.org). Please respect his unpaid labour (and that of other open source contributors), be kind, share projects you're working on, and consider contributing your own time to help improve the library. :heart:
Why osc.js?
-----------
There are several other OSC libraries available for JavaScript. However, most depend on Node.js-specific APIs. This means that they can't be run in a browser or on web-only platforms such as Chrome OS. osc.js uses only cross-platform APIs (`TypedArrays` and `DataView`), ensuring that it can run in any modern JavaScript environment.
osc.js is fast, comprehensive, fully spec-compliant, tested, modular, and provides a wide variety of optional transports for sending and receiving OSC data.
What Does it Do?
----------------
osc.js reads and writes OSC-formatted binary data into plain JavaScript objects. It provides adaptors for Node.js Buffer objects as well as standard ArrayBuffers.
The core of osc.js is transport agnostic. You can receive OSC data in whatever manner works best for your application: serial port APIs such as node-serialport or chrome.serial, socket APIs such as Node.js dgram or WebRTC data channels, WebSockets or binary XHR messages should all work. Connect osc.js up to your source of incoming/outgoing data, and you're all set. This approach is consistent with the design of Open Sound Control as a _content format_ that is independent from its means of transport.
In addition to the low-level encoder/decoder functions, osc.js also provides a comprehensive set of transport objects, called Port
s, for use in standard browsers, Chrome Apps, and Node.js applications. These include:
Transport | Supported Platforms |
---|---|
UDP | Node.js, Chrome Apps |
Serial port | Node.js, Chrome Apps |
Web Sockets | Browsers, Node.js, Chrome Apps |
TCP | Node.js |
package.json
configuration file for it:
{
"name": "name
, version
, and [other package.json fields](https://docs.npmjs.com/files/package.json) appropriately for your project.
Then, to install osc.js and all your other project dependencies, run:
npm install
Your dependencies will be located in a directory called node_modules
in your project root.
### Installing osc.js for use in Electron Applications
[Electron](https://github.com/electron/electron) allows developers to create applications using Web technologies and deploy them as native applications on Mac, Windows, and Linux.
Electron, however, ships with its own version of Node.js, which may be different from the version you have installed on your computer. osc.js depends on native Node.js modules such as [node-serialport](https://github.com/EmergingTechnologyAdvisors/node-serialport), which need to be compiled against the Electron version of Node.js in order for them to work correctly.
To install osc.js for Electron applications, there are two options:
1. Follow [the instructions provided by the node-serialport project](https://github.com/EmergingTechnologyAdvisors/node-serialport#electron) and use [electron-rebuild](https://github.com/electron/electron-rebuild) to recompile your dependencies after running npm install
2. Use an .npmrc
file to override npm's default compile target and runtime settings for Electron. Here's an example of an .npmrc
file. Don't forget to make sure that the target
property matches the version of Electron you're using:
```
target=23.1.3
disturl=https://electronjs.org/headers
runtime=electron
build_from_source=true
```
How osc.js Works
----------------
osc.js consists of two distinct layers:
1. The low-level functional API, which provides simple stateless functions for reading and writing OSC packets.
2. The transport layer, which provides a simple EventEmitter-style API for sending and receiving OSC packets using a variety of transports such as UDP and Web Sockets.
Typically, you'll use the Port API for sending and receiving OSC packets over a particular transport, but if you want to write your own transports or want a lower-level interface, you can use the functional API directly.
Port API
--------
### Methods
All osc.Port
objects implement the following supported methods:
Method | Description | Arguments |
---|---|---|
send |
Sends an OSC package (either a message or a bundle) on this Port. |
packet : the OSC message or bundle to send |
osc.Port
s implement the [Event Emitter API](https://nodejs.org/api/events.html). The following events are supported:
Event | Description | Arguments |
---|---|---|
ready |
Fires when a Port is ready to send or receive messages. | _none_ |
message |
Fires whenever an OSC message is received by the Port. |
message : the OSC message received; timeTag : the time tag specified by the sender (may be undefined for non-bundle messages); info an implementation-specific remote information object
|
bundle |
Fires whenever an OSC bundle is received. Subsequent bundle and/or message events will be fired for each sub-packet in the bundle. |
bundle : the OSC bundle received; timeTag : the time tag specified by the sender; info an implementation-specific remote information object
|
osc |
Fires whenever any type of OSC packet is recieved by this Port. |
packet : the OSC message or bundle receivedinfo an implementation-specific remote information object
|
raw |
Fires whenever any data is recieved by this Port. |
data : an Uint8Array containing the raw data receivedinfo an implementation-specific remote information object
|
error |
Fires whenever an error occurs. |
error : the Error object that was raised
|
osc.WebSocketPort
object supports sending and receiving
OSC messages over Web Sockets.
#### Options
Property | Description | Default Value |
---|---|---|
url | The Web Socket URL to connect to (required for clients) | none |
socket | A Web Socket instance to bind to (optional); if supplied, it is your job to configure and open it appropriately | none |
osc-browser.js
package in their code:
```javascript
require("osc/dist/osc-browser");
```
osc.js is not currently tested using WebPack due to limited support resources. Nonetheless, contributions are very much welcomed from the community to help make osc.js more idiomatic when using WebPack or similar technologies, particularly if such changes enable continued support of simpler toolchains (or none) and the use of long-standing browser idioms such as plain old script
tags.
osc.js also does not currently support being loaded as an ES6 module. Contributions for this are also welcome, but any solution should support full compatibility with simpler and long-standing web idioms as above (hint: a new built file will be required that contains suitable ES6 export boilerplate).
### Web Sockets in Node.js
The osc.WebSocketPort
object supports sending and receiving
OSC messages over Web Sockets.
#### Options
Property | Description | Default Value |
---|---|---|
url | The Web Socket URL to connect to (required for clients) | none |
socket | A Web Socket instance to bind to (required for servers, optional for clients); if supplied, it is your job to configure and open it appropriately | none |
osc.UDPPort
object supports the sending and receiving of
OSC messages over Node.js's UDP sockets. It also supports broadcast and multicast UDP.
#### Options
Property | Description | Default Value |
---|---|---|
localPort | The port to listen on | 57121 |
localAddress | The local address to bind to | "127.0.0.1" |
remotePort | The remote port to send messages to (optional) | none |
remoteAddress | The remote address to send messages to (optional) | none |
broadcast | A flag specifying if messages should be sent via UDP broadcast | false |
multicastTTL | The time to live (number of hops) for a multicast connection (optional) | none |
multicastMembership | An array of multicast addresses to join when listening for multicast messages (optional) | none |
socket | A raw dgram.Socket to use instead of osc.js creating one for you; if supplied, it is your job to configure and bind it appropriately | none |
osc.UDPPort
object supports the sending and receiving of
OSC messages over a chrome.sockets.udp
socket. It also supports broadcast and multicast UDP.
#### Options
Property | Description | Default Value |
---|---|---|
localPort | The port to listen on | 57121 |
localAddress | The local address to bind to | "127.0.0.1" |
remotePort | The remote port to send messages to (optional) | none |
remoteAddress | The remote address to send messages to (optional) | none |
broadcast | A flag specifying if messages should be sent via UDP broadcast | false |
multicastTTL | The time to live (number of hops) for a multicast connection (optional) | none |
multicastMembership | An array of multicast addresses to join when listening for multicast messages (optional) | none |
socketId | The id of an existing socket to use instead of osc.js creating one for you; if supplied, it is your job to configure and bind it appropriately | none |
"error"
messages whenever an error occurs,
such as when a malformed message is received. You should always listen for errors and
handle them in an appropriate manner for your application.
```javascript
var port = osc.UDPPort();
port.on("error", function (error) {
console.log("An error occurred: ", error.message);
});
```
The low-level osc.js API, described below, will throw JavaScript Error
objects whenever an error occurs;
they should be caught and handled using
try
/catch
.
```javascript
var msg;
try {
msg = osc.readPacket(rawPacket);
} catch (error) {
console.log("An error occurred: ", error.message);
}
```
The osc.js Low-Level API
------------------------
### OSC Bundle and Message Objects
osc.js represents bundles and messages as (mostly) JSON-compatible objects. Here's how they are structured:
#### Messages
OSC Message objects consist of two properties, `address`, which contains the URL-style address path and `args` which is an array of either raw argument values or type-annotated Argument objects (depending on the value of the metadata
option used when reading the message).
```javascript
{
address: "/an/osc/address",
args: [
{} // Raw or type-annotated OSC arguments
]
}
```
#### Bundles
OSC bundle objects consist of a time tag and an array of `packets`. Packets can be a mix of OSC bundle objects and message objects.
```javascript
{
timeTag: {
// OSC Time Tag object
},
packets: [
{} // Nested OSC bundle and message objects>
]
}
```
#### Argument Objects with Type Metadata
Type-annotated argument objects contain two properties: `type`, which contains the OSC type tag character (e.g. `"i"`, `"f"`, `"t"`, etc.) and the raw `value`.
```javascript
{
type: "f", // OSC type tag string
value: 444.4
}
```
If you are using type-annotated arguments, you should also set the metadata
option to true
when you instantiate your OSCPort
instance (or in the options
argument to osc.writeMessage
if you're using the low-level API).
#### Time Tags
Time tag objects contain two different representations: the raw NTP time and the equivalent (though less precise) native JavaScript timestamp. NTP times consist of a pair of values in an array. The first value represents the number of seconds since January 1, 1900. The second value is a Uint32 value (i.e. between 0 and 4294967296) that represents fractions of a second.
JavaScript timestamps are represented as milliseconds since January 1, 1970, which is the same unit as is returned by calls to `Date.now()`.
```javascript
{
raw: [
3608146800, // seconds since January 1, 1900.
2147483648 // fractions of a second
],
native: Number // Milliseconds since January 1, 1970
}
```
#### Colours
Colours are automatically normalized to CSS 3 rgba values (i.e. the alpha channel is represented as a float from `0.0` to `1.0`).
```javascript
{
r: 255,
g: 255,
b: 255,
a: 1.0
}
```
### Functions
There are two primary functions in osc.js used to read and write OSC data:
Function | Description | Arguments | Return value |
---|---|---|---|
osc.readPacket() |
Decodes binary OSC message into a tree of JavaScript objects containing the messages or bundles that were read. |
data : A Uint8Array containing the raw data of the OSC packet; options : (optional) An options object, described below; offsetState : (optional) an offset state object containing an idx property that specifies the offset index into data ; length the length (in bytes) to read from data
|
An osc.js message or bundle object |
osc.writePacket() |
Writes an OSC message or bundle object to a binary array. |
packet : An osc.js message or bundle object;options : (optional) An options object, described below |
A Uint8Array |
options
object that can be used to customize its behaviour. These options are also supported by all osc.Port
objects, and can be included as a parameter in the options
arguments passed to any Port
constructor. The supported fields in an options object are:
* metadata
: specifies if the OSC type metadata should be included. By default, type metadata isn't included when reading packets, and is inferred automatically when writing packets. If you need greater precision in regards to the arguments in an OSC message, set the metadata
argument to true. Defaults to false
.
* unpackSingleArgs
: specifies if osc.js should automatically unpack single-argument messages so that their args
property isn't wrapped in an array. Defaults to true
.
Mapping OSC to JS
------------------
Here are a few examples showing how OSC packets are mapped to plain JavaScript objects by osc.js.
Message | Objects | ||||
---|---|---|---|---|---|
"/carrier/freq" ",f" 440.4 |
|
||||
"/float/andArray" ",f[ff]" 440.4 42 47 |
|
||||
"/aTimeTag" ",t" 3608146800 2147483648 |
| ||||
"/blob" ",b" 0x63 0x61 0x74 0x21 |
|
Environment | Tested OS | Version |
---|---|---|
Chrome | Mac OS X, Windows | Stable channel |
Firefox | Mac OS X, Windows | Stable channel |
Safari | Mac OS X | Latest |
Edge | Windows | Latest |
Node.js | Mac OS X, Windows | LTS |
Electron | Mac OS X, Windows | Latest |
grunt jshint
.
Currently, the project is maintained by one person; sometimes it will take a bit of time to respond, review, and merge contributions. Help with bug triage, code reviews, testing, and examples is also welcome.
## How to Build and Test Your Contributions
osc.js depends on npm, Grunt, and Testem. Make sure you have these installed, and then run the following commands to fetch all necessary dependencies:
npm install
To lint and generate builds from new source code:
grunt
Running the unit tests:
1. To run the fully automated tests, run "npm test"
2. To run the electron tests, run "npm run electron-test"
Contributors
------------
* @colinbdclark wrote osc.js.
* @jacoscaz and @xseignard fixed bugs.
* @drart made and helped test some examples.
* @egasimus added support for 64-bit integers.
* @heisters contributed fixes for broadcast and multicast UDP on Node.js and improved time tag support.
* @tambien fixed error handling bugs in the transports layer.
* @janslow added support for passing remote information to all Port data events.