Skip to content
Merged
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
51 changes: 51 additions & 0 deletions src/modules/StreamingClient.ts
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,8 @@ import {
} from '../lib/ClientMetrics';

const SUCCESS_METRIC_POLLING_TIMEOUT_MS = 15000; // After this time we will stop polling for the first frame and consider the session a failure.
const STATS_COLLECTION_INTERVAL_MS = 5000;

export class StreamingClient {
private publicEventEmitter: PublicEventEmitter;
private internalEventEmitter: InternalEventEmitter;
Expand All @@ -44,6 +46,7 @@ export class StreamingClient {
private successMetricFired = false;
private showPeerConnectionStatsReport: boolean = false;
private peerConnectionStatsReportOutputFormat: 'console' | 'json' = 'console';
private statsCollectionInterval: ReturnType<typeof setInterval> | null = null;

constructor(
sessionId: string,
Expand Down Expand Up @@ -116,6 +119,47 @@ export class StreamingClient {
});
}

private startStatsCollection() {
if (this.statsCollectionInterval) {
return;
}

// Send stats every STATS_COLLECTION_INTERVAL_MS seconds
this.statsCollectionInterval = setInterval(async () => {
if (
!this.peerConnection ||
!this.dataChannel ||
this.dataChannel.readyState !== 'open'
) {
return;
}

try {
const stats = await this.peerConnection.getStats();
this.sendClientSideMetrics(stats);
} catch (error) {
console.error('Failed to collect and send stats:', error);
}
}, STATS_COLLECTION_INTERVAL_MS);
}

private sendClientSideMetrics(stats: RTCStatsReport) {
stats.forEach((report: RTCStats) => {
// Process inbound-rtp stats for both video and audio
if (report.type === 'inbound-rtp') {
const metrics = {
message_type: 'remote_rtp_stats',
data: report,
};

// Send the metrics via data channel
if (this.dataChannel && this.dataChannel.readyState === 'open') {
this.dataChannel.send(JSON.stringify(metrics));
}
}
});
}

private startSuccessMetricPolling() {
if (this.successMetricPoller || this.successMetricFired) {
return;
Expand Down Expand Up @@ -418,6 +462,8 @@ export class StreamingClient {
this.peerConnection?.iceConnectionState === 'completed'
) {
this.publicEventEmitter.emit(AnamEvent.CONNECTION_ESTABLISHED);
// Start collecting stats every 5 seconds
this.startStatsCollection();
}
}

Expand Down Expand Up @@ -610,6 +656,11 @@ export class StreamingClient {
}
}
}
// stop stats collection
if (this.statsCollectionInterval) {
clearInterval(this.statsCollectionInterval);
this.statsCollectionInterval = null;
}
// reset video frame polling
if (this.successMetricPoller) {
clearInterval(this.successMetricPoller);
Expand Down