Skip to content

Proposal: Allow multiple (and conditional) stream readers per topic #1427

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 5 commits into
base: main
Choose a base branch
from
Open
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
165 changes: 155 additions & 10 deletions examples/demo/demo.ts
Original file line number Diff line number Diff line change
Expand Up @@ -52,6 +52,7 @@ const state = {
bitrateInterval: undefined as any,
e2eeKeyProvider: new ExternalE2EEKeyProvider(),
chatMessages: new Map<string, { text: string; participant?: Participant }>(),
connectionType: 'direct' as 'direct' | 'sandbox',
};
let currentRoom: Room | undefined;

Expand All @@ -69,11 +70,31 @@ if (!storedKey) {
(<HTMLSelectElement>$('crypto-key')).value = storedKey;
}

// Load sandbox ID from localStorage if available
const storedSandboxId = localStorage.getItem('sandboxId') || '';
if (storedSandboxId) {
(<HTMLInputElement>$('sandbox-id')).value = storedSandboxId;
// Default to sandbox connection type if a sandbox ID exists
state.connectionType = 'sandbox';
(<HTMLSelectElement>$('connection-type')).value = 'sandbox';
// Update display of connection sections
document.getElementById('direct-connection')!.style.display = 'none';
document.getElementById('sandbox-connection')!.style.display = 'block';
}

function updateSearchParams(url: string, token: string, key: string) {
const params = new URLSearchParams({ url, token, key });
window.history.replaceState(null, '', `${window.location.pathname}?${params.toString()}`);
}

document.getElementById('connection-type')?.addEventListener('change', (e) => {
state.connectionType = (e.target as HTMLSelectElement).value as 'direct' | 'sandbox';
document.getElementById('direct-connection')!.style.display =
state.connectionType === 'direct' ? 'block' : 'none';
document.getElementById('sandbox-connection')!.style.display =
state.connectionType === 'sandbox' ? 'block' : 'none';
});

// handles actions from the HTML
const appActions = {
sendFile: async () => {
Expand All @@ -86,8 +107,48 @@ const appActions = {
});
},
connectWithFormInput: async () => {
const url = (<HTMLInputElement>$('url')).value;
const token = (<HTMLInputElement>$('token')).value;
let url: string;
let token: string;

if (state.connectionType === 'direct') {
url = (<HTMLInputElement>$('url')).value;
token = (<HTMLInputElement>$('token')).value;
updateSearchParams(url, token, (<HTMLSelectElement>$('crypto-key')).value);
} else {
const sandboxId = (<HTMLInputElement>$('sandbox-id')).value;
// Save sandbox ID to localStorage
localStorage.setItem('sandboxId', sandboxId);

const participantName = (<HTMLInputElement>$('participant-name')).value;
const roomName = (<HTMLInputElement>$('room-name')).value;

try {
const queryParams = new URLSearchParams({
roomName: roomName,
participantName: participantName
});

const response = await fetch(`https://cloud-api.livekit.io/api/sandbox/connection-details?${queryParams.toString()}`, {
method: 'POST',
headers: {
'X-Sandbox-ID': sandboxId
}
});

if (!response.ok) {
throw new Error('Failed to get token from sandbox server');
}

const data = await response.json();
url = data.serverUrl;
token = data.participantToken;
updateSearchParams(url, token, (<HTMLSelectElement>$('crypto-key')).value);
} catch (error) {
appendLog('Failed to get token:', error);
return;
}
}

const simulcast = (<HTMLInputElement>$('simulcast')).checked;
const dynacast = (<HTMLInputElement>$('dynacast')).checked;
const forceTURN = (<HTMLInputElement>$('force-turn')).checked;
Expand All @@ -104,8 +165,6 @@ const appActions = {
backupCodecPolicy = BackupCodecPolicy.SIMULCAST;
}

updateSearchParams(url, token, cryptoKey);

const roomOpts: RoomOptions = {
adaptiveStream,
dynacast,
Expand Down Expand Up @@ -252,7 +311,7 @@ const appActions = {
);
});

room.registerTextStreamHandler('chat', async (reader, participant) => {
room.registerTextStreamHandler('lk.chat', async (reader, participant) => {
const info = reader.info;
if (info.size) {
handleChatMessage(
Expand Down Expand Up @@ -281,7 +340,7 @@ const appActions = {
room.registerByteStreamHandler('files', async (reader, participant) => {
const info = reader.info;

appendLog(`started to receive a file called "${info.name}" from ${participant?.identity}`);
appendLog(`Handler #1: Started receiving a file called "${info.name}" from ${participant?.identity}`);

const progressContainer = document.createElement('div');
progressContainer.style.margin = '10px 0';
Expand All @@ -296,10 +355,8 @@ const appActions = {
progressContainer.appendChild(progressBar);
$('chat-area').after(progressContainer);

appendLog(`Started receiving file "${info.name}" from ${participant?.identity}`);

reader.onProgress = (progress) => {
console.log(`"progress ${progress ? (progress * 100).toFixed(0) : 'undefined'}%`);
console.log(`Handler #1: progress ${progress ? (progress * 100).toFixed(0) : 'undefined'}%`);

if (progress) {
progressBar.value = progress * 100;
Expand All @@ -308,7 +365,7 @@ const appActions = {
};

const result = new Blob(await reader.readAll(), { type: info.mimeType });
appendLog(`Completely received file "${info.name}" from ${participant?.identity}`);
appendLog(`Handler #1: Completely received file "${info.name}" from ${participant?.identity}`);

progressContainer.remove();

Expand Down Expand Up @@ -346,6 +403,94 @@ const appActions = {
}
});

// Add a second handler for the same topic
room.registerByteStreamHandler('files', async (reader, participant) => {
const info = reader.info;

appendLog(`Handler #2: Started receiving a file called "${info.name}" from ${participant?.identity}`);
console.log('Handler #2: File info:', info);

// Create a separate progress indicator for the second handler
const secondProgressContainer = document.createElement('div');
secondProgressContainer.style.margin = '10px 0';
secondProgressContainer.style.backgroundColor = '#f0f8ff'; // Light blue background to distinguish
const secondProgressLabel = document.createElement('div');
secondProgressLabel.innerText = `Handler #2 receiving "${info.name}"...`;
const secondProgressBar = document.createElement('progress');
secondProgressBar.max = 100;
secondProgressBar.value = 0;
secondProgressBar.style.width = '100%';

secondProgressContainer.appendChild(secondProgressLabel);
secondProgressContainer.appendChild(secondProgressBar);
$('chat-area').after(secondProgressContainer);

reader.onProgress = (progress) => {
console.log(`Handler #2: progress ${progress ? (progress * 100).toFixed(0) : 'undefined'}%`);

if (progress) {
secondProgressBar.value = progress * 100;
secondProgressLabel.innerText = `Handler #2: "${info.name}" (${(progress * 100).toFixed(0)}%)`;
}
};

// Read all the data
const fileData = await reader.readAll();
const fileSize = fileData.reduce((total, chunk) => total + chunk.byteLength, 0);

appendLog(`Handler #2: Completely received file "${info.name}" (${fileSize} bytes) from ${participant?.identity}`);
console.log(`Handler #2: File size: ${fileSize} bytes, MIME type: ${info.mimeType}`);

secondProgressContainer.remove();

// Create a Blob from the file data and display it (similar to handler #1)
const result = new Blob(fileData, { type: info.mimeType });

if (info.mimeType.startsWith('image/')) {
// Embed images directly in HTML with a different style for handler #2
const imgContainer = document.createElement('div');
imgContainer.style.margin = '10px 0';
imgContainer.style.padding = '10px';
imgContainer.style.border = '2px dashed #6495ED'; // Add a blue dashed border to distinguish
imgContainer.style.backgroundColor = '#f0f8ff'; // Light blue background

const handlerLabel = document.createElement('div');
handlerLabel.innerText = 'Handler #2 Image:';
handlerLabel.style.fontWeight = 'bold';
handlerLabel.style.marginBottom = '5px';

const img = document.createElement('img');
img.style.maxWidth = '300px';
img.style.maxHeight = '300px';
img.style.border = '1px solid #ddd';
img.src = URL.createObjectURL(result);

const downloadLink = document.createElement('a');
downloadLink.href = img.src;
downloadLink.innerText = `Download ${info.name} (from handler #2)`;
downloadLink.setAttribute('download', info.name);
downloadLink.style.display = 'block';
downloadLink.style.marginTop = '5px';

imgContainer.appendChild(handlerLabel);
imgContainer.appendChild(img);
imgContainer.appendChild(downloadLink);
$('chat-area').after(imgContainer);
} else {
// Non-images get a text download link instead
const downloadLink = document.createElement('a');
downloadLink.href = URL.createObjectURL(result);
downloadLink.innerText = `Download ${info.name} (from handler #2)`;
downloadLink.setAttribute('download', info.name);
downloadLink.style.margin = '10px';
downloadLink.style.padding = '5px';
downloadLink.style.display = 'block';
downloadLink.style.backgroundColor = '#f0f8ff';
downloadLink.style.border = '1px solid #6495ED';
$('chat-area').after(downloadLink);
}
});

try {
// read and set current key from input
const cryptoKey = (<HTMLSelectElement>$('crypto-key')).value;
Expand Down
54 changes: 41 additions & 13 deletions examples/demo/index.html
Original file line number Diff line number Diff line change
Expand Up @@ -17,25 +17,53 @@
<div class="container">
<div class="row">
<div class="col-md-8">
<h2>Livekit Sample App</h2>
<h2>LiveKit Sample App</h2>
<br />
<div id="connect-area">
<div>
<b>LiveKit URL</b>
</div>
<div>
<input type="text" class="form-control" id="url" value="ws://localhost:7880" />
<div class="form-group">
<label for="connection-type"><b>Connection Method</b></label>
<select class="form-control" id="connection-type">
<option value="direct">LiveKit URL + Token</option>
<option value="sandbox">Sandbox Token Server (LiveKit Cloud only)</option>
</select>
</div>
<div>
<b>Token</b>

<!-- Direct connection fields -->
<div id="direct-connection">
<div class="form-group">
<label for="url"><b>LiveKit URL</b></label>
<input type="text" class="form-control" id="url" value="ws://localhost:7880" />
</div>
<div class="form-group">
<label for="token"><b>Token</b></label>
<input type="text" class="form-control" id="token" />
</div>
</div>
<div>
<input type="text" class="form-control" id="token" />

<!-- Sandbox connection fields -->
<div id="sandbox-connection" style="display: none;">
<div>
<a href="https://cloud.livekit.io/projects/p_/sandbox/templates/token-server" target="_blank">
Create Your Sandbox Here
</a>
</div>
<div>
<b>E2EE key</b>
<div class="form-group">
<label for="sandbox-id"><b>Sandbox ID</b></label>
<input type="text" class="form-control" id="sandbox-id" />
</div>
<div class="form-group">
<label for="participant-name"><b>Participant Name</b></label>
<input type="text" class="form-control" id="participant-name" />
</div>
<div class="form-group">
<label for="room-name"><b>Room Name</b></label>
<input type="text" class="form-control" id="room-name" />
</div>
</div>
<div>

<!-- E2EE section - separate from connection details -->
<div class="form-group mt-4">
<label for="crypto-key"><b>E2EE Key</b></label>
<input type="text" class="form-control" id="crypto-key" />
</div>
</div>
Expand Down
5 changes: 0 additions & 5 deletions examples/demo/styles.css
Original file line number Diff line number Diff line change
@@ -1,9 +1,4 @@
#connect-area {
display: grid;
grid-template-columns: 1fr 1fr;
grid-template-rows: min-content min-content;
grid-auto-flow: column;
grid-gap: 10px;
margin-bottom: 15px;
}

Expand Down
Loading
Loading