Skip to content

Commit

Permalink
Move Request file to separate file.
Browse files Browse the repository at this point in the history
  • Loading branch information
i-zolotarenko committed Nov 13, 2023
1 parent e019870 commit eb1ba54
Show file tree
Hide file tree
Showing 8 changed files with 233 additions and 259 deletions.
10 changes: 2 additions & 8 deletions packages/p2p-media-loader-core/src/http-loader.ts
Original file line number Diff line number Diff line change
Expand Up @@ -35,15 +35,9 @@ export async function fulfillHttpSegmentRequest(
});

if (fetchResponse.ok) {
const totalBytesString = fetchResponse.headers.get("Content-Length");
if (!fetchResponse.body) {
fetchResponse.arrayBuffer().then((data) => {
requestControls.addLoadedChunk(data);
requestControls.completeOnSuccess();
});
return;
}
if (!fetchResponse.body) return;

const totalBytesString = fetchResponse.headers.get("Content-Length");
if (totalBytesString) request.setTotalBytes(+totalBytesString);

const reader = fetchResponse.body.getReader();
Expand Down
69 changes: 10 additions & 59 deletions packages/p2p-media-loader-core/src/hybrid-loader.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,14 +4,12 @@ import { SegmentsMemoryStorage } from "./segments-storage";
import { Settings, CoreEventHandlers } from "./types";
import { BandwidthApproximator } from "./bandwidth-approximator";
import { Playback, QueueItem } from "./internal-types";
import {
RequestsContainer,
EngineCallbacks,
HybridLoaderRequest,
Request,
} from "./request-container";
import { RequestsContainer } from "./request-container";
import { Request, EngineCallbacks, HybridLoaderRequest } from "./request";
import * as QueueUtils from "./utils/queue";
import * as LoggerUtils from "./utils/logger";
import * as StreamUtils from "./utils/stream";
import * as Utils from "./utils/utils";
import { P2PLoadersContainer } from "./p2p/loaders-container";
import { PeerRequestError } from "./p2p/peer";
import debug from "debug";
Expand Down Expand Up @@ -40,7 +38,7 @@ export class HybridLoader {
this.lastRequestedSegment = requestedSegment;
const activeStream = requestedSegment.stream;
this.playback = { position: requestedSegment.startTime, rate: 1 };
this.segmentAvgDuration = getSegmentAvgDuration(activeStream);
this.segmentAvgDuration = StreamUtils.getSegmentAvgDuration(activeStream);
this.requests = new RequestsContainer(
requestedSegment.stream.type,
this.bandwidthApproximator
Expand Down Expand Up @@ -159,23 +157,6 @@ export class HybridLoader {

if (statuses.isHighDemand) {
if (request?.type === "http") continue;

if (request?.type === "p2p") {
const timeToPlayback = getTimeToSegmentPlayback(
segment,
this.playback
);
const remainingDownloadTime =
getPredictedRemainingDownloadTime(request);
if (
remainingDownloadTime === undefined ||
remainingDownloadTime > timeToPlayback
) {
request.abort();
} else {
continue;
}
}
if (this.requests.executingHttpCount < simultaneousHttpDownloads) {
void this.loadThroughHttp(item);
continue;
Expand Down Expand Up @@ -218,8 +199,11 @@ export class HybridLoader {

// api method for engines
abortSegment(segment: Segment) {
const request = this.requests.get(segment);
if (!request) return;
request.abort();
this.createProcessQueueMicrotask();
this.logger.engine("abort: ", LoggerUtils.getSegmentString(segment));
this.requests.abortEngineRequest(segment);
}

private async loadThroughHttp(item: QueueItem, isRandom = false) {
Expand Down Expand Up @@ -286,7 +270,7 @@ export class HybridLoader {
const shouldLoad = Math.random() < probability;

if (!shouldLoad) return;
const item = queue[Math.floor(Math.random() * queue.length)];
const item = Utils.getRandomItem(queue);
void this.loadThroughHttp(item, true);

this.logger.loader(
Expand Down Expand Up @@ -387,36 +371,3 @@ function* arrayBackwards<T>(arr: T[]) {
yield arr[i];
}
}

function getTimeToSegmentPlayback(segment: Segment, playback: Playback) {
return Math.max(segment.startTime - playback.position, 0) / playback.rate;
}

function getPredictedRemainingDownloadTime(request: HybridLoaderRequest) {
const { progress } = request;
if (!progress || progress.lastLoadedChunkTimestamp === undefined) {
return undefined;
}

const now = performance.now();
const bandwidth =
progress.percent /
(progress.lastLoadedChunkTimestamp - progress.startTimestamp);
const remainingDownloadPercent = 100 - progress.percent;
const predictedRemainingTimeFromLastDownload =
remainingDownloadPercent / bandwidth;
const timeFromLastDownload = now - progress.lastLoadedChunkTimestamp;
return (predictedRemainingTimeFromLastDownload - timeFromLastDownload) / 1000;
}

function getSegmentAvgDuration(stream: StreamWithSegments) {
const { segments } = stream;
let sumDuration = 0;
const size = segments.size;
for (const segment of segments.values()) {
const duration = segment.endTime - segment.startTime;
sumDuration += duration;
}

return sumDuration / size;
}
16 changes: 7 additions & 9 deletions packages/p2p-media-loader-core/src/p2p/loader.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,10 +4,12 @@ import * as PeerUtil from "../utils/peer";
import { Segment, Settings, StreamWithSegments } from "../types";
import { QueueItem } from "../internal-types";
import { SegmentsMemoryStorage } from "../segments-storage";
import * as Utils from "../utils/utils";
import * as LoggerUtils from "../utils/logger";
import * as StreamUtils from "../utils/stream";
import * as Utils from "../utils/utils";
import { PeerSegmentStatus } from "../enums";
import { Request, RequestsContainer } from "../request-container";
import { RequestsContainer } from "../request-container";
import { Request } from "../request";
import debug from "debug";

export class P2PLoader {
Expand All @@ -26,7 +28,7 @@ export class P2PLoader {
private readonly settings: Settings
) {
this.peerId = PeerUtil.generatePeerId();
const streamExternalId = Utils.getStreamExternalId(
const streamExternalId = StreamUtils.getStreamExternalId(
this.streamManifestUrl,
this.stream
);
Expand Down Expand Up @@ -108,7 +110,7 @@ export class P2PLoader {
}

const peer = untestedPeers.length
? getRandomItem(untestedPeers)
? Utils.getRandomItem(untestedPeers)
: fastestPeer;

if (!peer) return;
Expand Down Expand Up @@ -182,7 +184,7 @@ export class P2PLoader {
};

private async onSegmentRequested(peer: Peer, segmentExternalId: string) {
const segment = Utils.getSegmentFromStreamByExternalId(
const segment = StreamUtils.getSegmentFromStreamByExternalId(
this.stream,
segmentExternalId
);
Expand Down Expand Up @@ -245,7 +247,3 @@ function utf8ToHex(utf8String: string) {

return result;
}

function getRandomItem<T>(items: T[]): T {
return items[Math.floor(Math.random() * items.length)];
}
2 changes: 1 addition & 1 deletion packages/p2p-media-loader-core/src/p2p/peer.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ import {
} from "../internal-types";
import { PeerCommandType, PeerSegmentStatus } from "../enums";
import * as PeerUtil from "../utils/peer";
import { Request, RequestControls } from "../request-container";
import { Request, RequestControls } from "../request";
import { Segment, Settings } from "../types";
import * as Utils from "../utils/utils";
import debug from "debug";
Expand Down
Loading

0 comments on commit eb1ba54

Please sign in to comment.