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 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
2 changes: 1 addition & 1 deletion .github/workflows/check-pr.yml
Original file line number Diff line number Diff line change
Expand Up @@ -29,4 +29,4 @@ jobs:
- run: pnpm lint
- run: pnpm build
- run: npx tsc
working-directory: ./p2p-media-loader-demo
working-directory: ./demo
2 changes: 1 addition & 1 deletion .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ pnpm-debug.log*
lerna-debug.log*

node_modules
/p2p-media-loader-demo/dist
/demo/dist
/packages/*/dist
/packages/*/lib
/packages/*/build
Expand Down
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
4 changes: 2 additions & 2 deletions p2p-media-loader-demo/package.json → demo/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -21,11 +21,11 @@
},
"devDependencies": {
"@types/dplayer": "^1.25.5",
"@types/react": "^18.2.45",
"@types/react": "^18.2.47",
"@types/react-dom": "^18.2.18",
"@vitejs/plugin-react": "^4.2.1",
"eslint-plugin-react-hooks": "^4.6.0",
"eslint-plugin-react-refresh": "^0.4.5",
"vite-plugin-node-polyfills": "^0.18.0"
"vite-plugin-node-polyfills": "^0.19.0"
}
}
2 changes: 1 addition & 1 deletion p2p-media-loader-demo/src/App.tsx → 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
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
Original file line number Diff line number Diff line change
Expand Up @@ -3,5 +3,6 @@ import react from "@vitejs/plugin-react";
import { nodePolyfills } from "vite-plugin-node-polyfills";

export default defineConfig({
server: { open: true, host: true },
plugins: [nodePolyfills(), react()],
});
8 changes: 4 additions & 4 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -15,14 +15,14 @@
},
"devDependencies": {
"@types/debug": "^4.1.12",
"@typescript-eslint/eslint-plugin": "^6.15.0",
"@typescript-eslint/parser": "^6.15.0",
"@typescript-eslint/eslint-plugin": "^6.18.1",
"@typescript-eslint/parser": "^6.18.1",
"eslint": "^8.56.0",
"eslint-plugin-prettier": "^5.1.2",
"eslint-plugin-prettier": "^5.1.3",
"prettier": "^3.1.1",
"rimraf": "^5.0.5",
"typescript": "^5.3.3",
"vite": "^5.0.10"
"vite": "^5.0.11"
},
"dependencies": {
"debug": "^4.3.4"
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