Skip to content
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

Bandwidth algorithm. #325

Merged
merged 21 commits into from
Jan 10, 2024
Merged
Show file tree
Hide file tree
Changes from 17 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
2 changes: 1 addition & 1 deletion p2p-media-loader-demo/src/App.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -133,7 +133,7 @@ function App() {

const initHlsDPlayer = (url: string) => {
if (!hlsEngine.current) return;
const engine = hlsEngine.current!;
const engine = hlsEngine.current;
const player = new DPlayer({
container: containerRef.current,
video: {
Expand Down
56 changes: 45 additions & 11 deletions packages/p2p-media-loader-core/src/bandwidth-calculator.ts
Original file line number Diff line number Diff line change
@@ -1,15 +1,17 @@
const CLEAR_THRESHOLD_MS = 3000;

export class BandwidthCalculator {
private simultaneousLoadingsCount = 0;
private readonly bytes: number[] = [];
private readonly loadingOnlyTimestamps: number[] = [];
private readonly timestamps: number[] = [];
private noLoadingsTotalTime = 0;
private allLoadingsStoppedTimestamp = 0;

constructor(private readonly clearThresholdMs = 10000) {}

addBytes(bytesLength: number, now = performance.now()) {
this.bytes.push(bytesLength);
this.timestamps.push(now - this.noLoadingsTotalTime);
this.loadingOnlyTimestamps.push(now - this.noLoadingsTotalTime);
this.timestamps.push(now);
}

startLoading(now = performance.now()) {
Expand All @@ -28,36 +30,68 @@ export class BandwidthCalculator {
this.allLoadingsStoppedTimestamp = now;
}

getBandwidthForLastNSeconds(seconds: number) {
if (!this.timestamps.length) return 0;
getBandwidthLoadingOnly(
seconds: number,
ignoreThresholdTimestamp = Number.NEGATIVE_INFINITY
) {
if (!this.loadingOnlyTimestamps.length) return 0;
const milliseconds = seconds * 1000;
const lastItemTimestamp = this.timestamps[this.timestamps.length - 1];
const lastItemTimestamp =
this.loadingOnlyTimestamps[this.loadingOnlyTimestamps.length - 1];
let lastCountedTimestamp = lastItemTimestamp;
const threshold = lastItemTimestamp - milliseconds;
let totalBytes = 0;

for (let i = this.bytes.length - 1; i >= 0; i--) {
const timestamp = this.timestamps[i];
if (timestamp < threshold) break;
const timestamp = this.loadingOnlyTimestamps[i];
if (
timestamp < threshold ||
this.timestamps[i] < ignoreThresholdTimestamp
) {
break;
}
lastCountedTimestamp = timestamp;
totalBytes += this.bytes[i];
}

return (totalBytes * 8000) / (lastItemTimestamp - lastCountedTimestamp);
}

getBandwidth(
seconds: number,
ignoreThresholdTimestamp = Number.NEGATIVE_INFINITY,
now = performance.now()
) {
if (!this.timestamps.length) return 0;
const milliseconds = seconds * 1000;
const threshold = now - milliseconds;
let lastCountedTimestamp = now;
let totalBytes = 0;

for (let i = this.bytes.length - 1; i >= 0; i--) {
const timestamp = this.timestamps[i];
if (timestamp < threshold || timestamp < ignoreThresholdTimestamp) break;
lastCountedTimestamp = timestamp;
totalBytes += this.bytes[i];
}

return (totalBytes * 8000) / (now - lastCountedTimestamp);
}

clearStale() {
if (!this.timestamps.length) return;
if (!this.loadingOnlyTimestamps.length) return;
const threshold =
this.timestamps[this.timestamps.length - 1] - CLEAR_THRESHOLD_MS;
this.loadingOnlyTimestamps[this.loadingOnlyTimestamps.length - 1] -
this.clearThresholdMs;

let samplesToRemove = 0;
for (const timestamp of this.timestamps) {
for (const timestamp of this.loadingOnlyTimestamps) {
if (timestamp > threshold) break;
samplesToRemove++;
}

this.bytes.splice(0, samplesToRemove);
this.loadingOnlyTimestamps.splice(0, samplesToRemove);
this.timestamps.splice(0, samplesToRemove);
}
}
32 changes: 27 additions & 5 deletions packages/p2p-media-loader-core/src/core.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,9 +6,10 @@ import {
Settings,
SegmentBase,
CoreEventHandlers,
BandwidthCalculators,
StreamDetails,
} from "./types";
import * as StreamUtils from "./utils/stream";
import { LinkedMap } from "./linked-map";
import { BandwidthCalculator } from "./bandwidth-calculator";
import { EngineCallbacks } from "./requests/engine-request";
import { SegmentsMemoryStorage } from "./segments-storage";
Expand All @@ -31,10 +32,17 @@ export class Core<TStream extends Stream = Stream> {
httpErrorRetries: 3,
p2pErrorRetries: 3,
};
private readonly bandwidthCalculator = new BandwidthCalculator();
private readonly bandwidthCalculators: BandwidthCalculators = {
all: new BandwidthCalculator(),
http: new BandwidthCalculator(),
};
private segmentStorage?: SegmentsMemoryStorage;
private mainStreamLoader?: HybridLoader;
private secondaryStreamLoader?: HybridLoader;
private streamDetails: StreamDetails = {
isLive: false,
activeLevelBitrate: 0,
};

constructor(private readonly eventHandlers?: CoreEventHandlers) {}

Expand All @@ -58,7 +66,7 @@ export class Core<TStream extends Stream = Stream> {
if (this.streams.has(stream.localId)) return;
this.streams.set(stream.localId, {
...stream,
segments: new LinkedMap<string, Segment>(),
segments: new Map<string, Segment>(),
});
}

Expand All @@ -72,7 +80,7 @@ export class Core<TStream extends Stream = Stream> {

addSegments?.forEach((s) => {
const segment = { ...s, stream };
stream.segments.addToEnd(segment.localId, segment);
stream.segments.set(segment.localId, segment);
});
removeSegmentIds?.forEach((id) => stream.segments.delete(id));
this.mainStreamLoader?.updateStream(stream);
Expand Down Expand Up @@ -105,6 +113,18 @@ export class Core<TStream extends Stream = Stream> {
this.secondaryStreamLoader?.updatePlayback(position, rate);
}

setActiveLevelBitrate(bitrate: number) {
if (bitrate !== this.streamDetails.activeLevelBitrate) {
this.streamDetails.activeLevelBitrate = bitrate;
this.mainStreamLoader?.notifyLevelChanged();
this.secondaryStreamLoader?.notifyLevelChanged();
}
}

setIsLive(isLive: boolean) {
this.streamDetails.isLive = isLive;
}

destroy(): void {
this.streams.clear();
this.mainStreamLoader?.destroy();
Expand All @@ -114,6 +134,7 @@ export class Core<TStream extends Stream = Stream> {
this.secondaryStreamLoader = undefined;
this.segmentStorage = undefined;
this.manifestResponseUrl = undefined;
this.streamDetails = { isLive: false, activeLevelBitrate: 0 };
}

private identifySegment(segmentId: string): Segment {
Expand Down Expand Up @@ -143,8 +164,9 @@ export class Core<TStream extends Stream = Stream> {
return new HybridLoader(
manifestResponseUrl,
segment,
this.streamDetails as Required<StreamDetails>,
this.settings,
this.bandwidthCalculator,
this.bandwidthCalculators,
this.segmentStorage,
this.eventHandlers
);
Expand Down
Loading