Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ The library provides a comprehensive set of Java classes that map to the WebRTC
- **[WHIP and WHEP](https://jrtc.dev/guide/client-api#whip-and-whep)** - Publish to and play from streaming servers
- **[Peer connections](https://jrtc.dev/guide/networking/peer-connection-config)** - The full native API, modeled on the W3C JavaScript API
- **[Data channels](https://jrtc.dev/guide/data/data-channels)** - Reliable or unreliable peer-to-peer messaging
- **[File transfer](https://jrtc.dev/guide/data/file-transfer)** - Send files over a data channel with progress, a checksum confirmed by the receiver and resume after a reconnect
- **[Statistics](https://jrtc.dev/guide/monitoring/rtc-stats)** - Detailed metrics on connection quality

**Audio and video**
Expand Down
1 change: 1 addition & 0 deletions docs/.vitepress/sidebar.ts
Original file line number Diff line number Diff line change
Expand Up @@ -54,6 +54,7 @@ function sidebarGuide(): DefaultTheme.SidebarItem[] {
collapsed: false,
items: [
{ text: 'Data Channels', link: '/data/data-channels' },
{ text: 'File Transfer', link: '/data/file-transfer' },
],
},
{
Expand Down
2 changes: 2 additions & 0 deletions docs/guide/client-api.md
Original file line number Diff line number Diff line change
Expand Up @@ -759,6 +759,8 @@ DataChannel positions = peer.createChannel("positions", ChannelOptions.builder()

`negotiatedId(int)` creates a channel both peers set up themselves with the same id, without announcing it; such a channel never shows up in `onChannel`. The [Data Channels](/guide/data/data-channels) guide explains the options in detail.

A completed `send` future means the data was handed to the transport, not that the remote application processed it. To send files, use `FileTransfers` from `dev.onvoid.webrtc.client.transfer`, which adds the receiver's own confirmations, a SHA-256 checksum, progress, cancelling and resume. See the [File Transfer](/guide/data/file-transfer) guide.

## WHIP and WHEP

Media servers and streaming services take streams with the WebRTC HTTP Ingestion Protocol ([WHIP](https://www.rfc-editor.org/rfc/rfc9725)) and hand them out with its egress counterpart, WHEP. Both exchange one offer and one answer over HTTP. `Whip` publishes tracks, and `Whep` receives a stream:
Expand Down
66 changes: 66 additions & 0 deletions docs/guide/data/file-transfer.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,66 @@
# File Transfer

`dev.onvoid.webrtc.client.transfer` sends files over a [client API](/guide/client-api) data channel. It adds what a plain `send()` doesn't give you: chunking with bounded memory, progress, cancelling, a confirmation from the receiver with a SHA-256 checksum, and resuming after a reconnect.

```java
FileTransfers files = FileTransfers.over(peer.createChannel("files"));

OutgoingTransfer upload = files.send(Paths.get("report.pdf"));
upload.onProgress(p -> System.out.printf("%.0f%%%n", 100 * p.fraction()));
upload.whenDone().thenRun(() -> System.out.println("The receiver has it"));

// On the other side:
peer.onChannel(channel -> {
if (channel.label().equals("files")) {
FileTransfers.over(channel).onOffer(offer ->
offer.accept(downloads.resolve(offer.safeFileName())));
}
});
```

`FileTransfers` takes over the channel: nothing else may be sent on it. Files go one at a time in each direction, in the order they were sent, and both peers may send at the same time. Each side reads and writes its files and runs its handlers on a thread of its own, not on the peer's event thread. Those handlers must not block.

## Confirmation, not just handing data to the transport

The future that `DataChannel.send()` returns completes once the data has been handed to the transport. It tells you nothing about the receiver. The transfer protocol has its own confirmations:

- The receiver acknowledges the bytes it wrote to its file, a quarter of its window at a time. Progress on both sides counts confirmed bytes.
- The sender never has more than the receiver's window unconfirmed (`TransferOptions.builder().window(bytes)`, 4 MiB by default). A slow disk therefore slows the sender down instead of filling memory. Keep the window below the receiver's `channelReceiveLimit`.
- `whenDone()` completes only once the receiver has checked the SHA-256 of the whole file against the sender's and moved the file into place.

## Offers

An offer's `name()` and `size()` come from the remote peer. Don't turn the name into a path as it is, because it may contain `../` or path separators. `safeFileName()` gives you a single file name that stays in the directory you resolve it against. `reject(reason)` makes the sender's transfer fail with that reason, and the sender's next file follows. If an offer arrives before any handler is registered, it waits for the first handler.

The data goes to `partialFile()` next to the target, and that file replaces the target only after the checksum matched. If more data arrives than the offer announced, or more than the window allows, or the data is out of order, the receiver treats it as a protocol error: the transfer fails and the channel closes.

## Cancelling and failures

`cancel()` works on either side. It tells the remote peer, and the receiver deletes its partial file. The other side fails with a `TransferCancelledException`. Every other failure is a `TransferException`, for example a rejected offer, a checksum mismatch, a read or write error, or a protocol error.

## Resuming after a reconnect

When the channel closes, or `close()` is called, unfinished transfers fail with an exception whose `isResumable()` is true. The receiver keeps its partial file. Over a new channel, for example of a new peer after the connection has been set up again, the sender resumes the transfer:

```java
OutgoingTransfer resumed = newFiles.resume(interrupted);
```

The offer keeps its id. If the receiver accepts it with the same target, the transfer continues from the end of the partial file, and the checksum still covers the whole file. With `TransferOptions.builder().resumable(false)`, the receiver deletes partial files on every failure and always starts over. An application that won't resume a transfer deletes `partialFile()` itself.

## Wire format

Each frame is one binary message, big-endian, and starts with its type and the 16-byte transfer id:

| Frame | Type | Fields after the id |
|--------|------|-----------------------------------------|
| OFFER | 1 | version (u8, 1), size (u64), name (text) |
| ACCEPT | 2 | offset (u64), window (u32) |
| REJECT | 3 | reason (text) |
| DATA | 4 | offset (u64), payload |
| ACK | 5 | offset (u64) |
| END | 6 | SHA-256 (32 bytes) |
| DONE | 7 | |
| CANCEL | 8 | failed (u8), reason (text) |

A text is a u16 length followed by at most 1024 bytes of UTF-8.
16 changes: 16 additions & 0 deletions docs/guide/examples.md
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,22 @@ This example is the shortest way to see a complete call working, and a starting
mvn exec:java -D"exec.mainClass=dev.onvoid.webrtc.examples.ClientApiExample" -D"exec.args=10"
```

## File Transfer

The [`FileTransferExample`](https://github.com/devopvoid/webrtc-java/blob/master/webrtc-examples/src/main/java/dev/onvoid/webrtc/examples/FileTransferExample.java) connects two peers in one process with the [Client API](/guide/client-api), and sends a file from one to the other with [File Transfer](/guide/data/file-transfer). It needs no audio or video hardware and no server.

**Key features demonstrated:**
- Running `FileTransfers` over a data channel on both sides
- Accepting an offer under a safe file name, in a directory of the application's choice
- Following the progress the receiver confirms
- Waiting until the receiver checked the SHA-256 of the file and moved it into place

Pass a file to send, or a size in MiB for a file of random data, 20 by default:

```bash
mvn exec:java -D"exec.mainClass=dev.onvoid.webrtc.examples.FileTransferExample" -D"exec.args=50"
```

## PeerConnection

The [`PeerConnectionExample`](https://github.com/devopvoid/webrtc-java/blob/master/webrtc-examples/src/main/java/dev/onvoid/webrtc/examples/PeerConnectionExample.java) sends the camera and the microphone from one peer to another in the same process, with the [Client API](/guide/client-api), and logs the video frames and audio that arrive.
Expand Down
1 change: 1 addition & 0 deletions docs/guide/index.md
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@ This section provides detailed guides for various features of the webrtc-java li
## Data Communication

- [Data Channels](/guide/data/data-channels) - Sending and receiving arbitrary data between peers
- [File Transfer](/guide/data/file-transfer) - Sending files with progress, confirmation, checksum and resume

## Networking and ICE

Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,125 @@
/*
* Copyright 2026 Alex Andres
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

package dev.onvoid.webrtc.examples;

import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Arrays;
import java.util.Random;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.TimeUnit;

import dev.onvoid.webrtc.client.AudioMode;
import dev.onvoid.webrtc.client.Peer;
import dev.onvoid.webrtc.client.PeerOptions;
import dev.onvoid.webrtc.client.Signaling;
import dev.onvoid.webrtc.client.SignalingPair;
import dev.onvoid.webrtc.client.WebRtc;
import dev.onvoid.webrtc.client.transfer.FileTransfers;
import dev.onvoid.webrtc.client.transfer.IncomingTransfer;
import dev.onvoid.webrtc.client.transfer.OutgoingTransfer;

/**
* Example of file transfer over a data channel ({@code dev.onvoid.webrtc.client.transfer}): two
* peers in one process, one sends a file, the other saves it.
* <p>
* This example shows how to:
* <ul>
* <li>Run {@link FileTransfers} over a data channel on both sides</li>
* <li>Accept an offer under a safe file name in a directory of the application's choice</li>
* <li>Follow the progress the receiver confirms</li>
* <li>Wait until the receiver checked the SHA-256 of the file and moved it into place</li>
* </ul>
* <p>
* Pass a file to send, or a size in MiB for a file of random data, 20 by default:
* <pre>
* mvn exec:java -D"exec.mainClass=dev.onvoid.webrtc.examples.FileTransferExample" -D"exec.args=50"
* </pre>
*
* @author Alex Andres
*/
public class FileTransferExample {

public static void main(String[] args) throws Exception {
Path downloads = Files.createTempDirectory("webrtc-downloads");
Path source = source(args.length > 0 ? args[0] : "20");

try (WebRtc rtc = WebRtc.builder().audio(AudioMode.HEADLESS).build()) {
// Both peers in one process. A real application signals through its own server.
SignalingPair link = Signaling.loopback();
Peer sender = rtc.createPeer(PeerOptions.builder()
.name("sender")
.signaling(link.first())
.build());
Peer receiver = rtc.createPeer(PeerOptions.builder()
.name("receiver")
.signaling(link.second())
.polite(true)
.build());

CompletableFuture<IncomingTransfer> incoming = new CompletableFuture<>();

receiver.onChannel(channel -> {
if (!channel.label().equals("files")) {
return;
}

FileTransfers.over(channel).onOffer(offer -> {
// The name comes from the remote peer: never use it as a path as it is.
System.out.printf("Receiver is offered %s, %d bytes%n", offer.safeFileName(), offer.size());
incoming.complete(offer.accept(downloads.resolve(offer.safeFileName())));
});
});

FileTransfers files = FileTransfers.over(sender.createChannel("files"));
OutgoingTransfer upload = files.send(source);

upload.onProgress(progress -> System.out.printf("Receiver confirmed %.0f%% (%d of %d bytes)%n",
100 * progress.fraction(), progress.bytes(), progress.size()));

// The main thread may wait; a handler must not.
upload.whenDone().get(60, TimeUnit.SECONDS);

IncomingTransfer received = incoming.get(5, TimeUnit.SECONDS);
received.whenDone().get(5, TimeUnit.SECONDS);

boolean same = Arrays.equals(Files.readAllBytes(source), Files.readAllBytes(received.file()));

System.out.println("Receiver saved " + received.file() + (same ? ", identical to " : ", differing from ")
+ source);
}
}

/**
* @return the file named, or a new file of random data of that many MiB.
*/
private static Path source(String argument) throws Exception {
Path file = Paths.get(argument);

if (Files.isRegularFile(file)) {
return file;
}

byte[] data = new byte[Integer.parseInt(argument) * 1024 * 1024];
new Random().nextBytes(data);

Path random = Files.createTempFile("webrtc-upload", ".bin");
random.toFile().deleteOnExit();
return Files.write(random, data);
}
}
Loading
Loading