Home Reference Source

src/controller/base-stream-controller.ts

  1. import TaskLoop from '../task-loop';
  2. import { FragmentState } from './fragment-tracker';
  3. import { Bufferable, BufferHelper } from '../utils/buffer-helper';
  4. import { logger } from '../utils/logger';
  5. import { Events } from '../events';
  6. import { ErrorDetails } from '../errors';
  7. import { ChunkMetadata } from '../types/transmuxer';
  8. import { appendUint8Array } from '../utils/mp4-tools';
  9. import { alignStream } from '../utils/discontinuities';
  10. import {
  11. findFragmentByPDT,
  12. findFragmentByPTS,
  13. findFragWithCC,
  14. } from './fragment-finders';
  15. import {
  16. getFragmentWithSN,
  17. getPartWith,
  18. updateFragPTSDTS,
  19. } from './level-helper';
  20. import TransmuxerInterface from '../demux/transmuxer-interface';
  21. import { Fragment, Part } from '../loader/fragment';
  22. import FragmentLoader, {
  23. FragmentLoadProgressCallback,
  24. LoadError,
  25. } from '../loader/fragment-loader';
  26. import { LevelDetails } from '../loader/level-details';
  27. import {
  28. BufferAppendingData,
  29. ErrorData,
  30. FragLoadedData,
  31. PartsLoadedData,
  32. KeyLoadedData,
  33. MediaAttachingData,
  34. BufferFlushingData,
  35. } from '../types/events';
  36. import Decrypter from '../crypt/decrypter';
  37. import TimeRanges from '../utils/time-ranges';
  38. import { PlaylistLevelType } from '../types/loader';
  39. import type { FragmentTracker } from './fragment-tracker';
  40. import type { Level } from '../types/level';
  41. import type { RemuxedTrack } from '../types/remuxer';
  42. import type Hls from '../hls';
  43. import type { HlsConfig } from '../config';
  44. import type { HlsEventEmitter } from '../events';
  45. import type { NetworkComponentAPI } from '../types/component-api';
  46. import type { SourceBufferName } from '../types/buffer';
  47.  
  48. type ResolveFragLoaded = (FragLoadedEndData) => void;
  49. type RejectFragLoaded = (LoadError) => void;
  50.  
  51. export const State = {
  52. STOPPED: 'STOPPED',
  53. IDLE: 'IDLE',
  54. KEY_LOADING: 'KEY_LOADING',
  55. FRAG_LOADING: 'FRAG_LOADING',
  56. FRAG_LOADING_WAITING_RETRY: 'FRAG_LOADING_WAITING_RETRY',
  57. WAITING_TRACK: 'WAITING_TRACK',
  58. PARSING: 'PARSING',
  59. PARSED: 'PARSED',
  60. BACKTRACKING: 'BACKTRACKING',
  61. ENDED: 'ENDED',
  62. ERROR: 'ERROR',
  63. WAITING_INIT_PTS: 'WAITING_INIT_PTS',
  64. WAITING_LEVEL: 'WAITING_LEVEL',
  65. };
  66.  
  67. export default class BaseStreamController
  68. extends TaskLoop
  69. implements NetworkComponentAPI
  70. {
  71. protected hls: Hls;
  72.  
  73. protected fragPrevious: Fragment | null = null;
  74. protected fragCurrent: Fragment | null = null;
  75. protected fragmentTracker: FragmentTracker;
  76. protected transmuxer: TransmuxerInterface | null = null;
  77. protected _state: string = State.STOPPED;
  78. protected media?: any;
  79. protected mediaBuffer?: any;
  80. protected config: HlsConfig;
  81. protected bitrateTest: boolean = false;
  82. protected lastCurrentTime: number = 0;
  83. protected nextLoadPosition: number = 0;
  84. protected startPosition: number = 0;
  85. protected loadedmetadata: boolean = false;
  86. protected fragLoadError: number = 0;
  87. protected retryDate: number = 0;
  88. protected levels: Array<Level> | null = null;
  89. protected fragmentLoader!: FragmentLoader;
  90. protected levelLastLoaded: number | null = null;
  91. protected startFragRequested: boolean = false;
  92. protected decrypter: Decrypter;
  93. protected initPTS: Array<number> = [];
  94. protected onvseeking: EventListener | null = null;
  95. protected onvended: EventListener | null = null;
  96.  
  97. private readonly logPrefix: string = '';
  98. protected log: (msg: any) => void;
  99. protected warn: (msg: any) => void;
  100.  
  101. constructor(hls: Hls, fragmentTracker: FragmentTracker, logPrefix: string) {
  102. super();
  103. this.logPrefix = logPrefix;
  104. this.log = logger.log.bind(logger, `${logPrefix}:`);
  105. this.warn = logger.warn.bind(logger, `${logPrefix}:`);
  106. this.hls = hls;
  107. this.fragmentLoader = new FragmentLoader(hls.config);
  108. this.fragmentTracker = fragmentTracker;
  109. this.config = hls.config;
  110. this.decrypter = new Decrypter(hls as HlsEventEmitter, hls.config);
  111. hls.on(Events.KEY_LOADED, this.onKeyLoaded, this);
  112. }
  113.  
  114. protected doTick() {
  115. this.onTickEnd();
  116. }
  117.  
  118. protected onTickEnd() {}
  119.  
  120. // eslint-disable-next-line @typescript-eslint/no-unused-vars
  121. public startLoad(startPosition: number): void {}
  122.  
  123. public stopLoad() {
  124. this.fragmentLoader.abort();
  125. const frag = this.fragCurrent;
  126. if (frag) {
  127. this.fragmentTracker.removeFragment(frag);
  128. }
  129. this.resetTransmuxer();
  130. this.fragCurrent = null;
  131. this.fragPrevious = null;
  132. this.clearInterval();
  133. this.clearNextTick();
  134. this.state = State.STOPPED;
  135. }
  136.  
  137. protected _streamEnded(bufferInfo, levelDetails: LevelDetails) {
  138. const { fragCurrent, fragmentTracker } = this;
  139. // we just got done loading the final fragment and there is no other buffered range after ...
  140. // rationale is that in case there are any buffered ranges after, it means that there are unbuffered portion in between
  141. // so we should not switch to ENDED in that case, to be able to buffer them
  142. if (
  143. !levelDetails.live &&
  144. fragCurrent &&
  145. // NOTE: Because of the way parts are currently parsed/represented in the playlist, we can end up
  146. // in situations where the current fragment is actually greater than levelDetails.endSN. While
  147. // this feels like the "wrong place" to account for that, this is a narrower/safer change than
  148. // updating e.g. M3U8Parser::parseLevelPlaylist().
  149. fragCurrent.sn >= levelDetails.endSN &&
  150. !bufferInfo.nextStart
  151. ) {
  152. const partList = levelDetails.partList;
  153. // Since the last part isn't guaranteed to correspond to fragCurrent for ll-hls, check instead if the last part is buffered.
  154. if (partList?.length) {
  155. const lastPart = partList[partList.length - 1];
  156.  
  157. // Checking the midpoint of the part for potential margin of error and related issues.
  158. // NOTE: Technically I believe parts could yield content that is < the computed duration (including potential a duration of 0)
  159. // and still be spec-compliant, so there may still be edge cases here. Likewise, there could be issues in end of stream
  160. // part mismatches for independent audio and video playlists/segments.
  161. const lastPartBuffered = BufferHelper.isBuffered(
  162. this.media,
  163. lastPart.start + lastPart.duration / 2
  164. );
  165. return lastPartBuffered;
  166. }
  167. const fragState = fragmentTracker.getState(fragCurrent);
  168. return (
  169. fragState === FragmentState.PARTIAL || fragState === FragmentState.OK
  170. );
  171. }
  172. return false;
  173. }
  174.  
  175. protected onMediaAttached(
  176. event: Events.MEDIA_ATTACHED,
  177. data: MediaAttachingData
  178. ) {
  179. const media = (this.media = this.mediaBuffer = data.media);
  180. this.onvseeking = this.onMediaSeeking.bind(this);
  181. this.onvended = this.onMediaEnded.bind(this);
  182. media.addEventListener('seeking', this.onvseeking as EventListener);
  183. media.addEventListener('ended', this.onvended as EventListener);
  184. const config = this.config;
  185. if (this.levels && config.autoStartLoad && this.state === State.STOPPED) {
  186. this.startLoad(config.startPosition);
  187. }
  188. }
  189.  
  190. protected onMediaDetaching() {
  191. const media = this.media;
  192. if (media?.ended) {
  193. this.log('MSE detaching and video ended, reset startPosition');
  194. this.startPosition = this.lastCurrentTime = 0;
  195. }
  196.  
  197. // remove video listeners
  198. if (media) {
  199. media.removeEventListener('seeking', this.onvseeking);
  200. media.removeEventListener('ended', this.onvended);
  201. this.onvseeking = this.onvended = null;
  202. }
  203. this.media = this.mediaBuffer = null;
  204. this.loadedmetadata = false;
  205. this.fragmentTracker.removeAllFragments();
  206. this.stopLoad();
  207. }
  208.  
  209. protected onMediaSeeking() {
  210. const { config, fragCurrent, media, mediaBuffer, state } = this;
  211. const currentTime: number = media ? media.currentTime : 0;
  212. const bufferInfo = BufferHelper.bufferInfo(
  213. mediaBuffer || media,
  214. currentTime,
  215. config.maxBufferHole
  216. );
  217.  
  218. this.log(
  219. `media seeking to ${
  220. Number.isFinite(currentTime) ? currentTime.toFixed(3) : currentTime
  221. }, state: ${state}`
  222. );
  223.  
  224. if (state === State.ENDED) {
  225. this.resetLoadingState();
  226. } else if (fragCurrent && !bufferInfo.len) {
  227. // check if we are seeking to a unbuffered area AND if frag loading is in progress
  228. const tolerance = config.maxFragLookUpTolerance;
  229. const fragStartOffset = fragCurrent.start - tolerance;
  230. const fragEndOffset =
  231. fragCurrent.start + fragCurrent.duration + tolerance;
  232. const pastFragment = currentTime > fragEndOffset;
  233. // check if the seek position is past current fragment, and if so abort loading
  234. if (currentTime < fragStartOffset || pastFragment) {
  235. if (pastFragment && fragCurrent.loader) {
  236. this.log(
  237. 'seeking outside of buffer while fragment load in progress, cancel fragment load'
  238. );
  239. fragCurrent.loader.abort();
  240. }
  241. this.resetLoadingState();
  242. }
  243. }
  244.  
  245. if (media) {
  246. this.lastCurrentTime = currentTime;
  247. }
  248.  
  249. // in case seeking occurs although no media buffered, adjust startPosition and nextLoadPosition to seek target
  250. if (!this.loadedmetadata && !bufferInfo.len) {
  251. this.nextLoadPosition = this.startPosition = currentTime;
  252. }
  253.  
  254. // Async tick to speed up processing
  255. this.tickImmediate();
  256. }
  257.  
  258. protected onMediaEnded() {
  259. // reset startPosition and lastCurrentTime to restart playback @ stream beginning
  260. this.startPosition = this.lastCurrentTime = 0;
  261. }
  262.  
  263. onKeyLoaded(event: Events.KEY_LOADED, data: KeyLoadedData) {
  264. if (
  265. this.state !== State.KEY_LOADING ||
  266. data.frag !== this.fragCurrent ||
  267. !this.levels
  268. ) {
  269. return;
  270. }
  271. this.state = State.IDLE;
  272. const levelDetails = this.levels[data.frag.level].details;
  273. if (levelDetails) {
  274. this.loadFragment(data.frag, levelDetails, data.frag.start);
  275. }
  276. }
  277.  
  278. protected onHandlerDestroying() {
  279. this.stopLoad();
  280. super.onHandlerDestroying();
  281. }
  282.  
  283. protected onHandlerDestroyed() {
  284. this.state = State.STOPPED;
  285. this.hls.off(Events.KEY_LOADED, this.onKeyLoaded, this);
  286. if (this.fragmentLoader) {
  287. this.fragmentLoader.destroy();
  288. }
  289. if (this.decrypter) {
  290. this.decrypter.destroy();
  291. }
  292.  
  293. this.hls =
  294. this.log =
  295. this.warn =
  296. this.decrypter =
  297. this.fragmentLoader =
  298. this.fragmentTracker =
  299. null as any;
  300. super.onHandlerDestroyed();
  301. }
  302.  
  303. protected loadKey(frag: Fragment, details: LevelDetails) {
  304. this.log(
  305. `Loading key for ${frag.sn} of [${details.startSN}-${details.endSN}], ${
  306. this.logPrefix === '[stream-controller]' ? 'level' : 'track'
  307. } ${frag.level}`
  308. );
  309. this.state = State.KEY_LOADING;
  310. this.fragCurrent = frag;
  311. this.hls.trigger(Events.KEY_LOADING, { frag });
  312. }
  313.  
  314. protected loadFragment(
  315. frag: Fragment,
  316. levelDetails: LevelDetails,
  317. targetBufferTime: number
  318. ) {
  319. this._loadFragForPlayback(frag, levelDetails, targetBufferTime);
  320. }
  321.  
  322. private _loadFragForPlayback(
  323. frag: Fragment,
  324. levelDetails: LevelDetails,
  325. targetBufferTime: number
  326. ) {
  327. const progressCallback: FragmentLoadProgressCallback = (
  328. data: FragLoadedData
  329. ) => {
  330. if (this.fragContextChanged(frag)) {
  331. this.warn(
  332. `Fragment ${frag.sn}${
  333. data.part ? ' p: ' + data.part.index : ''
  334. } of level ${frag.level} was dropped during download.`
  335. );
  336. this.fragmentTracker.removeFragment(frag);
  337. return;
  338. }
  339. frag.stats.chunkCount++;
  340. this._handleFragmentLoadProgress(data);
  341. };
  342.  
  343. this._doFragLoad(frag, levelDetails, targetBufferTime, progressCallback)
  344. .then((data) => {
  345. if (!data) {
  346. // if we're here we probably needed to backtrack or are waiting for more parts
  347. return;
  348. }
  349. this.fragLoadError = 0;
  350. const state = this.state;
  351. if (this.fragContextChanged(frag)) {
  352. if (
  353. state === State.FRAG_LOADING ||
  354. state === State.BACKTRACKING ||
  355. (!this.fragCurrent && state === State.PARSING)
  356. ) {
  357. this.fragmentTracker.removeFragment(frag);
  358. this.state = State.IDLE;
  359. }
  360. return;
  361. }
  362.  
  363. if ('payload' in data) {
  364. this.log(`Loaded fragment ${frag.sn} of level ${frag.level}`);
  365. this.hls.trigger(Events.FRAG_LOADED, data);
  366.  
  367. // Tracker backtrack must be called after onFragLoaded to update the fragment entity state to BACKTRACKED
  368. // This happens after handleTransmuxComplete when the worker or progressive is disabled
  369. if (this.state === State.BACKTRACKING) {
  370. this.fragmentTracker.backtrack(frag, data);
  371. this.resetFragmentLoading(frag);
  372. return;
  373. }
  374. }
  375.  
  376. // Pass through the whole payload; controllers not implementing progressive loading receive data from this callback
  377. this._handleFragmentLoadComplete(data);
  378. })
  379. .catch((reason) => {
  380. this.warn(reason);
  381. this.resetFragmentLoading(frag);
  382. });
  383. }
  384.  
  385. protected flushMainBuffer(
  386. startOffset: number,
  387. endOffset: number,
  388. type: SourceBufferName | null = null
  389. ) {
  390. if (!(startOffset - endOffset)) {
  391. return;
  392. }
  393. // When alternate audio is playing, the audio-stream-controller is responsible for the audio buffer. Otherwise,
  394. // passing a null type flushes both buffers
  395. const flushScope: BufferFlushingData = { startOffset, endOffset, type };
  396. // Reset load errors on flush
  397. this.fragLoadError = 0;
  398. this.hls.trigger(Events.BUFFER_FLUSHING, flushScope);
  399. }
  400.  
  401. protected _loadInitSegment(frag: Fragment) {
  402. this._doFragLoad(frag)
  403. .then((data) => {
  404. if (!data || this.fragContextChanged(frag) || !this.levels) {
  405. throw new Error('init load aborted');
  406. }
  407.  
  408. return data;
  409. })
  410. .then((data: FragLoadedData) => {
  411. const { hls } = this;
  412. const { payload } = data;
  413. const decryptData = frag.decryptdata;
  414.  
  415. // check to see if the payload needs to be decrypted
  416. if (
  417. payload &&
  418. payload.byteLength > 0 &&
  419. decryptData &&
  420. decryptData.key &&
  421. decryptData.iv &&
  422. decryptData.method === 'AES-128'
  423. ) {
  424. const startTime = self.performance.now();
  425. // decrypt the subtitles
  426. return this.decrypter
  427. .webCryptoDecrypt(
  428. new Uint8Array(payload),
  429. decryptData.key.buffer,
  430. decryptData.iv.buffer
  431. )
  432. .then((decryptedData) => {
  433. const endTime = self.performance.now();
  434. hls.trigger(Events.FRAG_DECRYPTED, {
  435. frag,
  436. payload: decryptedData,
  437. stats: {
  438. tstart: startTime,
  439. tdecrypt: endTime,
  440. },
  441. });
  442. data.payload = decryptedData;
  443.  
  444. return data;
  445. });
  446. }
  447.  
  448. return data;
  449. })
  450. .then((data: FragLoadedData) => {
  451. const { fragCurrent, hls, levels } = this;
  452. if (!levels) {
  453. throw new Error('init load aborted, missing levels');
  454. }
  455.  
  456. const details = levels[frag.level].details as LevelDetails;
  457. console.assert(
  458. details,
  459. 'Level details are defined when init segment is loaded'
  460. );
  461.  
  462. const stats = frag.stats;
  463. this.state = State.IDLE;
  464. this.fragLoadError = 0;
  465. frag.data = new Uint8Array(data.payload);
  466. stats.parsing.start = stats.buffering.start = self.performance.now();
  467. stats.parsing.end = stats.buffering.end = self.performance.now();
  468.  
  469. // Silence FRAG_BUFFERED event if fragCurrent is null
  470. if (data.frag === fragCurrent) {
  471. hls.trigger(Events.FRAG_BUFFERED, {
  472. stats,
  473. frag: fragCurrent,
  474. part: null,
  475. id: frag.type,
  476. });
  477. }
  478. this.tick();
  479. })
  480. .catch((reason) => {
  481. this.warn(reason);
  482. this.resetFragmentLoading(frag);
  483. });
  484. }
  485.  
  486. protected fragContextChanged(frag: Fragment | null) {
  487. const { fragCurrent } = this;
  488. return (
  489. !frag ||
  490. !fragCurrent ||
  491. frag.level !== fragCurrent.level ||
  492. frag.sn !== fragCurrent.sn ||
  493. frag.urlId !== fragCurrent.urlId
  494. );
  495. }
  496.  
  497. protected fragBufferedComplete(frag: Fragment, part: Part | null) {
  498. const media = this.mediaBuffer ? this.mediaBuffer : this.media;
  499. this.log(
  500. `Buffered ${frag.type} sn: ${frag.sn}${
  501. part ? ' part: ' + part.index : ''
  502. } of ${this.logPrefix === '[stream-controller]' ? 'level' : 'track'} ${
  503. frag.level
  504. } ${TimeRanges.toString(BufferHelper.getBuffered(media))}`
  505. );
  506. this.state = State.IDLE;
  507. this.tick();
  508. }
  509.  
  510. protected _handleFragmentLoadComplete(fragLoadedEndData: PartsLoadedData) {
  511. const { transmuxer } = this;
  512. if (!transmuxer) {
  513. return;
  514. }
  515. const { frag, part, partsLoaded } = fragLoadedEndData;
  516. // If we did not load parts, or loaded all parts, we have complete (not partial) fragment data
  517. const complete =
  518. !partsLoaded ||
  519. partsLoaded.length === 0 ||
  520. partsLoaded.some((fragLoaded) => !fragLoaded);
  521. const chunkMeta = new ChunkMetadata(
  522. frag.level,
  523. frag.sn as number,
  524. frag.stats.chunkCount + 1,
  525. 0,
  526. part ? part.index : -1,
  527. !complete
  528. );
  529. transmuxer.flush(chunkMeta);
  530. }
  531.  
  532. // eslint-disable-next-line @typescript-eslint/no-unused-vars
  533. protected _handleFragmentLoadProgress(frag: FragLoadedData) {}
  534.  
  535. protected _doFragLoad(
  536. frag: Fragment,
  537. details?: LevelDetails,
  538. targetBufferTime: number | null = null,
  539. progressCallback?: FragmentLoadProgressCallback
  540. ): Promise<PartsLoadedData | FragLoadedData | null> {
  541. if (!this.levels) {
  542. throw new Error('frag load aborted, missing levels');
  543. }
  544. targetBufferTime = Math.max(frag.start, targetBufferTime || 0);
  545. if (this.config.lowLatencyMode && details) {
  546. const partList = details.partList;
  547. if (partList && progressCallback) {
  548. if (targetBufferTime > frag.end && details.fragmentHint) {
  549. frag = details.fragmentHint;
  550. }
  551. const partIndex = this.getNextPart(partList, frag, targetBufferTime);
  552. if (partIndex > -1) {
  553. const part = partList[partIndex];
  554. this.log(
  555. `Loading part sn: ${frag.sn} p: ${part.index} cc: ${
  556. frag.cc
  557. } of playlist [${details.startSN}-${
  558. details.endSN
  559. }] parts [0-${partIndex}-${partList.length - 1}] ${
  560. this.logPrefix === '[stream-controller]' ? 'level' : 'track'
  561. }: ${frag.level}, target: ${parseFloat(
  562. targetBufferTime.toFixed(3)
  563. )}`
  564. );
  565. this.nextLoadPosition = part.start + part.duration;
  566. this.state = State.FRAG_LOADING;
  567. this.hls.trigger(Events.FRAG_LOADING, {
  568. frag,
  569. part: partList[partIndex],
  570. targetBufferTime,
  571. });
  572. return this.doFragPartsLoad(
  573. frag,
  574. partList,
  575. partIndex,
  576. progressCallback
  577. ).catch((error: LoadError) => this.handleFragLoadError(error));
  578. } else if (
  579. !frag.url ||
  580. this.loadedEndOfParts(partList, targetBufferTime)
  581. ) {
  582. // Fragment hint has no parts
  583. return Promise.resolve(null);
  584. }
  585. }
  586. }
  587.  
  588. this.log(
  589. `Loading fragment ${frag.sn} cc: ${frag.cc} ${
  590. details ? 'of [' + details.startSN + '-' + details.endSN + '] ' : ''
  591. }${this.logPrefix === '[stream-controller]' ? 'level' : 'track'}: ${
  592. frag.level
  593. }, target: ${parseFloat(targetBufferTime.toFixed(3))}`
  594. );
  595. // Don't update nextLoadPosition for fragments which are not buffered
  596. if (Number.isFinite(frag.sn as number) && !this.bitrateTest) {
  597. this.nextLoadPosition = frag.start + frag.duration;
  598. }
  599. this.state = State.FRAG_LOADING;
  600. this.hls.trigger(Events.FRAG_LOADING, { frag, targetBufferTime });
  601.  
  602. return this.fragmentLoader
  603. .load(frag, progressCallback)
  604. .catch((error: LoadError) => this.handleFragLoadError(error));
  605. }
  606.  
  607. private doFragPartsLoad(
  608. frag: Fragment,
  609. partList: Part[],
  610. partIndex: number,
  611. progressCallback: FragmentLoadProgressCallback
  612. ): Promise<PartsLoadedData | null> {
  613. return new Promise(
  614. (resolve: ResolveFragLoaded, reject: RejectFragLoaded) => {
  615. const partsLoaded: FragLoadedData[] = [];
  616. const loadPartIndex = (index: number) => {
  617. const part = partList[index];
  618. this.fragmentLoader
  619. .loadPart(frag, part, progressCallback)
  620. .then((partLoadedData: FragLoadedData) => {
  621. partsLoaded[part.index] = partLoadedData;
  622. const loadedPart = partLoadedData.part as Part;
  623. this.hls.trigger(Events.FRAG_LOADED, partLoadedData);
  624. const nextPart = partList[index + 1];
  625. if (nextPart && nextPart.fragment === frag) {
  626. loadPartIndex(index + 1);
  627. } else {
  628. return resolve({
  629. frag,
  630. part: loadedPart,
  631. partsLoaded,
  632. });
  633. }
  634. })
  635. .catch(reject);
  636. };
  637. loadPartIndex(partIndex);
  638. }
  639. );
  640. }
  641.  
  642. private handleFragLoadError({ data }: LoadError) {
  643. if (data && data.details === ErrorDetails.INTERNAL_ABORTED) {
  644. this.handleFragLoadAborted(data.frag, data.part);
  645. } else {
  646. this.hls.trigger(Events.ERROR, data as ErrorData);
  647. }
  648. return null;
  649. }
  650.  
  651. protected _handleTransmuxerFlush(chunkMeta: ChunkMetadata) {
  652. const context = this.getCurrentContext(chunkMeta);
  653. if (!context || this.state !== State.PARSING) {
  654. if (!this.fragCurrent) {
  655. this.state = State.IDLE;
  656. }
  657. return;
  658. }
  659. const { frag, part, level } = context;
  660. const now = self.performance.now();
  661. frag.stats.parsing.end = now;
  662. if (part) {
  663. part.stats.parsing.end = now;
  664. }
  665. this.updateLevelTiming(frag, part, level, chunkMeta.partial);
  666. }
  667.  
  668. protected getCurrentContext(
  669. chunkMeta: ChunkMetadata
  670. ): { frag: Fragment; part: Part | null; level: Level } | null {
  671. const { levels } = this;
  672. const { level: levelIndex, sn, part: partIndex } = chunkMeta;
  673. if (!levels || !levels[levelIndex]) {
  674. this.warn(
  675. `Levels object was unset while buffering fragment ${sn} of level ${levelIndex}. The current chunk will not be buffered.`
  676. );
  677. return null;
  678. }
  679. const level = levels[levelIndex];
  680. const part = partIndex > -1 ? getPartWith(level, sn, partIndex) : null;
  681. const frag = part
  682. ? part.fragment
  683. : getFragmentWithSN(level, sn, this.fragCurrent);
  684. if (!frag) {
  685. return null;
  686. }
  687. return { frag, part, level };
  688. }
  689.  
  690. protected bufferFragmentData(
  691. data: RemuxedTrack,
  692. frag: Fragment,
  693. part: Part | null,
  694. chunkMeta: ChunkMetadata
  695. ) {
  696. if (!data || this.state !== State.PARSING) {
  697. return;
  698. }
  699.  
  700. const { data1, data2 } = data;
  701. let buffer = data1;
  702. if (data1 && data2) {
  703. // Combine the moof + mdat so that we buffer with a single append
  704. buffer = appendUint8Array(data1, data2);
  705. }
  706.  
  707. if (!buffer || !buffer.length) {
  708. return;
  709. }
  710.  
  711. const segment: BufferAppendingData = {
  712. type: data.type,
  713. frag,
  714. part,
  715. chunkMeta,
  716. parent: frag.type,
  717. data: buffer,
  718. };
  719. this.hls.trigger(Events.BUFFER_APPENDING, segment);
  720.  
  721. if (data.dropped && data.independent && !part) {
  722. // Clear buffer so that we reload previous segments sequentially if required
  723. this.flushBufferGap(frag);
  724. }
  725. }
  726.  
  727. protected flushBufferGap(frag: Fragment) {
  728. const media = this.media;
  729. if (!media) {
  730. return;
  731. }
  732. // If currentTime is not buffered, clear the back buffer so that we can backtrack as much as needed
  733. if (!BufferHelper.isBuffered(media, media.currentTime)) {
  734. this.flushMainBuffer(0, frag.start);
  735. return;
  736. }
  737. // Remove back-buffer without interrupting playback to allow back tracking
  738. const currentTime = media.currentTime;
  739. const bufferInfo = BufferHelper.bufferInfo(media, currentTime, 0);
  740. const fragDuration = frag.duration;
  741. const segmentFraction = Math.min(
  742. this.config.maxFragLookUpTolerance * 2,
  743. fragDuration * 0.25
  744. );
  745. const start = Math.max(
  746. Math.min(frag.start - segmentFraction, bufferInfo.end - segmentFraction),
  747. currentTime + segmentFraction
  748. );
  749. if (frag.start - start > segmentFraction) {
  750. this.flushMainBuffer(start, frag.start);
  751. }
  752. }
  753.  
  754. protected getFwdBufferInfo(
  755. bufferable: Bufferable,
  756. type: PlaylistLevelType
  757. ): {
  758. len: number;
  759. start: number;
  760. end: number;
  761. nextStart?: number;
  762. } | null {
  763. const { config } = this;
  764. const pos = this.getLoadPosition();
  765. if (!Number.isFinite(pos)) {
  766. return null;
  767. }
  768. const bufferInfo = BufferHelper.bufferInfo(
  769. bufferable,
  770. pos,
  771. config.maxBufferHole
  772. );
  773. // Workaround flaw in getting forward buffer when maxBufferHole is smaller than gap at current pos
  774. if (bufferInfo.len === 0 && bufferInfo.nextStart !== undefined) {
  775. const bufferedFragAtPos = this.fragmentTracker.getBufferedFrag(pos, type);
  776. if (bufferedFragAtPos && bufferInfo.nextStart < bufferedFragAtPos.end) {
  777. return BufferHelper.bufferInfo(
  778. bufferable,
  779. pos,
  780. Math.max(bufferInfo.nextStart, config.maxBufferHole)
  781. );
  782. }
  783. }
  784. return bufferInfo;
  785. }
  786.  
  787. protected getMaxBufferLength(levelBitrate?: number): number {
  788. const { config } = this;
  789. let maxBufLen;
  790. if (levelBitrate) {
  791. maxBufLen = Math.max(
  792. (8 * config.maxBufferSize) / levelBitrate,
  793. config.maxBufferLength
  794. );
  795. } else {
  796. maxBufLen = config.maxBufferLength;
  797. }
  798. return Math.min(maxBufLen, config.maxMaxBufferLength);
  799. }
  800.  
  801. protected reduceMaxBufferLength(threshold?: number) {
  802. const config = this.config;
  803. const minLength = threshold || config.maxBufferLength;
  804. if (config.maxMaxBufferLength >= minLength) {
  805. // reduce max buffer length as it might be too high. we do this to avoid loop flushing ...
  806. config.maxMaxBufferLength /= 2;
  807. this.warn(`Reduce max buffer length to ${config.maxMaxBufferLength}s`);
  808. return true;
  809. }
  810. return false;
  811. }
  812.  
  813. protected getNextFragment(
  814. pos: number,
  815. levelDetails: LevelDetails
  816. ): Fragment | null {
  817. const fragments = levelDetails.fragments;
  818. const fragLen = fragments.length;
  819.  
  820. if (!fragLen) {
  821. return null;
  822. }
  823.  
  824. // find fragment index, contiguous with end of buffer position
  825. const { config } = this;
  826. const start = fragments[0].start;
  827. let frag;
  828.  
  829. if (levelDetails.live) {
  830. const initialLiveManifestSize = config.initialLiveManifestSize;
  831. if (fragLen < initialLiveManifestSize) {
  832. this.warn(
  833. `Not enough fragments to start playback (have: ${fragLen}, need: ${initialLiveManifestSize})`
  834. );
  835. return null;
  836. }
  837. // The real fragment start times for a live stream are only known after the PTS range for that level is known.
  838. // In order to discover the range, we load the best matching fragment for that level and demux it.
  839. // Do not load using live logic if the starting frag is requested - we want to use getFragmentAtPosition() so that
  840. // we get the fragment matching that start time
  841. if (
  842. !levelDetails.PTSKnown &&
  843. !this.startFragRequested &&
  844. this.startPosition === -1
  845. ) {
  846. frag = this.getInitialLiveFragment(levelDetails, fragments);
  847. this.startPosition = frag
  848. ? this.hls.liveSyncPosition || frag.start
  849. : pos;
  850. }
  851. } else if (pos <= start) {
  852. // VoD playlist: if loadPosition before start of playlist, load first fragment
  853. frag = fragments[0];
  854. }
  855.  
  856. // If we haven't run into any special cases already, just load the fragment most closely matching the requested position
  857. if (!frag) {
  858. const end = config.lowLatencyMode
  859. ? levelDetails.partEnd
  860. : levelDetails.fragmentEnd;
  861. frag = this.getFragmentAtPosition(pos, end, levelDetails);
  862. }
  863.  
  864. // If an initSegment is present, it must be buffered first
  865. if (frag?.initSegment && !frag?.initSegment.data && !this.bitrateTest) {
  866. frag = frag.initSegment;
  867. }
  868.  
  869. return frag;
  870. }
  871.  
  872. getNextPart(
  873. partList: Part[],
  874. frag: Fragment,
  875. targetBufferTime: number
  876. ): number {
  877. let nextPart = -1;
  878. let contiguous = false;
  879. let independentAttrOmitted = true;
  880. for (let i = 0, len = partList.length; i < len; i++) {
  881. const part = partList[i];
  882. independentAttrOmitted = independentAttrOmitted && !part.independent;
  883. if (nextPart > -1 && targetBufferTime < part.start) {
  884. break;
  885. }
  886. const loaded = part.loaded;
  887. if (
  888. !loaded &&
  889. (contiguous || part.independent || independentAttrOmitted) &&
  890. part.fragment === frag
  891. ) {
  892. nextPart = i;
  893. }
  894. contiguous = loaded;
  895. }
  896. return nextPart;
  897. }
  898.  
  899. private loadedEndOfParts(
  900. partList: Part[],
  901. targetBufferTime: number
  902. ): boolean {
  903. const lastPart = partList[partList.length - 1];
  904. return lastPart && targetBufferTime > lastPart.start && lastPart.loaded;
  905. }
  906.  
  907. /*
  908. This method is used find the best matching first fragment for a live playlist. This fragment is used to calculate the
  909. "sliding" of the playlist, which is its offset from the start of playback. After sliding we can compute the real
  910. start and end times for each fragment in the playlist (after which this method will not need to be called).
  911. */
  912. protected getInitialLiveFragment(
  913. levelDetails: LevelDetails,
  914. fragments: Array<Fragment>
  915. ): Fragment | null {
  916. const fragPrevious = this.fragPrevious;
  917. let frag: Fragment | null = null;
  918. if (fragPrevious) {
  919. if (levelDetails.hasProgramDateTime) {
  920. // Prefer using PDT, because it can be accurate enough to choose the correct fragment without knowing the level sliding
  921. this.log(
  922. `Live playlist, switching playlist, load frag with same PDT: ${fragPrevious.programDateTime}`
  923. );
  924. frag = findFragmentByPDT(
  925. fragments,
  926. fragPrevious.endProgramDateTime,
  927. this.config.maxFragLookUpTolerance
  928. );
  929. }
  930. if (!frag) {
  931. // SN does not need to be accurate between renditions, but depending on the packaging it may be so.
  932. const targetSN = (fragPrevious.sn as number) + 1;
  933. if (
  934. targetSN >= levelDetails.startSN &&
  935. targetSN <= levelDetails.endSN
  936. ) {
  937. const fragNext = fragments[targetSN - levelDetails.startSN];
  938. // Ensure that we're staying within the continuity range, since PTS resets upon a new range
  939. if (fragPrevious.cc === fragNext.cc) {
  940. frag = fragNext;
  941. this.log(
  942. `Live playlist, switching playlist, load frag with next SN: ${
  943. frag!.sn
  944. }`
  945. );
  946. }
  947. }
  948. // It's important to stay within the continuity range if available; otherwise the fragments in the playlist
  949. // will have the wrong start times
  950. if (!frag) {
  951. frag = findFragWithCC(fragments, fragPrevious.cc);
  952. if (frag) {
  953. this.log(
  954. `Live playlist, switching playlist, load frag with same CC: ${frag.sn}`
  955. );
  956. }
  957. }
  958. }
  959. } else {
  960. // Find a new start fragment when fragPrevious is null
  961. const liveStart = this.hls.liveSyncPosition;
  962. if (liveStart !== null) {
  963. frag = this.getFragmentAtPosition(
  964. liveStart,
  965. this.bitrateTest ? levelDetails.fragmentEnd : levelDetails.edge,
  966. levelDetails
  967. );
  968. }
  969. }
  970.  
  971. return frag;
  972. }
  973.  
  974. /*
  975. This method finds the best matching fragment given the provided position.
  976. */
  977. protected getFragmentAtPosition(
  978. bufferEnd: number,
  979. end: number,
  980. levelDetails: LevelDetails
  981. ): Fragment | null {
  982. const { config, fragPrevious } = this;
  983. let { fragments, endSN } = levelDetails;
  984. const { fragmentHint } = levelDetails;
  985. const tolerance = config.maxFragLookUpTolerance;
  986.  
  987. const loadingParts = !!(
  988. config.lowLatencyMode &&
  989. levelDetails.partList &&
  990. fragmentHint
  991. );
  992. if (loadingParts && fragmentHint && !this.bitrateTest) {
  993. // Include incomplete fragment with parts at end
  994. fragments = fragments.concat(fragmentHint);
  995. endSN = fragmentHint.sn as number;
  996. }
  997.  
  998. let frag;
  999. if (bufferEnd < end) {
  1000. const lookupTolerance = bufferEnd > end - tolerance ? 0 : tolerance;
  1001. // Remove the tolerance if it would put the bufferEnd past the actual end of stream
  1002. // Uses buffer and sequence number to calculate switch segment (required if using EXT-X-DISCONTINUITY-SEQUENCE)
  1003. frag = findFragmentByPTS(
  1004. fragPrevious,
  1005. fragments,
  1006. bufferEnd,
  1007. lookupTolerance
  1008. );
  1009. } else {
  1010. // reach end of playlist
  1011. frag = fragments[fragments.length - 1];
  1012. }
  1013.  
  1014. if (frag) {
  1015. const curSNIdx = frag.sn - levelDetails.startSN;
  1016. const sameLevel = fragPrevious && frag.level === fragPrevious.level;
  1017. const nextFrag = fragments[curSNIdx + 1];
  1018. const fragState = this.fragmentTracker.getState(frag);
  1019. if (fragState === FragmentState.BACKTRACKED) {
  1020. frag = null;
  1021. let i = curSNIdx;
  1022. while (
  1023. fragments[i] &&
  1024. this.fragmentTracker.getState(fragments[i]) ===
  1025. FragmentState.BACKTRACKED
  1026. ) {
  1027. // When fragPrevious is null, backtrack to first the first fragment is not BACKTRACKED for loading
  1028. // When fragPrevious is set, we want the first BACKTRACKED fragment for parsing and buffering
  1029. if (!fragPrevious) {
  1030. frag = fragments[--i];
  1031. } else {
  1032. frag = fragments[i--];
  1033. }
  1034. }
  1035. if (!frag) {
  1036. frag = nextFrag;
  1037. }
  1038. } else if (fragPrevious && frag.sn === fragPrevious.sn && !loadingParts) {
  1039. // Force the next fragment to load if the previous one was already selected. This can occasionally happen with
  1040. // non-uniform fragment durations
  1041. if (sameLevel) {
  1042. if (
  1043. frag.sn < endSN &&
  1044. this.fragmentTracker.getState(nextFrag) !== FragmentState.OK
  1045. ) {
  1046. this.log(
  1047. `SN ${frag.sn} just loaded, load next one: ${nextFrag.sn}`
  1048. );
  1049. frag = nextFrag;
  1050. } else {
  1051. frag = null;
  1052. }
  1053. }
  1054. }
  1055. }
  1056. return frag;
  1057. }
  1058.  
  1059. protected synchronizeToLiveEdge(levelDetails: LevelDetails) {
  1060. const { config, media } = this;
  1061. if (!media) {
  1062. return;
  1063. }
  1064. const liveSyncPosition = this.hls.liveSyncPosition;
  1065. const currentTime = media.currentTime;
  1066. const start = levelDetails.fragments[0].start;
  1067. const end = levelDetails.edge;
  1068. const withinSlidingWindow =
  1069. currentTime >= start - config.maxFragLookUpTolerance &&
  1070. currentTime <= end;
  1071. // Continue if we can seek forward to sync position or if current time is outside of sliding window
  1072. if (
  1073. liveSyncPosition !== null &&
  1074. media.duration > liveSyncPosition &&
  1075. (currentTime < liveSyncPosition || !withinSlidingWindow)
  1076. ) {
  1077. // Continue if buffer is starving or if current time is behind max latency
  1078. const maxLatency =
  1079. config.liveMaxLatencyDuration !== undefined
  1080. ? config.liveMaxLatencyDuration
  1081. : config.liveMaxLatencyDurationCount * levelDetails.targetduration;
  1082. if (
  1083. (!withinSlidingWindow && media.readyState < 4) ||
  1084. currentTime < end - maxLatency
  1085. ) {
  1086. if (!this.loadedmetadata) {
  1087. this.nextLoadPosition = liveSyncPosition;
  1088. }
  1089. // Only seek if ready and there is not a significant forward buffer available for playback
  1090. if (media.readyState) {
  1091. this.warn(
  1092. `Playback: ${currentTime.toFixed(
  1093. 3
  1094. )} is located too far from the end of live sliding playlist: ${end}, reset currentTime to : ${liveSyncPosition.toFixed(
  1095. 3
  1096. )}`
  1097. );
  1098. media.currentTime = liveSyncPosition;
  1099. }
  1100. }
  1101. }
  1102. }
  1103.  
  1104. protected alignPlaylists(
  1105. details: LevelDetails,
  1106. previousDetails?: LevelDetails
  1107. ): number {
  1108. const { levels, levelLastLoaded, fragPrevious } = this;
  1109. const lastLevel: Level | null =
  1110. levelLastLoaded !== null ? levels![levelLastLoaded] : null;
  1111.  
  1112. // FIXME: If not for `shouldAlignOnDiscontinuities` requiring fragPrevious.cc,
  1113. // this could all go in level-helper mergeDetails()
  1114. const length = details.fragments.length;
  1115. if (!length) {
  1116. this.warn(`No fragments in live playlist`);
  1117. return 0;
  1118. }
  1119. const slidingStart = details.fragments[0].start;
  1120. const firstLevelLoad = !previousDetails;
  1121. const aligned = details.alignedSliding && Number.isFinite(slidingStart);
  1122. if (firstLevelLoad || (!aligned && !slidingStart)) {
  1123. alignStream(fragPrevious, lastLevel, details);
  1124. const alignedSlidingStart = details.fragments[0].start;
  1125. this.log(
  1126. `Live playlist sliding: ${alignedSlidingStart.toFixed(2)} start-sn: ${
  1127. previousDetails ? previousDetails.startSN : 'na'
  1128. }->${details.startSN} prev-sn: ${
  1129. fragPrevious ? fragPrevious.sn : 'na'
  1130. } fragments: ${length}`
  1131. );
  1132. return alignedSlidingStart;
  1133. }
  1134. return slidingStart;
  1135. }
  1136.  
  1137. protected waitForCdnTuneIn(details: LevelDetails) {
  1138. // Wait for Low-Latency CDN Tune-in to get an updated playlist
  1139. const advancePartLimit = 3;
  1140. return (
  1141. details.live &&
  1142. details.canBlockReload &&
  1143. details.tuneInGoal >
  1144. Math.max(details.partHoldBack, details.partTarget * advancePartLimit)
  1145. );
  1146. }
  1147.  
  1148. protected setStartPosition(details: LevelDetails, sliding: number) {
  1149. // compute start position if set to -1. use it straight away if value is defined
  1150. let startPosition = this.startPosition;
  1151. if (startPosition < sliding) {
  1152. startPosition = -1;
  1153. }
  1154. if (startPosition === -1 || this.lastCurrentTime === -1) {
  1155. // first, check if start time offset has been set in playlist, if yes, use this value
  1156. const startTimeOffset = details.startTimeOffset!;
  1157. if (Number.isFinite(startTimeOffset)) {
  1158. startPosition = sliding + startTimeOffset;
  1159. if (startTimeOffset < 0) {
  1160. startPosition += details.totalduration;
  1161. }
  1162. startPosition = Math.min(
  1163. Math.max(sliding, startPosition),
  1164. sliding + details.totalduration
  1165. );
  1166. this.log(
  1167. `Start time offset ${startTimeOffset} found in playlist, adjust startPosition to ${startPosition}`
  1168. );
  1169. this.startPosition = startPosition;
  1170. } else if (details.live) {
  1171. // Leave this.startPosition at -1, so that we can use `getInitialLiveFragment` logic when startPosition has
  1172. // not been specified via the config or an as an argument to startLoad (#3736).
  1173. startPosition = this.hls.liveSyncPosition || sliding;
  1174. } else {
  1175. this.startPosition = startPosition = 0;
  1176. }
  1177. this.lastCurrentTime = startPosition;
  1178. }
  1179. this.nextLoadPosition = startPosition;
  1180. }
  1181.  
  1182. protected getLoadPosition(): number {
  1183. const { media } = this;
  1184. // if we have not yet loaded any fragment, start loading from start position
  1185. let pos = 0;
  1186. if (this.loadedmetadata && media) {
  1187. pos = media.currentTime;
  1188. } else if (this.nextLoadPosition) {
  1189. pos = this.nextLoadPosition;
  1190. }
  1191.  
  1192. return pos;
  1193. }
  1194.  
  1195. private handleFragLoadAborted(frag: Fragment, part: Part | undefined) {
  1196. if (this.transmuxer && frag.sn !== 'initSegment' && frag.stats.aborted) {
  1197. this.warn(
  1198. `Fragment ${frag.sn}${part ? ' part' + part.index : ''} of level ${
  1199. frag.level
  1200. } was aborted`
  1201. );
  1202. this.resetFragmentLoading(frag);
  1203. }
  1204. }
  1205.  
  1206. protected resetFragmentLoading(frag: Fragment) {
  1207. if (!this.fragCurrent || !this.fragContextChanged(frag)) {
  1208. this.state = State.IDLE;
  1209. }
  1210. }
  1211.  
  1212. protected onFragmentOrKeyLoadError(
  1213. filterType: PlaylistLevelType,
  1214. data: ErrorData
  1215. ) {
  1216. if (data.fatal) {
  1217. return;
  1218. }
  1219. const frag = data.frag;
  1220. // Handle frag error related to caller's filterType
  1221. if (!frag || frag.type !== filterType) {
  1222. return;
  1223. }
  1224. const fragCurrent = this.fragCurrent;
  1225. console.assert(
  1226. fragCurrent &&
  1227. frag.sn === fragCurrent.sn &&
  1228. frag.level === fragCurrent.level &&
  1229. frag.urlId === fragCurrent.urlId,
  1230. 'Frag load error must match current frag to retry'
  1231. );
  1232. const config = this.config;
  1233. // keep retrying until the limit will be reached
  1234. if (this.fragLoadError + 1 <= config.fragLoadingMaxRetry) {
  1235. if (this.resetLiveStartWhenNotLoaded(frag.level)) {
  1236. return;
  1237. }
  1238. // exponential backoff capped to config.fragLoadingMaxRetryTimeout
  1239. const delay = Math.min(
  1240. Math.pow(2, this.fragLoadError) * config.fragLoadingRetryDelay,
  1241. config.fragLoadingMaxRetryTimeout
  1242. );
  1243. this.warn(
  1244. `Fragment ${frag.sn} of ${filterType} ${frag.level} failed to load, retrying in ${delay}ms`
  1245. );
  1246. this.retryDate = self.performance.now() + delay;
  1247. this.fragLoadError++;
  1248. this.state = State.FRAG_LOADING_WAITING_RETRY;
  1249. } else if (data.levelRetry) {
  1250. if (filterType === PlaylistLevelType.AUDIO) {
  1251. // Reset current fragment since audio track audio is essential and may not have a fail-over track
  1252. this.fragCurrent = null;
  1253. }
  1254. // Fragment errors that result in a level switch or redundant fail-over
  1255. // should reset the stream controller state to idle
  1256. this.fragLoadError = 0;
  1257. this.state = State.IDLE;
  1258. } else {
  1259. logger.error(
  1260. `${data.details} reaches max retry, redispatch as fatal ...`
  1261. );
  1262. // switch error to fatal
  1263. data.fatal = true;
  1264. this.hls.stopLoad();
  1265. this.state = State.ERROR;
  1266. }
  1267. }
  1268.  
  1269. protected afterBufferFlushed(
  1270. media: Bufferable,
  1271. bufferType: SourceBufferName,
  1272. playlistType: PlaylistLevelType
  1273. ) {
  1274. if (!media) {
  1275. return;
  1276. }
  1277. // After successful buffer flushing, filter flushed fragments from bufferedFrags use mediaBuffered instead of media
  1278. // (so that we will check against video.buffered ranges in case of alt audio track)
  1279. const bufferedTimeRanges = BufferHelper.getBuffered(media);
  1280. this.fragmentTracker.detectEvictedFragments(
  1281. bufferType,
  1282. bufferedTimeRanges,
  1283. playlistType
  1284. );
  1285. if (this.state === State.ENDED) {
  1286. this.resetLoadingState();
  1287. }
  1288. }
  1289.  
  1290. protected resetLoadingState() {
  1291. this.fragCurrent = null;
  1292. this.fragPrevious = null;
  1293. this.state = State.IDLE;
  1294. }
  1295.  
  1296. protected resetLiveStartWhenNotLoaded(level: number): boolean {
  1297. // if loadedmetadata is not set, it means that we are emergency switch down on first frag
  1298. // in that case, reset startFragRequested flag
  1299. if (!this.loadedmetadata) {
  1300. this.startFragRequested = false;
  1301. const details = this.levels ? this.levels[level].details : null;
  1302. if (details?.live) {
  1303. // We can't afford to retry after a delay in a live scenario. Update the start position and return to IDLE.
  1304. this.startPosition = -1;
  1305. this.setStartPosition(details, 0);
  1306. this.resetLoadingState();
  1307. return true;
  1308. }
  1309. this.nextLoadPosition = this.startPosition;
  1310. }
  1311. return false;
  1312. }
  1313.  
  1314. private updateLevelTiming(
  1315. frag: Fragment,
  1316. part: Part | null,
  1317. level: Level,
  1318. partial: boolean
  1319. ) {
  1320. const details = level.details as LevelDetails;
  1321. console.assert(!!details, 'level.details must be defined');
  1322. const parsed = Object.keys(frag.elementaryStreams).reduce(
  1323. (result, type) => {
  1324. const info = frag.elementaryStreams[type];
  1325. if (info) {
  1326. const parsedDuration = info.endPTS - info.startPTS;
  1327. if (parsedDuration <= 0) {
  1328. // Destroy the transmuxer after it's next time offset failed to advance because duration was <= 0.
  1329. // The new transmuxer will be configured with a time offset matching the next fragment start,
  1330. // preventing the timeline from shifting.
  1331. this.warn(
  1332. `Could not parse fragment ${frag.sn} ${type} duration reliably (${parsedDuration}) resetting transmuxer to fallback to playlist timing`
  1333. );
  1334. this.resetTransmuxer();
  1335. return result || false;
  1336. }
  1337. const drift = partial
  1338. ? 0
  1339. : updateFragPTSDTS(
  1340. details,
  1341. frag,
  1342. info.startPTS,
  1343. info.endPTS,
  1344. info.startDTS,
  1345. info.endDTS
  1346. );
  1347. this.hls.trigger(Events.LEVEL_PTS_UPDATED, {
  1348. details,
  1349. level,
  1350. drift,
  1351. type,
  1352. frag,
  1353. start: info.startPTS,
  1354. end: info.endPTS,
  1355. });
  1356. return true;
  1357. }
  1358. return result;
  1359. },
  1360. false
  1361. );
  1362. if (parsed) {
  1363. this.state = State.PARSED;
  1364. this.hls.trigger(Events.FRAG_PARSED, { frag, part });
  1365. } else {
  1366. this.resetLoadingState();
  1367. }
  1368. }
  1369.  
  1370. protected resetTransmuxer() {
  1371. if (this.transmuxer) {
  1372. this.transmuxer.destroy();
  1373. this.transmuxer = null;
  1374. }
  1375. }
  1376.  
  1377. set state(nextState) {
  1378. const previousState = this._state;
  1379. if (previousState !== nextState) {
  1380. this._state = nextState;
  1381. this.log(`${previousState}->${nextState}`);
  1382. }
  1383. }
  1384.  
  1385. get state() {
  1386. return this._state;
  1387. }
  1388. }