Skip to content

Commit

Permalink
RTCDataChannel: support Blob
Browse files Browse the repository at this point in the history
Blob is now a thing in NodeJS starting in v16.17.0 and v18.0.0.
  • Loading branch information
peat-psuwit committed Sep 9, 2023
1 parent c065bc0 commit 3967cb3
Showing 1 changed file with 8 additions and 12 deletions.
20 changes: 8 additions & 12 deletions src/webrtc/RTCDataChannel.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { Buffer } from 'buffer';
import { Buffer, Blob as NodeBlob } from 'buffer';
import { setImmediate as resolveImmediate } from 'timers/promises';

import {
Expand Down Expand Up @@ -92,7 +92,7 @@ class NgwRTCDataChannel extends EventTarget implements RTCDataChannel {
}

// MessageEvent is a bit complicated, so I have a helper function.
private _dispatchMessageEvent(data: string | ArrayBufferLike | null) {
private _dispatchMessageEvent(data: string | ArrayBufferLike | NodeBlob | null) {
this.dispatchEvent(new MessageEvent('message', {
data: data,
origin: "null", // Opaque origin
Expand All @@ -103,19 +103,15 @@ class NgwRTCDataChannel extends EventTarget implements RTCDataChannel {
}

private _handleMessageData = async (data: GLib.Bytes | null) => {
if (this._binaryType == 'blob') {
console.warn("We cannot create a blob in NodeJS! Data will be silently dropped.");
return;
}

await resolveImmediate(); // Relief the PC thread.

if (!data) {
return this._dispatchMessageEvent(null);
}

const arrayView = Uint8Array.from(data.getData() || []);
this._dispatchMessageEvent(arrayView.buffer);
const blobOrBuffer = this._binaryType == 'blob' ? new NodeBlob([arrayView]) : arrayView.buffer;
this._dispatchMessageEvent(blobOrBuffer);
}

private _handleMessageString = async (data: string | null) => {
Expand All @@ -136,8 +132,6 @@ class NgwRTCDataChannel extends EventTarget implements RTCDataChannel {
// TS doesn't enforce runtime behavior
switch (value) {
case 'blob':
console.warn("Blob isn't a thing in NodeJS. We will silently drop data if a binary data arrives.");
// Fall-through
case 'arraybuffer':
this._binaryType = value;
break;
Expand Down Expand Up @@ -233,7 +227,7 @@ class NgwRTCDataChannel extends EventTarget implements RTCDataChannel {
}
}

send(data: string | Blob | ArrayBuffer | ArrayBufferView) {
async send(data: string | Blob | NodeBlob | ArrayBuffer | ArrayBufferView) {
this._cacheBufferedAmount();

if (typeof data === 'string') {
Expand All @@ -244,7 +238,9 @@ class NgwRTCDataChannel extends EventTarget implements RTCDataChannel {

let arrayBuffer: ArrayBuffer;

if (ArrayBuffer.isView(data)) {
if (data instanceof NodeBlob) {
arrayBuffer = await data.arrayBuffer();
} else if (ArrayBuffer.isView(data)) {
arrayBuffer = data.buffer;
} else if (data instanceof ArrayBuffer) {
arrayBuffer = data;
Expand Down

0 comments on commit 3967cb3

Please sign in to comment.