Skip to content

Commit 31e2932

Browse files
committed
Get rid of word source
1 parent 79aa6a6 commit 31e2932

File tree

8 files changed

+97
-90
lines changed

8 files changed

+97
-90
lines changed

server.js

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
1-
import { SourceServer } from "./dist/server/source-server.js";
2-
import { Source } from "./dist/server/source.js";
1+
import { HTTPServer } from "./dist/server/http-server.js";
2+
import { Server } from "./dist/server/server.js";
33
import { generateUniqueId } from "./dist/util/unique-id.js";
44
import fs from "fs";
55
import path from "path";
@@ -75,14 +75,14 @@ async function main() {
7575
const wavData = parseWavFile(WAV_FILE);
7676

7777
// Create and start the Source server
78-
const source = new Source(
78+
const source = new Server(
7979
{
80-
source_id: generateUniqueId("source"),
80+
source_id: generateUniqueId("server"),
8181
name: "SDKSample",
8282
},
8383
logger,
8484
);
85-
const server = new SourceServer(source, PORT, logger);
85+
const server = new HTTPServer(source, PORT, logger);
8686
try {
8787
server.start();
8888
} catch (error) {

src/messages.ts

Lines changed: 8 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -26,7 +26,7 @@ export interface PlayerTimeInfo {
2626
player_transmitted: number;
2727
}
2828

29-
export interface SourceTimeInfo {
29+
export interface ServerTimeInfo {
3030
player_transmitted: number;
3131
source_received: number;
3232
source_transmitted: number;
@@ -37,19 +37,19 @@ export interface PlayerTimeMessage {
3737
payload: PlayerTimeInfo;
3838
}
3939

40-
export interface SourceInfo {
40+
export interface ServerInfo {
4141
source_id: string;
4242
name: string;
4343
}
4444

45-
export interface SourceHelloMessage {
45+
export interface ServerHelloMessage {
4646
type: "source/hello";
47-
payload: SourceInfo;
47+
payload: ServerInfo;
4848
}
4949

50-
export interface SourceTimeMessage {
50+
export interface ServerTimeMessage {
5151
type: "source/time";
52-
payload: SourceTimeInfo;
52+
payload: ServerTimeInfo;
5353
}
5454

5555
export interface SessionStartMessage {
@@ -115,9 +115,9 @@ export type ClientMessages =
115115
export type ServerMessages =
116116
| SessionStartMessage
117117
| SessionEndMessage
118-
| SourceHelloMessage
118+
| ServerHelloMessage
119119
| MetadataUpdateMessage
120-
| SourceTimeMessage;
120+
| ServerTimeMessage;
121121

122122
export enum BinaryMessageType {
123123
PlayAudioChunk = 1,

src/player/player.ts

Lines changed: 19 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,11 @@
11
import {
2-
SourceInfo,
2+
ServerInfo,
33
SessionInfo,
44
ServerMessages,
55
BinaryMessageType,
66
PlayerHelloMessage,
77
Metadata,
8-
SourceTimeInfo,
8+
ServerTimeInfo,
99
PlayerTimeMessage,
1010
} from "../messages.js";
1111
import type { Logger } from "../logging.js";
@@ -14,7 +14,7 @@ import { EventEmitter } from "../util/event-emitter.js";
1414
type Events = {
1515
open: void;
1616
close: { expected: boolean };
17-
"source-update": SourceInfo | null;
17+
"server-update": ServerInfo | null;
1818
"session-update": SessionInfo | null;
1919
"metadata-update": Metadata | null;
2020
};
@@ -28,17 +28,19 @@ export interface PlayerOptions {
2828
// Use standard AudioContext or fallback to webkitAudioContext
2929
const AudioContextClass = window.AudioContext || window.webkitAudioContext;
3030

31+
// Maximum number of samples to keep for time diff calculation
32+
const MAX_TIME_DIFF_SAMPLES = 50;
33+
3134
export class Player extends EventEmitter<Events> {
3235
private options: PlayerOptions;
3336
private logger: Logger = console;
3437
private ws: WebSocket | null = null;
35-
private sourceInfo: SourceInfo | null = null;
38+
private serverInfo: ServerInfo | null = null;
3639
private sessionInfo: SessionInfo | null = null;
3740
private audioContext: AudioContext | null = null;
3841
private metadata: Metadata | null = null;
3942
private serverTimeDiff: number = 0; // Time difference between server and client
4043
private serverTimeDiffSamples: number[] = []; // Store last 50 samples for median
41-
private readonly maxTimeDiffSamples = 50;
4244
private expectClose = true;
4345

4446
constructor(options: PlayerOptions) {
@@ -61,6 +63,7 @@ export class Player extends EventEmitter<Events> {
6163
this.ws.onopen = () => {
6264
this.logger.log("WebSocket connected");
6365
this.audioContext = new AudioContextClass();
66+
this.serverTimeDiffSamples = [];
6467
this.expectClose = false;
6568
this.sendHello();
6669
this.sendPlayerTime();
@@ -139,9 +142,9 @@ export class Player extends EventEmitter<Events> {
139142
this.logger.log("Received text message:", message);
140143
switch (message.type) {
141144
case "source/hello":
142-
this.sourceInfo = message.payload;
143-
this.logger.log("Source connected:", this.sourceInfo);
144-
this.fire("source-update", this.sourceInfo);
145+
this.serverInfo = message.payload;
146+
this.logger.log("Server connected:", this.serverInfo);
147+
this.fire("server-update", this.serverInfo);
145148

146149
break;
147150
case "session/start":
@@ -156,6 +159,7 @@ export class Player extends EventEmitter<Events> {
156159
// Re-instate the audioContext or else the old buffer keeps playing.
157160
this.audioContext!.close();
158161
this.audioContext = new AudioContextClass();
162+
this.serverTimeDiffSamples = [];
159163
// Sync player time with the server.
160164
this.sendPlayerTime();
161165
// Clear session information when session ends.
@@ -171,7 +175,7 @@ export class Player extends EventEmitter<Events> {
171175

172176
case "source/time":
173177
// Pass player_received time to the handler
174-
this.handleSourceTime(message.payload, receivedAt);
178+
this.handleServerTime(message.payload, receivedAt);
175179
break;
176180

177181
default:
@@ -323,7 +327,7 @@ export class Player extends EventEmitter<Events> {
323327
}
324328
}
325329

326-
handleSourceTime(payload: SourceTimeInfo, receivedAt: number) {
330+
handleServerTime(payload: ServerTimeInfo, receivedAt: number) {
327331
const { player_transmitted, source_received, source_transmitted } = payload;
328332

329333
// Calculate the raw offset from this message (in seconds)
@@ -336,8 +340,11 @@ export class Player extends EventEmitter<Events> {
336340

337341
// Store the offset sample
338342
this.serverTimeDiffSamples.push(offset);
339-
if (this.serverTimeDiffSamples.length > this.maxTimeDiffSamples) {
343+
if (this.serverTimeDiffSamples.length > MAX_TIME_DIFF_SAMPLES) {
340344
this.serverTimeDiffSamples.shift();
345+
} else if (this.serverTimeDiffSamples.length < 20) {
346+
// let's kick off another sample
347+
this.sendPlayerTime();
341348
}
342349

343350
// Calculate the median of the samples for a stable offset
@@ -364,7 +371,7 @@ export class Player extends EventEmitter<Events> {
364371
this.expectClose = true;
365372
this.ws.close();
366373
this.ws = null;
367-
this.sourceInfo = null;
374+
this.serverInfo = null;
368375
this.sessionInfo = null;
369376

370377
if (this.audioContext && this.audioContext.state !== "closed") {

src/server/http-server.ts

Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,45 @@
1+
import { WebSocketServer, WebSocket } from "ws";
2+
import type { Logger } from "../logging.js";
3+
import { Server } from "./server.js";
4+
import { ServerClient } from "./server-client.js";
5+
6+
export class HTTPServer {
7+
private websocketServer: WebSocketServer | null = null;
8+
9+
constructor(
10+
private server: Server,
11+
public port: number,
12+
private logger: Logger = console,
13+
) {}
14+
15+
// Start the WebSocket server
16+
start() {
17+
this.websocketServer = new WebSocketServer({ port: this.port });
18+
this.logger.log(`WebSocket server started on port ${this.port}`);
19+
20+
this.websocketServer.on("connection", this.handleConnection.bind(this));
21+
this.websocketServer.on("error", (error) => {
22+
this.logger.error("WebSocket server error:", error);
23+
});
24+
}
25+
26+
handleConnection(ws: WebSocket, request: any) {
27+
const playerClient = new ServerClient(ws, this.logger);
28+
this.server.addClient(playerClient);
29+
}
30+
31+
// Stop the WebSocket server
32+
stop() {
33+
const session = this.server.getSession();
34+
if (session) {
35+
session.end();
36+
}
37+
38+
if (this.websocketServer) {
39+
this.websocketServer.close(() => {
40+
this.logger.log("WebSocket server closed");
41+
});
42+
this.websocketServer = null;
43+
}
44+
}
45+
}

src/server/source-client.ts renamed to src/server/server-client.ts

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -11,13 +11,13 @@ import type { Logger } from "../logging.js";
1111
import { generateUniqueId } from "../util/unique-id.js";
1212
import { EventEmitter } from "../util/event-emitter.js";
1313

14-
interface SourceClientEvents {
14+
interface ServerClientEvents {
1515
close: void;
1616
"player-state": PlayerState | null;
1717
"stream-command": StreamCommandMessage["payload"];
1818
}
1919

20-
export class SourceClient extends EventEmitter<SourceClientEvents> {
20+
export class ServerClient extends EventEmitter<ServerClientEvents> {
2121
public clientId: string;
2222
public playerInfo: PlayerInfo | null = null;
2323
public playerState: PlayerState | null = null;

src/server/source-session.ts renamed to src/server/server-session.ts

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -4,16 +4,16 @@ import {
44
SessionEndMessage,
55
} from "../messages.js";
66
import type { Logger } from "../logging.js";
7-
import { SourceClient } from "./source-client.js";
7+
import { ServerClient } from "./server-client.js";
88

99
const HEADER_SIZE = 13;
1010

11-
export class SourceSession {
11+
export class ServerSession {
1212
sessionActive: Set<string> = new Set();
1313

1414
constructor(
1515
private readonly sessionInfo: SessionInfo,
16-
private readonly clients: Map<string, SourceClient>,
16+
private readonly clients: Map<string, ServerClient>,
1717
private readonly logger: Logger,
1818
private readonly onSessionEnd: () => void,
1919
) {}

src/server/source.ts renamed to src/server/server.ts

Lines changed: 15 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -1,19 +1,19 @@
1-
import { SourceClient } from "./source-client.js";
1+
import { ServerClient } from "./server-client.js";
22
import { generateUniqueId } from "../util/unique-id.js";
3-
import { SourceSession } from "./source-session.js";
3+
import { ServerSession } from "./server-session.js";
44
import type { Logger } from "../logging.js";
5-
import type { SourceInfo, SessionInfo } from "../messages.js";
5+
import type { ServerInfo, SessionInfo } from "../messages.js";
66

7-
export class Source {
8-
private clients: Map<string, SourceClient> = new Map();
9-
private session: SourceSession | null = null;
7+
export class Server {
8+
private clients: Map<string, ServerClient> = new Map();
9+
private session: ServerSession | null = null;
1010

11-
constructor(private sourceInfo: SourceInfo, private logger: Logger) {}
11+
constructor(private serverInfo: ServerInfo, private logger: Logger) {}
1212

13-
addClient(client: SourceClient) {
13+
addClient(client: ServerClient) {
1414
client.send({
1515
type: "source/hello" as const,
16-
payload: this.getSourceInfo(),
16+
payload: this.getServerInfo(),
1717
});
1818
this.clients.set(client.clientId, client);
1919

@@ -37,7 +37,7 @@ export class Source {
3737
}
3838

3939
// Get a copy of the current clients map
40-
getClients(): Map<string, SourceClient> {
40+
getClients(): Map<string, ServerClient> {
4141
return new Map(this.clients);
4242
}
4343

@@ -46,8 +46,8 @@ export class Source {
4646
return this.clients.size;
4747
}
4848

49-
getSourceInfo(): SourceInfo {
50-
return this.sourceInfo;
49+
getServerInfo(): ServerInfo {
50+
return this.serverInfo;
5151
}
5252

5353
// Start an audio session
@@ -56,7 +56,7 @@ export class Source {
5656
sampleRate: number = 44100,
5757
channels: number = 2,
5858
bitDepth: number = 16,
59-
): SourceSession {
59+
): ServerSession {
6060
if (this.session) {
6161
throw new Error("Session already active");
6262
}
@@ -74,7 +74,7 @@ export class Source {
7474
};
7575

7676
// Create new session with current clients
77-
this.session = new SourceSession(
77+
this.session = new ServerSession(
7878
sessionInfo,
7979
this.getClients(),
8080
this.logger,
@@ -89,7 +89,7 @@ export class Source {
8989
}
9090

9191
// Get current session if exists
92-
getSession(): SourceSession | null {
92+
getSession(): ServerSession | null {
9393
return this.session;
9494
}
9595

src/server/source-server.ts

Lines changed: 0 additions & 45 deletions
This file was deleted.

0 commit comments

Comments
 (0)