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
Changes from 1 commit
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
Prev Previous commit
Next Next commit
Return generator from generateQueue function.
  • Loading branch information
i-zolotarenko committed Jan 4, 2024
commit 1522279856235e0284224204051af47037ec28e8
111 changes: 64 additions & 47 deletions packages/p2p-media-loader-core/src/hybrid-loader.ts
Original file line number Diff line number Diff line change
@@ -15,6 +15,7 @@ import * as LoggerUtils from "./utils/logger";
import * as StreamUtils from "./utils/stream";
import * as Utils from "./utils/utils";
import debug from "debug";
import { QueueItem } from "./utils/queue";

const FAILED_ATTEMPTS_CLEAR_INTERVAL = 60000;

@@ -199,17 +200,7 @@ export class HybridLoader {
}

private processQueue() {
const { queue, queueSegmentIds } = QueueUtils.generateQueue({
lastRequestedSegment: this.lastRequestedSegment,
playback: this.playback,
settings: this.settings,
skipSegment: (segment) => {
return (
this.requests.get(segment)?.status === "succeed" ||
this.segmentStorage.hasSegment(segment)
);
},
});
const { queue, queueSegmentIds } = this.generateQueue();
this.processRequests(queueSegmentIds);

const {
@@ -218,22 +209,6 @@ export class HybridLoader {
httpErrorRetries,
} = this.settings;

for (const engineRequest of this.engineRequests.values()) {
if (this.requests.executingHttpCount >= simultaneousHttpDownloads) break;
const request = this.requests.get(engineRequest.segment);
if (
!queueSegmentIds.has(engineRequest.segment.localId) &&
engineRequest.status === "pending" &&
(!request ||
request.status === "not-started" ||
(request.status === "failed" &&
request.failedAttempts.httpAttemptsCount <
this.settings.httpErrorRetries))
) {
void this.loadThroughHttp(engineRequest.segment);
}
}

for (const item of queue) {
const { statuses, segment } = item;
const request = this.requests.get(segment);
@@ -328,36 +303,46 @@ export class HybridLoader {
const { simultaneousHttpDownloads, httpErrorRetries } = this.settings;
const p2pLoader = this.p2pLoaders.currentLoader;
const connectedPeersAmount = p2pLoader.connectedPeersAmount;

if (
this.requests.executingHttpCount >= simultaneousHttpDownloads ||
!connectedPeersAmount
) {
return;
}
const { queue } = QueueUtils.generateQueue({
lastRequestedSegment: this.lastRequestedSegment,
playback: this.playback,
settings: this.settings,
skipSegment: (segment, statuses) => {
const request = this.requests.get(segment);
return (
!statuses.isHttpDownloadable ||
this.segmentStorage.hasSegment(segment) ||
request?.type !== undefined ||
(request?.failedAttempts.httpAttemptsCount ?? 0) >=
httpErrorRetries ||
p2pLoader.isLoadingOrLoadedBySomeone(segment)
);
},
});
if (!queue.length) return;

const segmentsToLoad: Segment[] = [];
for (const { segment, statuses } of QueueUtils.generateQueue(
this.lastRequestedSegment,
this.playback,
this.settings
)) {
if (
!statuses.isHttpDownloadable ||
p2pLoader.isLoadingOrLoadedBySomeone(segment) ||
this.segmentStorage.hasSegment(segment)
) {
continue;
}
const request = this.requests.get(segment);
if (
request &&
(request.status === "succeed" ||
(request.failedAttempts.httpAttemptsCount ?? 0) >= httpErrorRetries)
) {
continue;
}
segmentsToLoad.push(segment);
}

if (!segmentsToLoad.length) return;
const peersAmount = connectedPeersAmount + 1;
const probability = Math.min(queue.length / peersAmount, 1);
const probability = Math.min(segmentsToLoad.length / peersAmount, 1);
const shouldLoad = Math.random() < probability;

if (!shouldLoad) return;
const item = Utils.getRandomItem(queue);
void this.loadThroughHttp(item.segment);
const segment = Utils.getRandomItem(segmentsToLoad);
void this.loadThroughHttp(segment);
}

private abortLastHttpLoadingInQueueAfterItem(
@@ -390,6 +375,38 @@ export class HybridLoader {
return false;
}

private generateQueue() {
const queue: QueueItem[] = [];
const queueSegmentIds = new Set<string>();
let maxPossibleLength = 0;
let alreadyLoadedAmount = 0;
for (const item of QueueUtils.generateQueue(
this.lastRequestedSegment,
this.playback,
this.settings
)) {
maxPossibleLength++;
const { segment } = item;
if (
this.segmentStorage.hasSegment(segment) ||
this.requests.get(segment)?.status === "succeed"
) {
alreadyLoadedAmount++;
continue;
}
queue.push(item);
queueSegmentIds.add(segment.localId);
}

return {
queue,
queueSegmentIds,
maxPossibleLength,
alreadyLoadedAmount,
loadedPercent: (alreadyLoadedAmount / maxPossibleLength) * 100,
};
}

updatePlayback(position: number, rate: number) {
const isRateChanged = this.playback.rate !== rate;
const isPositionChanged = this.playback.position !== position;
2 changes: 1 addition & 1 deletion packages/p2p-media-loader-core/src/p2p/tracker-client.ts
Original file line number Diff line number Diff line change
@@ -42,9 +42,9 @@ export class P2PTrackerClient {
port: 6881,
announce: [
// "wss://tracker.novage.com.ua",
"wss://tracker.openwebtorrent.com",
"wss://tracker.webtorrent.dev",
"wss://tracker.files.fm:7073/announce",
"wss://tracker.openwebtorrent.com",
],
rtcConfig: {
iceServers: [
67 changes: 33 additions & 34 deletions packages/p2p-media-loader-core/src/utils/queue.ts
Original file line number Diff line number Diff line change
@@ -7,44 +7,43 @@ import {

export type QueueItem = { segment: Segment; statuses: SegmentPlaybackStatuses };

export function generateQueue({
lastRequestedSegment,
playback,
settings,
skipSegment,
}: {
lastRequestedSegment: Readonly<Segment>;
playback: Readonly<Playback>;
skipSegment: (segment: Segment, statuses: SegmentPlaybackStatuses) => boolean;
settings: PlaybackTimeWindowsSettings;
}): { queue: QueueItem[]; queueSegmentIds: Set<string> } {
export function* generateQueue(
lastRequestedSegment: Readonly<Segment>,
playback: Readonly<Playback>,
settings: PlaybackTimeWindowsSettings
): Generator<QueueItem, void> {
const { localId: requestedSegmentId, stream } = lastRequestedSegment;
const queueSegments = stream.segments.values(requestedSegmentId);

const first = queueSegments.next().value;
if (!first) return;

const firstStatuses = getSegmentPlaybackStatuses(first, playback, settings);
if (isNotActualStatuses(firstStatuses)) {
firstStatuses.isHighDemand = true;
yield { segment: first, statuses: firstStatuses };

// for cases when engine requests segment that is a little bit
// earlier than current playhead position
// it could happen when playhead position is significantly changed by user
const second = queueSegments.next().value;
if (!second) return;
const secondStatuses = getSegmentPlaybackStatuses(
second,
playback,
settings
);
if (isNotActualStatuses(secondStatuses)) return;
yield { segment: second, statuses: secondStatuses };
} else {
yield { segment: first, statuses: firstStatuses };
}

const queue: QueueItem[] = [];
const queueSegmentIds = new Set<string>();

const { segments } = stream;
const isNextNotActual = (segmentId: string) => {
const next = segments.getNextTo(segmentId)?.[1];
if (!next) return true;
const statuses = getSegmentPlaybackStatuses(next, playback, settings);
return isNotActualStatuses(statuses);
};

let i = 0;
for (const segment of segments.values(requestedSegmentId)) {
for (const segment of queueSegments) {
const statuses = getSegmentPlaybackStatuses(segment, playback, settings);
const isNotActual = isNotActualStatuses(statuses);
if (isNotActual && (i !== 0 || isNextNotActual(requestedSegmentId))) break;
i++;
if (skipSegment(segment, statuses)) continue;

if (isNotActual) statuses.isHighDemand = true;
queue.push({ segment, statuses });
queueSegmentIds.add(segment.localId);
if (isNotActualStatuses(statuses)) break;
yield { segment, statuses };
}

return { queue, queueSegmentIds };
}

function isNotActualStatuses(statuses: SegmentPlaybackStatuses) {