Skip to content

Commit e34c363

Browse files
Refactor: dynamic liveSyncDurationCount based on fragment duration in hls.js package (#450)
1 parent 8b74e2f commit e34c363

File tree

1 file changed

+29
-7
lines changed

1 file changed

+29
-7
lines changed

packages/p2p-media-loader-hlsjs/src/engine.ts

Lines changed: 29 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -61,6 +61,8 @@ export type HlsWithP2PConfig<HlsType extends abstract new () => unknown> =
6161
};
6262
};
6363

64+
const MAX_LIVE_SYNC_DURATION = 120;
65+
6466
/**
6567
* Represents a P2P (peer-to-peer) engine for HLS (HTTP Live Streaming) to enhance media streaming efficiency.
6668
* This class integrates P2P technologies into HLS.js, enabling the distribution of media segments via a peer network
@@ -307,25 +309,45 @@ export class HlsJsP2PEngine {
307309
) => {
308310
if (
309311
this.currentHlsInstance &&
310-
this.currentHlsInstance.config.liveSyncDurationCount !==
311-
data.details.fragments.length - 1 &&
312312
data.details.live &&
313313
data.details.fragments[0].type === ("main" as PlaylistLevelType) &&
314314
!this.currentHlsInstance.userConfig.liveSyncDuration &&
315315
!this.currentHlsInstance.userConfig.liveSyncDurationCount &&
316316
data.details.fragments.length > 4
317317
) {
318-
this.debug(
319-
`set liveSyncDurationCount ${data.details.fragments.length - 1}`,
320-
);
321-
this.currentHlsInstance.config.liveSyncDurationCount =
322-
data.details.fragments.length - 1;
318+
this.updateLiveSyncDurationCount(data);
323319
}
324320

325321
this.core.setIsLive(data.details.live);
326322
this.segmentManager.updatePlaylist(data);
327323
};
328324

325+
private updateLiveSyncDurationCount(
326+
data: LevelUpdatedData | AudioTrackLoadedData,
327+
) {
328+
const fragmentDuration = data.details.targetduration;
329+
330+
const maxLiveSyncCount = Math.floor(
331+
MAX_LIVE_SYNC_DURATION / fragmentDuration,
332+
);
333+
const newLiveSyncDurationCount = Math.min(
334+
data.details.fragments.length - 1,
335+
maxLiveSyncCount,
336+
);
337+
338+
if (
339+
this.currentHlsInstance &&
340+
this.currentHlsInstance.config.liveSyncDurationCount !==
341+
newLiveSyncDurationCount
342+
) {
343+
this.debug(
344+
`Setting liveSyncDurationCount to ${newLiveSyncDurationCount}`,
345+
);
346+
this.currentHlsInstance.config.liveSyncDurationCount =
347+
newLiveSyncDurationCount;
348+
}
349+
}
350+
329351
private handleMediaAttached = () => {
330352
this.updateMediaElementEventHandlers("register");
331353
};

0 commit comments

Comments
 (0)