@vkontakte/videoplayer-core 2.0.171-dev.4982aad68.0 → 2.0.171-dev.881304e5f.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (35) hide show
  1. package/es2015.cjs +37 -43
  2. package/es2015.esm.js +38 -44
  3. package/esnext.cjs +29 -35
  4. package/esnext.esm.js +34 -40
  5. package/evergreen.esm.js +34 -40
  6. package/package.json +2 -2
  7. package/types/player/Player.d.ts +1 -0
  8. package/types/providers/DashLiveProvider/utils/LiveDashPlayer.d.ts +2 -0
  9. package/types/providers/DashProvider/baseDashProvider.d.ts +1 -2
  10. package/types/providers/DashProvider/lib/buffer.d.ts +0 -2
  11. package/types/providers/DashProvider/lib/fetcher.d.ts +4 -6
  12. package/types/providers/DashProvider/lib/player.d.ts +0 -1
  13. package/types/providers/DashProvider/lib/urlsCache.d.ts +23 -0
  14. package/types/providers/DashProviderVirtual/baseDashProvider.d.ts +1 -2
  15. package/types/providers/DashProviderVirtual/lib/buffer/types.d.ts +0 -2
  16. package/types/providers/DashProviderVirtual/lib/buffer/virtualBuffer/baseVirtualBufferManager.versionA.d.ts +1 -3
  17. package/types/providers/DashProviderVirtual/lib/buffer/virtualBuffer/byteRangeVirtualBufferManager.versionA.d.ts +0 -1
  18. package/types/providers/DashProviderVirtual/lib/fetcher.d.ts +4 -6
  19. package/types/providers/DashProviderVirtual/lib/player/basePlayer.d.ts +0 -2
  20. package/types/providers/DashProviderVirtual/lib/urlsCache.d.ts +22 -0
  21. package/types/providers/ProviderContainer/index.d.ts +0 -3
  22. package/types/providers/ProviderContainer/utils/formatsSupport.d.ts +0 -1
  23. package/types/providers/utils/Abr/types.d.ts +1 -4
  24. package/types/providers/utils/Abr/utils.d.ts +1 -3
  25. package/types/utils/timers.d.ts +2 -0
  26. package/types/utils/tuningConfig.d.ts +13 -19
  27. package/types/providers/utils/Abr/rules/video/downloadTimeRule.d.ts +0 -15
  28. package/types/providers/utils/segmentCache/IndexedDbSegmentCacheStorage.d.ts +0 -52
  29. package/types/providers/utils/segmentCache/SegmentCache.d.ts +0 -40
  30. package/types/providers/utils/segmentCache/constants.d.ts +0 -20
  31. package/types/providers/utils/segmentCache/index.d.ts +0 -8
  32. package/types/providers/utils/segmentCache/segmentCacheDb.d.ts +0 -25
  33. package/types/providers/utils/segmentCache/segmentCacheUtils.d.ts +0 -25
  34. package/types/providers/utils/segmentCache/types.d.ts +0 -74
  35. package/types/utils/buffer/dynamicBufferTarget.d.ts +0 -10
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@vkontakte/videoplayer-core",
3
- "version": "2.0.171-dev.4982aad68.0",
3
+ "version": "2.0.171-dev.881304e5f.0",
4
4
  "author": "vk.ru",
5
5
  "description": "Videoplayer core library based on the vk.ru platform",
6
6
  "homepage": "https://vk.ru",
@@ -42,6 +42,6 @@
42
42
  "**/*.d.ts"
43
43
  ],
44
44
  "dependencies": {
45
- "@vkontakte/videoplayer-shared": "1.0.100-dev.4982aad68.0"
45
+ "@vkontakte/videoplayer-shared": "1.0.100-dev.881304e5f.0"
46
46
  }
47
47
  }
@@ -30,6 +30,7 @@ export default class Player implements IPlayer {
30
30
  experimental: PlayerExperimentalImpl;
31
31
  private devNullLog;
32
32
  private collectDecodingInfoDestroyCb;
33
+ private hasReleasedTimers;
33
34
  constructor(tuning?: IOptionalTuningConfig, tracer?: ITracer, playerOptions?: IPlayerOptions);
34
35
  private readonly doInit;
35
36
  /**
@@ -49,6 +49,8 @@ export default class LiveDashPlayer {
49
49
  private bufferStates;
50
50
  private downloadRate?;
51
51
  private sourceJitter;
52
+ /** Токен для защиты от устаревших callback'ов sourceopen при многократных вызовах _setVideoSrc */
53
+ private srcToken;
52
54
  private chunkRateEstimator;
53
55
  private manifestUrl;
54
56
  private urlResolver;
@@ -54,9 +54,8 @@ export default abstract class BaseDashProvider implements IProvider {
54
54
  protected getProviderSubscriptionInfo(): IProviderSubscriptionInfo;
55
55
  protected subscribe(): void;
56
56
  private syncBufferTarget;
57
- private resolveAudioBufferTargetMs;
58
57
  private resolveBufferTargetMs;
59
- private getCurrentVideoBitrateKbps;
58
+ private resolveAudioBufferTargetMs;
60
59
  protected selectVideoAudioRepresentations(): [Representation, Representation | undefined] | undefined;
61
60
  protected prepare(manifestOffset?: number): void;
62
61
  protected syncPlayback: () => void;
@@ -41,7 +41,6 @@ export declare class BufferManager {
41
41
  private parsedInitData;
42
42
  private representations;
43
43
  private segments;
44
- private segmentIndexMap;
45
44
  private allInitsLoaded;
46
45
  private activeSegments;
47
46
  private forwardBufferRepresentations;
@@ -107,7 +106,6 @@ export declare class BufferManager {
107
106
  private feedPreDownloadedFirstSegment;
108
107
  private loadByteRangeSegments;
109
108
  private prepareByteRangeFetchSegmentParams;
110
- private buildCacheMetadata;
111
109
  private prepareTemplateFetchSegmentParams;
112
110
  private abortActiveSegments;
113
111
  private onSomeTemplateDataLoaded;
@@ -4,7 +4,6 @@ import type { Byte, IValueSubject, ISubject, Milliseconds, IRange, ITracer, IErr
4
4
  import { abortable } from "@vkontakte/videoplayer-shared";
5
5
  import type { ExactVideoQuality } from "@vkontakte/videoplayer-shared";
6
6
  import type { CommonInit, GenericContainerParser, Segment, SegmentReference } from "../../utils/parsers/types";
7
- import type { ISegmentCacheStorage, CacheMetadata } from "../../utils/segmentCache";
8
7
  declare global {
9
8
  interface Navigator {
10
9
  connection: {
@@ -25,11 +24,11 @@ export interface IParams {
25
24
  tracer: ITracer;
26
25
  useEnableSubtitlesParam?: boolean;
27
26
  handleExtendedNetworkErrorsSet?: boolean;
27
+ useUrlCacheMechanism?: boolean;
28
28
  measureNonSegmentRequests?: boolean;
29
29
  measureFastSamples?: boolean;
30
30
  preloadFirstSegment?: boolean;
31
31
  maxQualityForFirstSegmentPreload?: ExactVideoQuality;
32
- segmentCacheService?: ISegmentCacheStorage;
33
32
  }
34
33
  export type Priority = "high" | "low" | "auto";
35
34
  export interface FetchParamsWithUrl extends FetchParams {
@@ -46,8 +45,8 @@ export interface FetchParams {
46
45
  isLowLatency?: boolean;
47
46
  bufferOptimisation?: boolean;
48
47
  ignoreNetworkErrors?: boolean;
48
+ urlCacheMechanismEnabled?: boolean;
49
49
  representationHeight?: number;
50
- cacheMetadata?: CacheMetadata;
51
50
  }
52
51
  export type RepresentationFetchResult = {
53
52
  init: CommonInit | null;
@@ -74,17 +73,16 @@ export declare class Fetcher {
74
73
  private readonly subscription;
75
74
  private compatibilityMode;
76
75
  private useEnableSubtitlesParam;
76
+ private useUrlCacheMechanism;
77
77
  private measureNonSegmentRequests;
78
78
  private measureFastSamples;
79
79
  private preloadFirstSegment;
80
80
  private maxQualityForFirstSegmentPreload;
81
- private segmentCacheService;
82
- private segmentCache;
83
81
  private startupPhase;
84
82
  private performanceObserver;
85
83
  private pendingConnectionMetrics;
86
84
  private handleExtendedNetworkErrorsSet;
87
- constructor({ throughputEstimator, requestQuic, tracer, compatibilityMode, useEnableSubtitlesParam, handleExtendedNetworkErrorsSet, measureNonSegmentRequests, measureFastSamples, preloadFirstSegment, maxQualityForFirstSegmentPreload, segmentCacheService }: IParams);
85
+ constructor({ throughputEstimator, requestQuic, tracer, compatibilityMode, useEnableSubtitlesParam, handleExtendedNetworkErrorsSet, useUrlCacheMechanism, measureNonSegmentRequests, measureFastSamples, preloadFirstSegment, maxQualityForFirstSegmentPreload }: IParams);
88
86
  private onHeadersReceived;
89
87
  private setupPerformanceObserver;
90
88
  private processPerformanceResourceTiming;
@@ -40,7 +40,6 @@ export declare class Player {
40
40
  private subscriptionRemovable;
41
41
  private representationSubscription;
42
42
  private fetcher;
43
- private segmentCacheService;
44
43
  state$: StateMachine<State>;
45
44
  currentVideoRepresentation$: IValueSubject<Representation["id"] | undefined>;
46
45
  currentVideoRepresentationInit$: IValueSubject<CommonInit | undefined>;
@@ -0,0 +1,23 @@
1
+ export type CacheManager = {
2
+ get: () => Promise<Response | null>;
3
+ set: (response: Response) => void;
4
+ };
5
+ /**
6
+ * Пытаемся добиться кэширования вызовов.
7
+ * Сейчас есть проблема, что expires и sig меняются, хотя контент не меняется, поэтому ходим мимо кэша.
8
+ * Из за этого обрабатываем кэш вручную.
9
+ */
10
+ export declare const createCacheManager: (url: string) => Promise<CacheManager>;
11
+ export declare function canUseCacheApi(): boolean;
12
+ export declare function normalizeUrl(url: string): string;
13
+ /**
14
+ * Проверяет, не просрочен ли кэшированный ответ
15
+ */
16
+ export declare function isResponseExpired(response: Response): boolean;
17
+ export declare function cloneResponse(response: Response, url: string): Response;
18
+ /**
19
+ * Извлекает expires из оригинального URL (параметр expires1)
20
+ * Предполагается, что expires1 — timestamp в секундах
21
+ */
22
+ export declare function getExpiresFromUrl(url: string): number;
23
+ export declare const dropUrlsCache: () => Promise<void>;
@@ -55,9 +55,8 @@ export default abstract class BaseDashProvider implements IProvider {
55
55
  protected getProviderSubscriptionInfo(): IProviderSubscriptionInfo;
56
56
  protected subscribe(): void;
57
57
  private syncBufferTarget;
58
- private resolveAudioBufferTargetMs;
59
58
  private resolveBufferTargetMs;
60
- private getCurrentVideoBitrateKbps;
59
+ private resolveAudioBufferTargetMs;
61
60
  protected selectVideoAudioRepresentations(): [Representation, Representation | undefined] | undefined;
62
61
  protected prepare(manifestOffset?: number): void;
63
62
  protected syncPlayback: () => void;
@@ -3,7 +3,6 @@ import type { CommonInit, Manifest, Representation, Segment } from "../../../uti
3
3
  import type { Fetcher } from "../fetcher";
4
4
  import type { ITuningConfig } from "../../../../utils/tuningConfig";
5
5
  import type { VideoSegmentLoadProgress } from "../../../utils/Abr/types";
6
- import type { ISegmentCacheStorage } from "../../../utils/segmentCache";
7
6
  export type TRepresentationSwitchMode = "lazy" | "force";
8
7
  export declare enum SwithRepresentationMode {
9
8
  Lazy = "lazy",
@@ -16,7 +15,6 @@ export interface Dependencies {
16
15
  tuning: ITuningConfig;
17
16
  compatibilityMode?: boolean;
18
17
  manifest: Manifest | null;
19
- segmentCacheService?: ISegmentCacheStorage;
20
18
  getCurrentPosition(): Milliseconds | undefined;
21
19
  getCurrentStallDuration(): Milliseconds;
22
20
  isActiveLowLatency(): boolean;
@@ -2,7 +2,6 @@ import type { Fetcher, FetchParamsWithUrl, Priority, RepresentationFetchResult }
2
2
  import type { CommonInit, ContainerParser, Representation, Segment } from "../../../../utils/parsers/types";
3
3
  import { StreamKind } from "../../../../utils/parsers/types";
4
4
  import type { ITuningConfig } from "../../../../../utils/tuningConfig";
5
- import type { ISegmentCacheStorage } from "../../../../utils/segmentCache";
6
5
  import type { Byte, IError, IRange, ISubject, ITracer, IValueSubject, Milliseconds, Seconds } from "@vkontakte/videoplayer-shared";
7
6
  import { abortable, Subscription } from "@vkontakte/videoplayer-shared";
8
7
  import type { NativeBufferManager } from "../nativeBufferManager";
@@ -20,7 +19,6 @@ export declare abstract class BaseVirtualBufferManager<T extends Segment> implem
20
19
  protected readonly fetcher: Fetcher;
21
20
  protected readonly tracer: ITracer;
22
21
  protected readonly tuning: ITuningConfig;
23
- protected readonly segmentCacheService: ISegmentCacheStorage | undefined;
24
22
  protected representations: Map<Representation["id"], Representation>;
25
23
  protected playingRepresentationId: Representation["id"] | undefined;
26
24
  protected downloadingRepresentationId: Representation["id"] | undefined;
@@ -54,7 +52,7 @@ export declare abstract class BaseVirtualBufferManager<T extends Segment> implem
54
52
  protected subscription: Subscription;
55
53
  protected readonly getCurrentPosition: () => Milliseconds | undefined;
56
54
  protected readonly getCurrentStallDuration: () => Milliseconds | undefined;
57
- protected constructor(kind: StreamKind, nativeBufferManager: NativeBufferManager, representations: Representation[], { fetcher, tracer, tuning, getCurrentPosition, getCurrentStallDuration, manifest, segmentCacheService }: Dependencies);
55
+ protected constructor(kind: StreamKind, nativeBufferManager: NativeBufferManager, representations: Representation[], { fetcher, tracer, tuning, getCurrentPosition, getCurrentStallDuration, manifest }: Dependencies);
58
56
  protected abstract loadItems(itemsToLoad: IBufferPlaybackQueueItem<T>[], representation: Representation, priority?: Priority): Promise<void>;
59
57
  protected abstract selectItemsToLoad(): IBufferPlaybackQueueItem<T>[];
60
58
  protected abstract prepareFetchParams(items: IBufferPlaybackQueueItem<T>[], representation: Representation): FetchParamsWithUrl;
@@ -8,7 +8,6 @@ export declare class ByteRangeVirtualBufferManager extends BaseVirtualBufferMana
8
8
  protected override loadItems(itemsToLoad: IBufferPlaybackQueueItem<ByteRangeSegment>[], representation: Representation, priority?: Priority): Promise<void>;
9
9
  protected override selectItemsToLoad(): IBufferPlaybackQueueItem<ByteRangeSegment>[];
10
10
  protected override prepareFetchParams(items: IBufferPlaybackQueueItem<ByteRangeSegment>[], representation: Representation): FetchParamsWithUrl;
11
- private buildCacheMetadata;
12
11
  /**
13
12
  * Закидываем в буфер сегменты атомарнее чем сегмент целиком. Например, по боксам в мпеге и по блокам в вебме.
14
13
  * Таким образом не ждём его полной загрузки и готовы играть его намного быстрее
@@ -4,7 +4,6 @@ import type { Byte, IError, IRange, ISubject, ITracer, IValueSubject, Millisecon
4
4
  import { abortable } from "@vkontakte/videoplayer-shared";
5
5
  import type { ExactVideoQuality } from "@vkontakte/videoplayer-shared";
6
6
  import type { CommonInit, GenericContainerParser, Segment, SegmentReference, StreamKind } from "../../utils/parsers/types";
7
- import type { ISegmentCacheStorage, CacheMetadata } from "../../utils/segmentCache";
8
7
  declare global {
9
8
  interface Navigator {
10
9
  connection: {
@@ -25,11 +24,11 @@ export interface IParams {
25
24
  tracer: ITracer;
26
25
  useEnableSubtitlesParam?: boolean;
27
26
  handleExtendedNetworkErrorsSet?: boolean;
27
+ useUrlCacheMechanism?: boolean;
28
28
  measureNonSegmentRequests?: boolean;
29
29
  measureFastSamples?: boolean;
30
30
  preloadFirstSegment?: boolean;
31
31
  maxQualityForFirstSegmentPreload?: ExactVideoQuality;
32
- segmentCacheService?: ISegmentCacheStorage;
33
32
  }
34
33
  export type Priority = "high" | "low" | "auto";
35
34
  export interface FetchParamsWithUrl extends FetchParams {
@@ -45,8 +44,8 @@ export interface FetchParams {
45
44
  measureThroughput?: boolean;
46
45
  isLowLatency?: boolean;
47
46
  bufferOptimisation?: boolean;
47
+ urlCacheMechanismEnabled?: boolean;
48
48
  kind: StreamKind;
49
- cacheMetadata?: CacheMetadata;
50
49
  }
51
50
  export type RepresentationFetchResult<T extends Segment> = {
52
51
  initMetadata: CommonInit | null;
@@ -73,17 +72,16 @@ export declare class Fetcher {
73
72
  private subscription;
74
73
  private compatibilityMode;
75
74
  private useEnableSubtitlesParam;
75
+ private useUrlCacheMechanism;
76
76
  private measureNonSegmentRequests;
77
77
  private measureFastSamples;
78
78
  private preloadFirstSegment;
79
79
  private maxQualityForFirstSegmentPreload;
80
- private segmentCacheService;
81
- private segmentCache;
82
80
  private startupPhase;
83
81
  private performanceObserver;
84
82
  private pendingConnectionMetrics;
85
83
  private handleExtendedNetworkErrorsSet;
86
- constructor({ throughputEstimator, requestQuic, tracer, compatibilityMode, useEnableSubtitlesParam, handleExtendedNetworkErrorsSet, measureNonSegmentRequests, measureFastSamples, preloadFirstSegment, maxQualityForFirstSegmentPreload, segmentCacheService }: IParams);
84
+ constructor({ throughputEstimator, requestQuic, tracer, compatibilityMode, useEnableSubtitlesParam, handleExtendedNetworkErrorsSet, useUrlCacheMechanism, measureNonSegmentRequests, measureFastSamples, preloadFirstSegment, maxQualityForFirstSegmentPreload }: IParams);
87
85
  private onHeadersReceived;
88
86
  private setupPerformanceObserver;
89
87
  private processResourceTiming;
@@ -9,7 +9,6 @@ import type { IError, IRange, ISubject, ISubscription, ITracer, IValueSubject, M
9
9
  import { abortable, Subject, Subscription, SubscriptionRemovable } from "@vkontakte/videoplayer-shared";
10
10
  import type { VideoSegmentLoadProgress } from "../../../utils/Abr/types";
11
11
  import { Fetcher } from "../fetcher";
12
- import type { ISegmentCacheStorage } from "../../../utils/segmentCache";
13
12
  import type { Dependencies, IVirtualBufferManager, SwithRepresentationMode } from "../buffer/types";
14
13
  import type { Params } from "./types";
15
14
  import { State } from "./types";
@@ -36,7 +35,6 @@ export declare abstract class BasePlayer {
36
35
  protected subscriptionRemovable: SubscriptionRemovable;
37
36
  protected representationSubscription: Subscription;
38
37
  protected fetcher: Fetcher;
39
- protected segmentCacheService: ISegmentCacheStorage | undefined;
40
38
  protected forceEnded$: ISubject<void>;
41
39
  protected stallWatchdogSubscription: ISubscription | undefined;
42
40
  protected destroyController: AbortController;
@@ -0,0 +1,22 @@
1
+ export type CacheManager = {
2
+ get: () => Promise<Response | null>;
3
+ set: (response: Response) => Promise<void>;
4
+ };
5
+ /**
6
+ * Пытаемся добиться кэширования вызовов.
7
+ * Сейчас есть проблема, что expires и sig меняются, хотя контент не меняется, поэтому ходим мимо кэша.
8
+ * Из за этого обрабатываем кэш вручную.
9
+ */
10
+ export declare const createCacheManager: (url: string) => Promise<CacheManager>;
11
+ export declare function canUseCacheApi(): boolean;
12
+ export declare function normalizeUrl(url: string): string;
13
+ /**
14
+ * Проверяет, не просрочен ли кэшированный ответ
15
+ */
16
+ export declare function isResponseExpired(response: Response): boolean;
17
+ export declare function cloneResponse(response: Response, url: string): Response;
18
+ /**
19
+ * Извлекает expires из оригинального URL (параметр expires1)
20
+ * Предполагается, что expires1 — timestamp в секундах
21
+ */
22
+ export declare function getExpiresFromUrl(url: string): number;
@@ -37,7 +37,6 @@ export default class ProviderContainer implements IProviderContainer {
37
37
  private currentProviderStarted;
38
38
  private volumeMultiplierManager;
39
39
  private dashMaxTvVideoQuality;
40
- private segmentCacheCleared;
41
40
  private mayday;
42
41
  private maydayStatistics;
43
42
  constructor(params: IParams);
@@ -51,8 +50,6 @@ export default class ProviderContainer implements IProviderContainer {
51
50
  private destroyProvider;
52
51
  private handleMaydayRecommendation;
53
52
  private applyErrorSideEffects;
54
- /** Битые данные в кэше могут вызывать повторные ошибки после реинита — очищаем кэш целиком. */
55
- private clearSegmentCacheOnError;
56
53
  private createProvider;
57
54
  private createScreenProvider;
58
55
  private createChromecastProvider;
@@ -15,7 +15,6 @@ type LiveFormat = VideoFormat.WEB_RTC_LIVE | VideoFormat.HLS_LIVE | VideoFormat.
15
15
  type AllLiveFormats = [LiveFormat, LiveFormat, LiveFormat, LiveFormat, LiveFormat];
16
16
  export declare const getLiveFormatsPriority: ({ androidPreferredFormat, preferCMAF, preferWebRTC }: Constraints) => AllLiveFormats;
17
17
  export declare const getChromeCastFormatsPriority: (live: boolean) => VideoFormat[];
18
- export declare const selectCodec: (codecs: Set<string>) => string | undefined;
19
18
  type CodecStream = {
20
19
  codecs: string;
21
20
  hdr?: boolean;
@@ -21,8 +21,7 @@ export declare enum VideoRuleName {
21
21
  UpperLimit = "upper_limit_rule",
22
22
  Throughput = "throughput_rule",
23
23
  AbandonRequest = "abandon_request_rule",
24
- InsufficientBuffer = "insufficient_buffer_rule",
25
- DownloadTime = "download_time_rule"
24
+ InsufficientBuffer = "insufficient_buffer_rule"
26
25
  }
27
26
  export declare enum AudioRuleName {
28
27
  MinAudioForVideo = "min_audio_for_video_rule",
@@ -40,7 +39,6 @@ export interface IUpdatableAbrManagerContext {
40
39
  desiredVideoTrack: Nullable<IVideoTrack>;
41
40
  limits: QualityLimits;
42
41
  forwardBufferHealth?: number;
43
- forwardBufferTarget: Milliseconds;
44
42
  forwardVideoBufferRepresentations: Nullable<Map<Representation["id"], Segment[]>>;
45
43
  forwardAudioBufferRepresentations: Nullable<Map<Representation["id"], Segment[]>>;
46
44
  forwardBufferDuration?: Milliseconds;
@@ -120,7 +118,6 @@ export interface IVideoAbrContext extends IBaseAbrControllerContext {
120
118
  container: Nullable<IRectangle>;
121
119
  panelSize: Nullable<IRectangle>;
122
120
  forwardBufferRepresentations: Nullable<Map<Representation["id"], Segment[]>>;
123
- forwardBufferTarget: Milliseconds;
124
121
  limits: QualityLimits;
125
122
  visible: boolean;
126
123
  severeStallOccurred: boolean;
@@ -1,7 +1,5 @@
1
- import type { Kbps, Milliseconds, Nullable } from "@vkontakte/videoplayer-shared";
1
+ import type { Milliseconds, Nullable } from "@vkontakte/videoplayer-shared";
2
2
  import type { IAudioTrack, IBaseTrack, IVideoTrack } from "../../../player/types";
3
- import type { Segment } from "../parsers/types";
4
- export declare const computeForwardBitrate: (segments: Nullable<Segment[]>) => Kbps;
5
3
  export declare const bufferToPlaybackMs: (contentMs: Milliseconds | undefined, playbackRate: number) => Milliseconds;
6
4
  export declare enum CompareTrack {
7
5
  Descending = -1,
@@ -0,0 +1,2 @@
1
+ import type { ITimers } from "@vkontakte/videoplayer-shared";
2
+ export declare const timers: ITimers;
@@ -2,10 +2,9 @@ import type { VideoCodecName, VideoFormat } from "../player/types";
2
2
  import { WebmCodecStrategy } from "../enums/WebmCodecStrategy";
3
3
  import { AndroidPreferredFormat } from "../enums/AndroidPreferredFormat";
4
4
  import { IOSPreferredFormat } from "../enums/IOSPreferredFormat";
5
- import type { Byte, Kbps, Milliseconds, RecursivePartial, Seconds } from "@vkontakte/videoplayer-shared";
5
+ import type { Byte, Kbps, Milliseconds, RecursivePartial, Seconds, TimerModule } from "@vkontakte/videoplayer-shared";
6
6
  import { type ExactVideoQuality, VideoQuality } from "@vkontakte/videoplayer-shared";
7
7
  import { AudioRuleName, VideoRuleName } from "../providers/utils/Abr/types";
8
- import type { SegmentCacheConfig } from "../providers/utils/segmentCache/types";
9
8
  export type ITuningConfig = {
10
9
  /** @deprecated */
11
10
  configName?: string[];
@@ -19,6 +18,7 @@ export type ITuningConfig = {
19
18
  * Включает очистку состояния плеера при вызове метода stop()
20
19
  */
21
20
  allowPlayerReuse: boolean;
21
+ useWorkerTimers: TimerModule[];
22
22
  throughputEstimator: {
23
23
  type: "TwoEma" | "EmaAndMa";
24
24
  emaAlphaSlow: number;
@@ -147,7 +147,6 @@ export type ITuningConfig = {
147
147
  forwardBufferTargetManual: Milliseconds;
148
148
  forwardBufferTargetPreload: Milliseconds;
149
149
  audioBufferAheadOfVideoMs: Milliseconds;
150
- useDynamicBufferTarget: boolean;
151
150
  seekBiasInTheEnd: Milliseconds;
152
151
  maxSegmentDurationLeftToSelectNextSegment: Milliseconds;
153
152
  minSafeBufferThreshold: number;
@@ -176,7 +175,6 @@ export type ITuningConfig = {
176
175
  vktvAbrThrottle: number;
177
176
  timeupdateEventTickThrottle: number;
178
177
  fetcherBufferOptimisation: boolean;
179
- codecsPrioritizeEnabled: boolean;
180
178
  usePersistentGaps: boolean;
181
179
  abrThrottle: number;
182
180
  useVideoElementWaitingCurrentTimeReassign: boolean;
@@ -223,26 +221,14 @@ export type ITuningConfig = {
223
221
  budgetFactor: number;
224
222
  fallbackSegmentDurationMs: Milliseconds;
225
223
  };
226
- dynamicBufferTarget: {
227
- maxMs: Milliseconds;
228
- optimisticHeadroomLow: number;
229
- optimisticHeadroomHigh: number;
230
- weakThroughputLowKbps: Kbps;
231
- weakThroughputHighKbps: Kbps;
232
- maxFactor: number;
233
- };
234
224
  videoStreamRepresentaionsFilter: [VideoQuality, number, VideoCodecName][];
235
225
  filterOnDemandQualityList: boolean;
236
226
  dashMaxTvVideoQuality: boolean;
237
227
  checkRepresentationCanPlayType: Extract<CanPlayTypeResult, "maybe" | "probably"> | false;
238
228
  preloadFirstSegment: boolean;
239
229
  maxQualityForFirstSegmentPreload: ExactVideoQuality;
240
- downloadTime: {
241
- minLookaheadSegments: number;
242
- safetyFactor: number;
243
- bootstrapBufferMs: Milliseconds;
244
- demandTolerance: number;
245
- };
230
+ /** Включает отправку телеметрии трейсера (resume) при превышении stall watchdog */
231
+ tracerResumeOnUnexpectedStall: boolean;
246
232
  };
247
233
  dashCmafLive: {
248
234
  externalStopControl: boolean;
@@ -416,6 +402,15 @@ export type ITuningConfig = {
416
402
  */
417
403
  handleExtendedNetworkErrorsSet?: boolean;
418
404
  /**
405
+ * Кэшируем ответы от сервера руками, так как из за динамичесокй природы некоторых параметров в урле
406
+ * браузер это не может сделать.
407
+ */
408
+ useUrlCacheMechanism?: boolean;
409
+ /**
410
+ * Очищаем кэш урлов при падение провайдера.
411
+ */
412
+ dropUrlCacheWhenProviderCrashed?: boolean;
413
+ /**
419
414
  * При смене/реините провайдера игнорируем результат того, смогло видео заиграть или нет.
420
415
  */
421
416
  ignoreForcePlayResultWhenProviderChanged?: boolean;
@@ -438,7 +433,6 @@ export type ITuningConfig = {
438
433
  * провайдер по-прежнему ждёт canplay, чтобы play() не вызывался до появления данных.
439
434
  */
440
435
  readyOnLoadedMetadata: boolean;
441
- segmentCache: SegmentCacheConfig;
442
436
  };
443
437
  export type IOptionalTuningConfig = RecursivePartial<ITuningConfig>;
444
438
  export declare const fillDefault: (partial: IOptionalTuningConfig) => ITuningConfig;
@@ -1,15 +0,0 @@
1
- import type { IAbrRule, IAbrRuleResolution, IVideoAbrContext } from "../../types";
2
- import type { IVideoTrack } from "../../../../../player/types";
3
- import type { Kbps, Milliseconds } from "@vkontakte/videoplayer-shared";
4
- import { LimitAboveRule } from "../limitAboveRule";
5
- import type { RulePhaseConfig } from "../../controllers/abrPhaseController";
6
- type DownloadTimeLogsArgs = [estimatedThroughput: Kbps, forwardBufferDuration: Milliseconds, simulatedFinalBufferMs: Milliseconds | null];
7
- export declare class DownloadTimeRule extends LimitAboveRule<IVideoTrack, IVideoAbrContext, DownloadTimeLogsArgs> implements IAbrRule<IVideoTrack, IVideoAbrContext> {
8
- constructor(phaseConfig: RulePhaseConfig);
9
- execute(context: IVideoAbrContext): IAbrRuleResolution<IVideoTrack>;
10
- private buildReferenceTimeline;
11
- private resolveLookaheadCount;
12
- private simulate;
13
- protected createLogMessage(selectedTrack: IVideoTrack, estimatedThroughput: Kbps, forwardBufferDuration: Milliseconds, simulatedFinalBufferMs: Milliseconds | null): string;
14
- }
15
- export {};
@@ -1,52 +0,0 @@
1
- import type { InitSegmentParams, ISegmentCacheStorage, SegmentCacheConfig, SetSegmentParams } from "./types";
2
- export declare class IndexedDbSegmentCacheStorage implements ISegmentCacheStorage {
3
- private config;
4
- private dbPromise;
5
- private destroyed;
6
- private evictionTimerId;
7
- private globalTotalBytes;
8
- private maxTotalStoredBytes;
9
- private quotaExceeded;
10
- private cacheEventsChannel;
11
- constructor(config: SegmentCacheConfig);
12
- private getDb;
13
- private isFresh;
14
- /**
15
- * Читает записи по массиву ключей в одной транзакции.
16
- * Свежие по TTL — возвращает данные и обновляет lastAccessAt (не чаще чем раз в TOUCH_INTERVAL_MS,
17
- * чтобы избежать write amplification: каждый cache hit не должен делать store.put с полным ArrayBuffer).
18
- * Протухшие — удаляет, декрементирует globalTotalBytes.
19
- */
20
- private readFreshRecord;
21
- /**
22
- * При открытии БД пересчитывает globalTotalBytes: проходит по всем записям,
23
- * суммирует размер живых (не протухших по TTL) и удаляет протухшие.
24
- * TTL различается: media — ttlMs, init/index — initTtlMs.
25
- */
26
- private handleDbOpened;
27
- /** Возвращает TTL в зависимости от типа записи по первичному ключу. */
28
- private ttlForEntry;
29
- getSegments(normalizedUrl: string, indices: number[]): Promise<Map<number, ArrayBuffer>>;
30
- setSegment(params: SetSegmentParams): Promise<void>;
31
- getInitSegment({ normalizedUrl, rangeType, range }: InitSegmentParams): Promise<ArrayBuffer | null>;
32
- /** Универсальная запись с подсчётом delta, QuotaExceededError-обработкой и eviction. */
33
- private putRecord;
34
- private handleQuotaExceededError;
35
- /** Полная очистка кэша с рассылкой события остальным инстансам (вкладки, другие плееры). */
36
- clear(): Promise<void>;
37
- destroy(): void;
38
- private scheduleEviction;
39
- /**
40
- * LRU-eviction: запускается по дебаунсу после каждой записи.
41
- * Без квоты — триггерит при достижении maxTotalStoredBytes.
42
- * После QuotaExceededError — раньше, на maxTotalStoredBytes * evictionThreshold,
43
- * чтобы не упереться в квоту повторно.
44
- * Очищает с запасом — до maxTotalStoredBytes * evictionTargetPercent.
45
- */
46
- private runEviction;
47
- /**
48
- * Удаляет самые старые по lastAccessAt записи, пока не освободит хотя бы bytesToFree.
49
- * maxBytesPerBatch ограничивает длительность одной транзакции; без лимита — при QuotaExceededError.
50
- */
51
- private evictOldest;
52
- }
@@ -1,40 +0,0 @@
1
- import type { ISegmentCacheStorage, CacheMetadata, CacheMetadataEntry } from "./types";
2
- import type { SubRange } from "./segmentCacheUtils";
3
- export declare enum CacheCheckResultType {
4
- FullHit = "full_hit",
5
- FullMiss = "full_miss",
6
- Partial = "partial"
7
- }
8
- export type CacheCheckResult = {
9
- type: CacheCheckResultType.FullHit;
10
- data: ArrayBuffer;
11
- } | {
12
- type: CacheCheckResultType.FullMiss;
13
- } | {
14
- type: CacheCheckResultType.Partial;
15
- cached: Map<number, ArrayBuffer>;
16
- missingRange: SubRange;
17
- startBuffer: {
18
- buffer: ArrayBuffer;
19
- loaded: number;
20
- } | null;
21
- };
22
- export declare class SegmentCache {
23
- private cacheService;
24
- constructor(cacheService: ISegmentCacheStorage);
25
- getCached(url: string, metadata: CacheMetadata): Promise<CacheCheckResult>;
26
- storeDownloadedSegments({ url, buffer, segments, networkDataOffset }: {
27
- url: string;
28
- buffer: ArrayBuffer;
29
- segments: CacheMetadataEntry[];
30
- networkDataOffset?: number;
31
- }): void;
32
- private assembleStartBuffer;
33
- private buildPartialFromCacheStart;
34
- storeMissing({ url, missingRange, networkData, networkDataOffset }: {
35
- url: string;
36
- missingRange: SubRange;
37
- networkData: ArrayBuffer;
38
- networkDataOffset?: number;
39
- }): void;
40
- }
@@ -1,20 +0,0 @@
1
- export declare const DB_NAME = "vk_player_segment_cache";
2
- export declare const DB_VERSION = 1;
3
- export declare const STORE = "cache";
4
- export declare const EVICTION_DEBOUNCE_MS = 5e3;
5
- /** Канал синхронизации инстансов storage (вкладки, несколько плееров на странице) */
6
- export declare const CACHE_EVENTS_CHANNEL = "vk_player_segment_cache_events";
7
- /** Событие полной очистки кэша: получатель сбрасывает in-memory счётчик байт, база уже пуста */
8
- export declare const CACHE_CLEARED_EVENT = "cleared";
9
- /**
10
- * Минимальный интервал между обновлениями lastAccessAt при чтении.
11
- * Без него каждый cache hit делал бы store.put с полным ArrayBuffer ради одного поля.
12
- * При TTL в часы точность LRU до минут не нужна — 5 минут достаточно.
13
- */
14
- export declare const TOUCH_INTERVAL_MS: number;
15
- /** Тип записи: media-сегмент, init-сегмент, index-сегмент */
16
- export declare enum CacheEntryType {
17
- Media = 0,
18
- Init = 1,
19
- Index = 2
20
- }
@@ -1,8 +0,0 @@
1
- export { IndexedDbSegmentCacheStorage } from "./IndexedDbSegmentCacheStorage";
2
- export { SegmentCache, CacheCheckResultType } from "./SegmentCache";
3
- export type { CacheCheckResult } from "./SegmentCache";
4
- export { normalizeSegmentCacheUrl, assemblePartialBuffer, toEntryType, createMediaKey, createInitKey, isQuotaExceededError } from "./segmentCacheUtils";
5
- export type { SubRange } from "./segmentCacheUtils";
6
- export { clearSegmentCacheDb } from "./segmentCacheDb";
7
- export { DB_NAME, DB_VERSION, STORE, EVICTION_DEBOUNCE_MS, CacheEntryType } from "./constants";
8
- export type { ISegmentCacheStorage, CacheMetadata, CacheMetadataEntry, SegmentCacheConfig, SegmentCacheEntry, InitSegmentParams, InitSegmentRangeType, SetMediaSegmentParams, SetInitSegmentParams, SetSegmentParams, CacheRecord, CachePrimaryKey } from "./types";
@@ -1,25 +0,0 @@
1
- export declare const INDEX_BY_LAST_ACCESS = "byLastAccess";
2
- export declare const INDEX_BY_SIZE_AND_AGE = "bySizeAndAge";
3
- export declare const INDEX_BY_LAST_ACCESS_AND_SIZE = "byLastAccessAndSize";
4
- /**
5
- * Открывает базу кэша, при первом создании поднимает store и индексы.
6
- * onOpened (если передан) await-ится до resolve — используется только в clearSegmentCacheDb.
7
- * Инстанс storage не использует onOpened: rehydrate запускается параллельно, чтобы не блокировать чтения.
8
- */
9
- export declare const openSegmentCacheDb: (onOpened?: (db: IDBDatabase) => Promise<void>) => Promise<IDBDatabase>;
10
- /** Выполняет операции в одной readwrite-транзакции, резолвится по её завершении. */
11
- export declare const execStoreTx: (db: IDBDatabase, body: (store: IDBObjectStore) => void) => Promise<void>;
12
- /**
13
- * Гоняет курсор по индексу, вызывая visit на каждой записи.
14
- * visit возвращает false — итерация останавливается, транзакция завершается.
15
- * Работает только внутри execStoreTx: завершение итерации отслеживается транзакцией.
16
- */
17
- export declare const iterateCursor: <T extends IDBCursor>(request: IDBRequest<T | null>, visit: (cursor: T) => boolean) => void;
18
- /** Рассылает событие полной очистки кэша всем инстансам storage (вкладки, другие плееры на странице). */
19
- export declare const broadcastCacheCleared: () => void;
20
- /**
21
- * Полностью очищает кэш без привязки к инстансу storage: можно звать из мест,
22
- * где экземпляр IndexedDbSegmentCacheStorage недоступен (например, из ProviderContainer при ошибках).
23
- * Живые инстансы узнают об очистке через broadcastCacheCleared и сбросят in-memory счётчики.
24
- */
25
- export declare const clearSegmentCacheDb: () => Promise<void>;