Home Reference Source

src/controller/stream-controller.js

  1. /*
  2. * Stream Controller
  3. */
  4.  
  5. import BinarySearch from '../utils/binary-search';
  6. import { BufferHelper } from '../utils/buffer-helper';
  7. import Demuxer from '../demux/demuxer';
  8. import Event from '../events';
  9. import { FragmentState } from './fragment-tracker';
  10. import { ElementaryStreamTypes } from '../loader/fragment';
  11. import { PlaylistLevelType } from '../types/loader';
  12. import * as LevelHelper from './level-helper';
  13. import TimeRanges from '../utils/time-ranges';
  14. import { ErrorDetails } from '../errors';
  15. import { logger } from '../utils/logger';
  16. import { alignStream } from '../utils/discontinuities';
  17. import { findFragmentByPDT, findFragmentByPTS } from './fragment-finders';
  18. import GapController from './gap-controller';
  19. import BaseStreamController, { State } from './base-stream-controller';
  20.  
  21. const TICK_INTERVAL = 100; // how often to tick in ms
  22.  
  23. class StreamController extends BaseStreamController {
  24. constructor (hls, fragmentTracker) {
  25. super(hls,
  26. Event.MEDIA_ATTACHED,
  27. Event.MEDIA_DETACHING,
  28. Event.MANIFEST_LOADING,
  29. Event.MANIFEST_PARSED,
  30. Event.LEVEL_LOADED,
  31. Event.LEVELS_UPDATED,
  32. Event.KEY_LOADED,
  33. Event.FRAG_LOADED,
  34. Event.FRAG_LOAD_EMERGENCY_ABORTED,
  35. Event.FRAG_PARSING_INIT_SEGMENT,
  36. Event.FRAG_PARSING_DATA,
  37. Event.FRAG_PARSED,
  38. Event.ERROR,
  39. Event.AUDIO_TRACK_SWITCHING,
  40. Event.AUDIO_TRACK_SWITCHED,
  41. Event.BUFFER_CREATED,
  42. Event.BUFFER_APPENDED,
  43. Event.BUFFER_FLUSHED);
  44.  
  45. this.fragmentTracker = fragmentTracker;
  46. this.config = hls.config;
  47. this.audioCodecSwap = false;
  48. this._state = State.STOPPED;
  49. this.stallReported = false;
  50. this.gapController = null;
  51. this.altAudio = false;
  52. this.bitrateTest = false;
  53. }
  54.  
  55. startLoad (startPosition) {
  56. if (this.levels) {
  57. let lastCurrentTime = this.lastCurrentTime, hls = this.hls;
  58. this.stopLoad();
  59. this.setInterval(TICK_INTERVAL);
  60. this.level = -1;
  61. this.fragLoadError = 0;
  62. if (!this.startFragRequested) {
  63. // determine load level
  64. let startLevel = hls.startLevel;
  65. if (startLevel === -1) {
  66. if (hls.config.testBandwidth) {
  67. // -1 : guess start Level by doing a bitrate test by loading first fragment of lowest quality level
  68. startLevel = 0;
  69. this.bitrateTest = true;
  70. } else {
  71. startLevel = hls.nextAutoLevel;
  72. }
  73. }
  74. // set new level to playlist loader : this will trigger start level load
  75. // hls.nextLoadLevel remains until it is set to a new value or until a new frag is successfully loaded
  76. this.level = hls.nextLoadLevel = startLevel;
  77. this.loadedmetadata = false;
  78. }
  79. // if startPosition undefined but lastCurrentTime set, set startPosition to last currentTime
  80. if (lastCurrentTime > 0 && startPosition === -1) {
  81. logger.log(`override startPosition with lastCurrentTime @${lastCurrentTime.toFixed(3)}`);
  82. startPosition = lastCurrentTime;
  83. }
  84. this.state = State.IDLE;
  85. this.nextLoadPosition = this.startPosition = this.lastCurrentTime = startPosition;
  86. this.tick();
  87. } else {
  88. this.forceStartLoad = true;
  89. this.state = State.STOPPED;
  90. }
  91. }
  92.  
  93. stopLoad () {
  94. this.forceStartLoad = false;
  95. super.stopLoad();
  96. }
  97.  
  98. doTick () {
  99. switch (this.state) {
  100. case State.BUFFER_FLUSHING:
  101. // in buffer flushing state, reset fragLoadError counter
  102. this.fragLoadError = 0;
  103. break;
  104. case State.IDLE:
  105. this._doTickIdle();
  106. break;
  107. case State.WAITING_LEVEL:
  108. var level = this.levels[this.level];
  109. // check if playlist is already loaded
  110. if (level && level.details) {
  111. this.state = State.IDLE;
  112. }
  113.  
  114. break;
  115. case State.FRAG_LOADING_WAITING_RETRY:
  116. var now = window.performance.now();
  117. var retryDate = this.retryDate;
  118. // if current time is gt than retryDate, or if media seeking let's switch to IDLE state to retry loading
  119. if (!retryDate || (now >= retryDate) || (this.media && this.media.seeking)) {
  120. logger.log('mediaController: retryDate reached, switch back to IDLE state');
  121. this.state = State.IDLE;
  122. }
  123. break;
  124. case State.ERROR:
  125. case State.STOPPED:
  126. case State.FRAG_LOADING:
  127. case State.PARSING:
  128. case State.PARSED:
  129. case State.ENDED:
  130. break;
  131. default:
  132. break;
  133. }
  134. // check buffer
  135. this._checkBuffer();
  136. // check/update current fragment
  137. this._checkFragmentChanged();
  138. }
  139.  
  140. // Ironically the "idle" state is the on we do the most logic in it seems ....
  141. // NOTE: Maybe we could rather schedule a check for buffer length after half of the currently
  142. // played segment, or on pause/play/seek instead of naively checking every 100ms?
  143. _doTickIdle () {
  144. const hls = this.hls,
  145. config = hls.config,
  146. media = this.media;
  147.  
  148. // if start level not parsed yet OR
  149. // if video not attached AND start fragment already requested OR start frag prefetch disable
  150. // exit loop, as we either need more info (level not parsed) or we need media to be attached to load new fragment
  151. if (this.levelLastLoaded === undefined || (
  152. !media && (this.startFragRequested || !config.startFragPrefetch))) {
  153. return;
  154. }
  155.  
  156. // if we have not yet loaded any fragment, start loading from start position
  157. let pos;
  158. if (this.loadedmetadata) {
  159. pos = media.currentTime;
  160. } else {
  161. pos = this.nextLoadPosition;
  162. }
  163.  
  164. // determine next load level
  165. let level = hls.nextLoadLevel,
  166. levelInfo = this.levels[level];
  167.  
  168. if (!levelInfo) {
  169. return;
  170. }
  171.  
  172. let levelBitrate = levelInfo.bitrate,
  173. maxBufLen;
  174.  
  175. // compute max Buffer Length that we could get from this load level, based on level bitrate.
  176. if (levelBitrate) {
  177. maxBufLen = Math.max(8 * config.maxBufferSize / levelBitrate, config.maxBufferLength);
  178. } else {
  179. maxBufLen = config.maxBufferLength;
  180. }
  181.  
  182. maxBufLen = Math.min(maxBufLen, config.maxMaxBufferLength);
  183.  
  184. // determine next candidate fragment to be loaded, based on current position and end of buffer position
  185. // ensure up to `config.maxMaxBufferLength` of buffer upfront
  186.  
  187. const bufferInfo = BufferHelper.bufferInfo(this.mediaBuffer ? this.mediaBuffer : media, pos, config.maxBufferHole),
  188. bufferLen = bufferInfo.len;
  189. // Stay idle if we are still with buffer margins
  190. if (bufferLen >= maxBufLen) {
  191. return;
  192. }
  193.  
  194. // if buffer length is less than maxBufLen try to load a new fragment ...
  195. logger.trace(`buffer length of ${bufferLen.toFixed(3)} is below max of ${maxBufLen.toFixed(3)}. checking for more payload ...`);
  196.  
  197. // set next load level : this will trigger a playlist load if needed
  198. this.level = hls.nextLoadLevel = level;
  199.  
  200. const levelDetails = levelInfo.details;
  201. // if level info not retrieved yet, switch state and wait for level retrieval
  202. // if live playlist, ensure that new playlist has been refreshed to avoid loading/try to load
  203. // a useless and outdated fragment (that might even introduce load error if it is already out of the live playlist)
  204. if (!levelDetails || (levelDetails.live && this.levelLastLoaded !== level)) {
  205. this.state = State.WAITING_LEVEL;
  206. return;
  207. }
  208.  
  209. if (this._streamEnded(bufferInfo, levelDetails)) {
  210. const data = {};
  211. if (this.altAudio) {
  212. data.type = 'video';
  213. }
  214.  
  215. this.hls.trigger(Event.BUFFER_EOS, data);
  216. this.state = State.ENDED;
  217. return;
  218. }
  219. // if we have the levelDetails for the selected variant, lets continue enrichen our stream (load keys/fragments or trigger EOS, etc..)
  220. this._fetchPayloadOrEos(pos, bufferInfo, levelDetails);
  221. }
  222.  
  223. _fetchPayloadOrEos (pos, bufferInfo, levelDetails) {
  224. const fragPrevious = this.fragPrevious,
  225. level = this.level,
  226. fragments = levelDetails.fragments,
  227. fragLen = fragments.length;
  228.  
  229. // empty playlist
  230. if (fragLen === 0) {
  231. return;
  232. }
  233.  
  234. // find fragment index, contiguous with end of buffer position
  235. let start = fragments[0].start,
  236. end = fragments[fragLen - 1].start + fragments[fragLen - 1].duration,
  237. bufferEnd = bufferInfo.end,
  238. frag;
  239.  
  240. if (levelDetails.initSegment && !levelDetails.initSegment.data) {
  241. frag = levelDetails.initSegment;
  242. } else {
  243. // in case of live playlist we need to ensure that requested position is not located before playlist start
  244. if (levelDetails.live) {
  245. let initialLiveManifestSize = this.config.initialLiveManifestSize;
  246. if (fragLen < initialLiveManifestSize) {
  247. logger.warn(`Can not start playback of a level, reason: not enough fragments ${fragLen} < ${initialLiveManifestSize}`);
  248. return;
  249. }
  250.  
  251. frag = this._ensureFragmentAtLivePoint(levelDetails, bufferEnd, start, end, fragPrevious, fragments);
  252. // if it explicitely returns null don't load any fragment and exit function now
  253. if (frag === null) {
  254. return;
  255. }
  256. } else {
  257. // VoD playlist: if bufferEnd before start of playlist, load first fragment
  258. if (bufferEnd < start) {
  259. frag = fragments[0];
  260. }
  261. }
  262. }
  263. if (!frag) {
  264. frag = this._findFragment(start, fragPrevious, fragLen, fragments, bufferEnd, end, levelDetails);
  265. }
  266.  
  267. if (frag) {
  268. if (frag.encrypted) {
  269. logger.log(`Loading key for ${frag.sn} of [${levelDetails.startSN} ,${levelDetails.endSN}],level ${level}`);
  270. this._loadKey(frag);
  271. } else {
  272. logger.log(`Loading ${frag.sn} of [${levelDetails.startSN} ,${levelDetails.endSN}],level ${level}, currentTime:${pos.toFixed(3)},bufferEnd:${bufferEnd.toFixed(3)}`);
  273. this._loadFragment(frag);
  274. }
  275. }
  276. }
  277.  
  278. _ensureFragmentAtLivePoint (levelDetails, bufferEnd, start, end, fragPrevious, fragments) {
  279. const config = this.hls.config, media = this.media;
  280.  
  281. let frag;
  282.  
  283. // check if requested position is within seekable boundaries :
  284. // logger.log(`start/pos/bufEnd/seeking:${start.toFixed(3)}/${pos.toFixed(3)}/${bufferEnd.toFixed(3)}/${this.media.seeking}`);
  285. let maxLatency = Infinity;
  286.  
  287. if (config.liveMaxLatencyDuration !== undefined) {
  288. maxLatency = config.liveMaxLatencyDuration;
  289. } else if (Number.isFinite(config.liveMaxLatencyDurationCount)) {
  290. maxLatency = config.liveMaxLatencyDurationCount * levelDetails.targetduration;
  291. }
  292.  
  293. if (bufferEnd < Math.max(start - config.maxFragLookUpTolerance, end - maxLatency)) {
  294. let liveSyncPosition = this.liveSyncPosition = this.computeLivePosition(start, levelDetails);
  295. bufferEnd = liveSyncPosition;
  296. if (media && !media.paused && media.readyState && media.duration > liveSyncPosition && liveSyncPosition > media.currentTime) {
  297. logger.log(`buffer end: ${bufferEnd.toFixed(3)} is located too far from the end of live sliding playlist, reset currentTime to : ${liveSyncPosition.toFixed(3)}`);
  298. media.currentTime = liveSyncPosition;
  299. }
  300.  
  301. this.nextLoadPosition = liveSyncPosition;
  302. }
  303.  
  304. // if end of buffer greater than live edge, don't load any fragment
  305. // this could happen if live playlist intermittently slides in the past.
  306. // level 1 loaded [182580161,182580167]
  307. // level 1 loaded [182580162,182580169]
  308. // Loading 182580168 of [182580162 ,182580169],level 1 ..
  309. // Loading 182580169 of [182580162 ,182580169],level 1 ..
  310. // level 1 loaded [182580162,182580168] <============= here we should have bufferEnd > end. in that case break to avoid reloading 182580168
  311. // level 1 loaded [182580164,182580171]
  312. //
  313. // don't return null in case media not loaded yet (readystate === 0)
  314. if (levelDetails.PTSKnown && bufferEnd > end && media && media.readyState) {
  315. return null;
  316. }
  317.  
  318. if (this.startFragRequested && !levelDetails.PTSKnown) {
  319. /* we are switching level on live playlist, but we don't have any PTS info for that quality level ...
  320. try to load frag matching with next SN.
  321. even if SN are not synchronized between playlists, loading this frag will help us
  322. compute playlist sliding and find the right one after in case it was not the right consecutive one */
  323. if (fragPrevious) {
  324. if (levelDetails.hasProgramDateTime) {
  325. // Relies on PDT in order to switch bitrates (Support EXT-X-DISCONTINUITY without EXT-X-DISCONTINUITY-SEQUENCE)
  326. logger.log(`live playlist, switching playlist, load frag with same PDT: ${fragPrevious.programDateTime}`);
  327. frag = findFragmentByPDT(fragments, fragPrevious.endProgramDateTime, config.maxFragLookUpTolerance);
  328. } else {
  329. // Uses buffer and sequence number to calculate switch segment (required if using EXT-X-DISCONTINUITY-SEQUENCE)
  330. const targetSN = fragPrevious.sn + 1;
  331. if (targetSN >= levelDetails.startSN && targetSN <= levelDetails.endSN) {
  332. const fragNext = fragments[targetSN - levelDetails.startSN];
  333. if (fragPrevious.cc === fragNext.cc) {
  334. frag = fragNext;
  335. logger.log(`live playlist, switching playlist, load frag with next SN: ${frag.sn}`);
  336. }
  337. }
  338. // next frag SN not available (or not with same continuity counter)
  339. // look for a frag sharing the same CC
  340. if (!frag) {
  341. frag = BinarySearch.search(fragments, function (frag) {
  342. return fragPrevious.cc - frag.cc;
  343. });
  344. if (frag) {
  345. logger.log(`live playlist, switching playlist, load frag with same CC: ${frag.sn}`);
  346. }
  347. }
  348. }
  349. }
  350. }
  351.  
  352. return frag;
  353. }
  354.  
  355. _findFragment (start, fragPreviousLoad, fragmentIndexRange, fragments, bufferEnd, end, levelDetails) {
  356. const config = this.hls.config;
  357. let fragNextLoad;
  358.  
  359. if (bufferEnd < end) {
  360. const lookupTolerance = (bufferEnd > end - config.maxFragLookUpTolerance) ? 0 : config.maxFragLookUpTolerance;
  361. // Remove the tolerance if it would put the bufferEnd past the actual end of stream
  362. // Uses buffer and sequence number to calculate switch segment (required if using EXT-X-DISCONTINUITY-SEQUENCE)
  363. fragNextLoad = findFragmentByPTS(fragPreviousLoad, fragments, bufferEnd, lookupTolerance);
  364. } else {
  365. // reach end of playlist
  366. fragNextLoad = fragments[fragmentIndexRange - 1];
  367. }
  368.  
  369. if (fragNextLoad) {
  370. const curSNIdx = fragNextLoad.sn - levelDetails.startSN;
  371. const sameLevel = fragPreviousLoad && fragNextLoad.level === fragPreviousLoad.level;
  372. const prevSnFrag = fragments[curSNIdx - 1];
  373. const nextSnFrag = fragments[curSNIdx + 1];
  374.  
  375. // logger.log('find SN matching with pos:' + bufferEnd + ':' + frag.sn);
  376. if (fragPreviousLoad && fragNextLoad.sn === fragPreviousLoad.sn) {
  377. if (sameLevel && !fragNextLoad.backtracked) {
  378. if (fragNextLoad.sn < levelDetails.endSN) {
  379. let deltaPTS = fragPreviousLoad.deltaPTS;
  380. // if there is a significant delta between audio and video, larger than max allowed hole,
  381. // and if previous remuxed fragment did not start with a keyframe. (fragPrevious.dropped)
  382. // let's try to load previous fragment again to get last keyframe
  383. // then we will reload again current fragment (that way we should be able to fill the buffer hole ...)
  384. if (deltaPTS && deltaPTS > config.maxBufferHole && fragPreviousLoad.dropped && curSNIdx) {
  385. fragNextLoad = prevSnFrag;
  386. logger.warn('Previous fragment was dropped with large PTS gap between audio and video. Maybe fragment is not starting with a keyframe? Loading previous one to try to overcome this');
  387. } else {
  388. fragNextLoad = nextSnFrag;
  389. logger.log(`Re-loading fragment with SN: ${fragNextLoad.sn}`);
  390. }
  391. } else {
  392. fragNextLoad = null;
  393. }
  394. } else if (fragNextLoad.backtracked) {
  395. // Only backtrack a max of 1 consecutive fragment to prevent sliding back too far when little or no frags start with keyframes
  396. if (nextSnFrag && nextSnFrag.backtracked) {
  397. logger.warn(`Already backtracked from fragment ${nextSnFrag.sn}, will not backtrack to fragment ${fragNextLoad.sn}. Loading fragment ${nextSnFrag.sn}`);
  398. fragNextLoad = nextSnFrag;
  399. } else {
  400. // If a fragment has dropped frames and it's in a same level/sequence, load the previous fragment to try and find the keyframe
  401. // Reset the dropped count now since it won't be reset until we parse the fragment again, which prevents infinite backtracking on the same segment
  402. logger.warn('Loaded fragment with dropped frames, backtracking 1 segment to find a keyframe');
  403. fragNextLoad.dropped = 0;
  404. if (prevSnFrag) {
  405. fragNextLoad = prevSnFrag;
  406. fragNextLoad.backtracked = true;
  407. } else if (curSNIdx) {
  408. // can't backtrack on very first fragment
  409. fragNextLoad = null;
  410. }
  411. }
  412. }
  413. }
  414. }
  415.  
  416. return fragNextLoad;
  417. }
  418.  
  419. _loadKey (frag) {
  420. this.state = State.KEY_LOADING;
  421. this.hls.trigger(Event.KEY_LOADING, { frag });
  422. }
  423.  
  424. _loadFragment (frag) {
  425. // Check if fragment is not loaded
  426. let fragState = this.fragmentTracker.getState(frag);
  427.  
  428. this.fragCurrent = frag;
  429. if (frag.sn !== 'initSegment') {
  430. this.startFragRequested = true;
  431. }
  432. // Don't update nextLoadPosition for fragments which are not buffered
  433. if (Number.isFinite(frag.sn) && !frag.bitrateTest) {
  434. this.nextLoadPosition = frag.start + frag.duration;
  435. }
  436.  
  437. // Allow backtracked fragments to load
  438. if (frag.backtracked || fragState === FragmentState.NOT_LOADED || fragState === FragmentState.PARTIAL) {
  439. frag.autoLevel = this.hls.autoLevelEnabled;
  440. frag.bitrateTest = this.bitrateTest;
  441.  
  442. this.hls.trigger(Event.FRAG_LOADING, { frag });
  443. // lazy demuxer init, as this could take some time ... do it during frag loading
  444. if (!this.demuxer) {
  445. this.demuxer = new Demuxer(this.hls, 'main');
  446. }
  447.  
  448. this.state = State.FRAG_LOADING;
  449. } else if (fragState === FragmentState.APPENDING) {
  450. // Lower the buffer size and try again
  451. if (this._reduceMaxBufferLength(frag.duration)) {
  452. this.fragmentTracker.removeFragment(frag);
  453. }
  454. }
  455. }
  456.  
  457. set state (nextState) {
  458. if (this.state !== nextState) {
  459. const previousState = this.state;
  460. this._state = nextState;
  461. logger.log(`main stream-controller: ${previousState}->${nextState}`);
  462. this.hls.trigger(Event.STREAM_STATE_TRANSITION, { previousState, nextState });
  463. }
  464. }
  465.  
  466. get state () {
  467. return this._state;
  468. }
  469.  
  470. getBufferedFrag (position) {
  471. return this.fragmentTracker.getBufferedFrag(position, PlaylistLevelType.MAIN);
  472. }
  473.  
  474. get currentLevel () {
  475. let media = this.media;
  476. if (media) {
  477. const frag = this.getBufferedFrag(media.currentTime);
  478. if (frag) {
  479. return frag.level;
  480. }
  481. }
  482. return -1;
  483. }
  484.  
  485. get nextBufferedFrag () {
  486. let media = this.media;
  487. if (media) {
  488. // first get end range of current fragment
  489. return this.followingBufferedFrag(this.getBufferedFrag(media.currentTime));
  490. } else {
  491. return null;
  492. }
  493. }
  494.  
  495. followingBufferedFrag (frag) {
  496. if (frag) {
  497. // try to get range of next fragment (500ms after this range)
  498. return this.getBufferedFrag(frag.endPTS + 0.5);
  499. }
  500. return null;
  501. }
  502.  
  503. get nextLevel () {
  504. const frag = this.nextBufferedFrag;
  505. if (frag) {
  506. return frag.level;
  507. } else {
  508. return -1;
  509. }
  510. }
  511.  
  512. _checkFragmentChanged () {
  513. let fragPlayingCurrent, currentTime, video = this.media;
  514. if (video && video.readyState && video.seeking === false) {
  515. currentTime = video.currentTime;
  516. /* if video element is in seeked state, currentTime can only increase.
  517. (assuming that playback rate is positive ...)
  518. As sometimes currentTime jumps back to zero after a
  519. media decode error, check this, to avoid seeking back to
  520. wrong position after a media decode error
  521. */
  522. if (currentTime > this.lastCurrentTime) {
  523. this.lastCurrentTime = currentTime;
  524. }
  525.  
  526. if (BufferHelper.isBuffered(video, currentTime)) {
  527. fragPlayingCurrent = this.getBufferedFrag(currentTime);
  528. } else if (BufferHelper.isBuffered(video, currentTime + 0.1)) {
  529. /* ensure that FRAG_CHANGED event is triggered at startup,
  530. when first video frame is displayed and playback is paused.
  531. add a tolerance of 100ms, in case current position is not buffered,
  532. check if current pos+100ms is buffered and use that buffer range
  533. for FRAG_CHANGED event reporting */
  534. fragPlayingCurrent = this.getBufferedFrag(currentTime + 0.1);
  535. }
  536. if (fragPlayingCurrent) {
  537. let fragPlaying = fragPlayingCurrent;
  538. if (fragPlaying !== this.fragPlaying) {
  539. this.hls.trigger(Event.FRAG_CHANGED, { frag: fragPlaying });
  540. const fragPlayingLevel = fragPlaying.level;
  541. if (!this.fragPlaying || this.fragPlaying.level !== fragPlayingLevel) {
  542. this.hls.trigger(Event.LEVEL_SWITCHED, { level: fragPlayingLevel });
  543. }
  544.  
  545. this.fragPlaying = fragPlaying;
  546. }
  547. }
  548. }
  549. }
  550.  
  551. /*
  552. on immediate level switch :
  553. - pause playback if playing
  554. - cancel any pending load request
  555. - and trigger a buffer flush
  556. */
  557. immediateLevelSwitch () {
  558. logger.log('immediateLevelSwitch');
  559. if (!this.immediateSwitch) {
  560. this.immediateSwitch = true;
  561. let media = this.media, previouslyPaused;
  562. if (media) {
  563. previouslyPaused = media.paused;
  564. media.pause();
  565. } else {
  566. // don't restart playback after instant level switch in case media not attached
  567. previouslyPaused = true;
  568. }
  569. this.previouslyPaused = previouslyPaused;
  570. }
  571. let fragCurrent = this.fragCurrent;
  572. if (fragCurrent && fragCurrent.loader) {
  573. fragCurrent.loader.abort();
  574. }
  575.  
  576. this.fragCurrent = null;
  577. // flush everything
  578. this.flushMainBuffer(0, Number.POSITIVE_INFINITY);
  579. }
  580.  
  581. /**
  582. * on immediate level switch end, after new fragment has been buffered:
  583. * - nudge video decoder by slightly adjusting video currentTime (if currentTime buffered)
  584. * - resume the playback if needed
  585. */
  586. immediateLevelSwitchEnd () {
  587. const media = this.media;
  588. if (media && media.buffered.length) {
  589. this.immediateSwitch = false;
  590. if (BufferHelper.isBuffered(media, media.currentTime)) {
  591. // only nudge if currentTime is buffered
  592. media.currentTime -= 0.0001;
  593. }
  594. if (!this.previouslyPaused) {
  595. media.play();
  596. }
  597. }
  598. }
  599.  
  600. /**
  601. * try to switch ASAP without breaking video playback:
  602. * in order to ensure smooth but quick level switching,
  603. * we need to find the next flushable buffer range
  604. * we should take into account new segment fetch time
  605. */
  606. nextLevelSwitch () {
  607. const media = this.media;
  608. // ensure that media is defined and that metadata are available (to retrieve currentTime)
  609. if (media && media.readyState) {
  610. let fetchdelay, fragPlayingCurrent, nextBufferedFrag;
  611. fragPlayingCurrent = this.getBufferedFrag(media.currentTime);
  612. if (fragPlayingCurrent && fragPlayingCurrent.startPTS > 1) {
  613. // flush buffer preceding current fragment (flush until current fragment start offset)
  614. // minus 1s to avoid video freezing, that could happen if we flush keyframe of current video ...
  615. this.flushMainBuffer(0, fragPlayingCurrent.startPTS - 1);
  616. }
  617. if (!media.paused) {
  618. // add a safety delay of 1s
  619. let nextLevelId = this.hls.nextLoadLevel, nextLevel = this.levels[nextLevelId], fragLastKbps = this.fragLastKbps;
  620. if (fragLastKbps && this.fragCurrent) {
  621. fetchdelay = this.fragCurrent.duration * nextLevel.bitrate / (1000 * fragLastKbps) + 1;
  622. } else {
  623. fetchdelay = 0;
  624. }
  625. } else {
  626. fetchdelay = 0;
  627. }
  628. // logger.log('fetchdelay:'+fetchdelay);
  629. // find buffer range that will be reached once new fragment will be fetched
  630. nextBufferedFrag = this.getBufferedFrag(media.currentTime + fetchdelay);
  631. if (nextBufferedFrag) {
  632. // we can flush buffer range following this one without stalling playback
  633. nextBufferedFrag = this.followingBufferedFrag(nextBufferedFrag);
  634. if (nextBufferedFrag) {
  635. // if we are here, we can also cancel any loading/demuxing in progress, as they are useless
  636. let fragCurrent = this.fragCurrent;
  637. if (fragCurrent && fragCurrent.loader) {
  638. fragCurrent.loader.abort();
  639. }
  640.  
  641. this.fragCurrent = null;
  642. // start flush position is the start PTS of next buffered frag.
  643. // we use frag.naxStartPTS which is max(audio startPTS, video startPTS).
  644. // in case there is a small PTS Delta between audio and video, using maxStartPTS avoids flushing last samples from current fragment
  645. this.flushMainBuffer(nextBufferedFrag.maxStartPTS, Number.POSITIVE_INFINITY);
  646. }
  647. }
  648. }
  649. }
  650.  
  651. flushMainBuffer (startOffset, endOffset) {
  652. this.state = State.BUFFER_FLUSHING;
  653. let flushScope = { startOffset: startOffset, endOffset: endOffset };
  654. // if alternate audio tracks are used, only flush video, otherwise flush everything
  655. if (this.altAudio) {
  656. flushScope.type = 'video';
  657. }
  658.  
  659. this.hls.trigger(Event.BUFFER_FLUSHING, flushScope);
  660. }
  661.  
  662. onMediaAttached (data) {
  663. let media = this.media = this.mediaBuffer = data.media;
  664. this.onvseeking = this.onMediaSeeking.bind(this);
  665. this.onvseeked = this.onMediaSeeked.bind(this);
  666. this.onvended = this.onMediaEnded.bind(this);
  667. media.addEventListener('seeking', this.onvseeking);
  668. media.addEventListener('seeked', this.onvseeked);
  669. media.addEventListener('ended', this.onvended);
  670. let config = this.config;
  671. if (this.levels && config.autoStartLoad) {
  672. this.hls.startLoad(config.startPosition);
  673. }
  674.  
  675. this.gapController = new GapController(config, media, this.fragmentTracker, this.hls);
  676. }
  677.  
  678. onMediaDetaching () {
  679. let media = this.media;
  680. if (media && media.ended) {
  681. logger.log('MSE detaching and video ended, reset startPosition');
  682. this.startPosition = this.lastCurrentTime = 0;
  683. }
  684.  
  685. // reset fragment backtracked flag
  686. let levels = this.levels;
  687. if (levels) {
  688. levels.forEach(level => {
  689. if (level.details) {
  690. level.details.fragments.forEach(fragment => {
  691. fragment.backtracked = undefined;
  692. });
  693. }
  694. });
  695. }
  696.  
  697. // remove video listeners
  698. if (media) {
  699. media.removeEventListener('seeking', this.onvseeking);
  700. media.removeEventListener('seeked', this.onvseeked);
  701. media.removeEventListener('ended', this.onvended);
  702. this.onvseeking = this.onvseeked = this.onvended = null;
  703. }
  704.  
  705. this.fragmentTracker.removeAllFragments();
  706. this.media = this.mediaBuffer = null;
  707. this.loadedmetadata = false;
  708. this.stopLoad();
  709. }
  710.  
  711. onMediaSeeked () {
  712. const media = this.media;
  713. const currentTime = media ? media.currentTime : undefined;
  714. if (Number.isFinite(currentTime)) {
  715. logger.log(`media seeked to ${currentTime.toFixed(3)}`);
  716. }
  717.  
  718. // tick to speed up FRAGMENT_PLAYING triggering
  719. this.tick();
  720. }
  721.  
  722. onManifestLoading () {
  723. // reset buffer on manifest loading
  724. logger.log('trigger BUFFER_RESET');
  725. this.hls.trigger(Event.BUFFER_RESET);
  726. this.fragmentTracker.removeAllFragments();
  727. this.stalled = false;
  728. this.startPosition = this.lastCurrentTime = 0;
  729. }
  730.  
  731. onManifestParsed (data) {
  732. let aac = false, heaac = false, codec;
  733. data.levels.forEach(level => {
  734. // detect if we have different kind of audio codecs used amongst playlists
  735. codec = level.audioCodec;
  736. if (codec) {
  737. if (codec.indexOf('mp4a.40.2') !== -1) {
  738. aac = true;
  739. }
  740.  
  741. if (codec.indexOf('mp4a.40.5') !== -1) {
  742. heaac = true;
  743. }
  744. }
  745. });
  746. this.audioCodecSwitch = (aac && heaac);
  747. if (this.audioCodecSwitch) {
  748. logger.log('both AAC/HE-AAC audio found in levels; declaring level codec as HE-AAC');
  749. }
  750.  
  751. this.altAudio = data.altAudio;
  752. this.levels = data.levels;
  753. this.startFragRequested = false;
  754. let config = this.config;
  755. if (config.autoStartLoad || this.forceStartLoad) {
  756. this.hls.startLoad(config.startPosition);
  757. }
  758. }
  759.  
  760. onLevelLoaded (data) {
  761. const newDetails = data.details;
  762. const newLevelId = data.level;
  763. const lastLevel = this.levels[this.levelLastLoaded];
  764. const curLevel = this.levels[newLevelId];
  765. const duration = newDetails.totalduration;
  766. let sliding = 0;
  767.  
  768. logger.log(`level ${newLevelId} loaded [${newDetails.startSN},${newDetails.endSN}],duration:${duration}`);
  769.  
  770. if (newDetails.live) {
  771. let curDetails = curLevel.details;
  772. if (curDetails && newDetails.fragments.length > 0) {
  773. // we already have details for that level, merge them
  774. LevelHelper.mergeDetails(curDetails, newDetails);
  775. sliding = newDetails.fragments[0].start;
  776. this.liveSyncPosition = this.computeLivePosition(sliding, curDetails);
  777. if (newDetails.PTSKnown && Number.isFinite(sliding)) {
  778. logger.log(`live playlist sliding:${sliding.toFixed(3)}`);
  779. } else {
  780. logger.log('live playlist - outdated PTS, unknown sliding');
  781. alignStream(this.fragPrevious, lastLevel, newDetails);
  782. }
  783. } else {
  784. logger.log('live playlist - first load, unknown sliding');
  785. newDetails.PTSKnown = false;
  786. alignStream(this.fragPrevious, lastLevel, newDetails);
  787. }
  788. } else {
  789. newDetails.PTSKnown = false;
  790. }
  791. // override level info
  792. curLevel.details = newDetails;
  793. this.levelLastLoaded = newLevelId;
  794. this.hls.trigger(Event.LEVEL_UPDATED, { details: newDetails, level: newLevelId });
  795.  
  796. if (this.startFragRequested === false) {
  797. // compute start position if set to -1. use it straight away if value is defined
  798. if (this.startPosition === -1 || this.lastCurrentTime === -1) {
  799. // first, check if start time offset has been set in playlist, if yes, use this value
  800. let startTimeOffset = newDetails.startTimeOffset;
  801. if (Number.isFinite(startTimeOffset)) {
  802. if (startTimeOffset < 0) {
  803. logger.log(`negative start time offset ${startTimeOffset}, count from end of last fragment`);
  804. startTimeOffset = sliding + duration + startTimeOffset;
  805. }
  806. logger.log(`start time offset found in playlist, adjust startPosition to ${startTimeOffset}`);
  807. this.startPosition = startTimeOffset;
  808. } else {
  809. // if live playlist, set start position to be fragment N-this.config.liveSyncDurationCount (usually 3)
  810. if (newDetails.live) {
  811. this.startPosition = this.computeLivePosition(sliding, newDetails);
  812. logger.log(`configure startPosition to ${this.startPosition}`);
  813. } else {
  814. this.startPosition = 0;
  815. }
  816. }
  817. this.lastCurrentTime = this.startPosition;
  818. }
  819. this.nextLoadPosition = this.startPosition;
  820. }
  821. // only switch batck to IDLE state if we were waiting for level to start downloading a new fragment
  822. if (this.state === State.WAITING_LEVEL) {
  823. this.state = State.IDLE;
  824. }
  825.  
  826. // trigger handler right now
  827. this.tick();
  828. }
  829.  
  830. onKeyLoaded () {
  831. if (this.state === State.KEY_LOADING) {
  832. this.state = State.IDLE;
  833. this.tick();
  834. }
  835. }
  836.  
  837. onFragLoaded (data) {
  838. const { fragCurrent, hls, levels, media } = this;
  839. const fragLoaded = data.frag;
  840. if (this.state === State.FRAG_LOADING &&
  841. fragCurrent &&
  842. fragLoaded.type === 'main' &&
  843. fragLoaded.level === fragCurrent.level &&
  844. fragLoaded.sn === fragCurrent.sn) {
  845. const stats = data.stats;
  846. const currentLevel = levels[fragCurrent.level];
  847. const details = currentLevel.details;
  848. // reset frag bitrate test in any case after frag loaded event
  849. // if this frag was loaded to perform a bitrate test AND if hls.nextLoadLevel is greater than 0
  850. // then this means that we should be able to load a fragment at a higher quality level
  851. this.bitrateTest = false;
  852. this.stats = stats;
  853.  
  854. logger.log(`Loaded ${fragCurrent.sn} of [${details.startSN} ,${details.endSN}],level ${fragCurrent.level}`);
  855. if (fragLoaded.bitrateTest && hls.nextLoadLevel) {
  856. // switch back to IDLE state ... we just loaded a fragment to determine adequate start bitrate and initialize autoswitch algo
  857. this.state = State.IDLE;
  858. this.startFragRequested = false;
  859. stats.tparsed = stats.tbuffered = window.performance.now();
  860. hls.trigger(Event.FRAG_BUFFERED, { stats: stats, frag: fragCurrent, id: 'main' });
  861. this.tick();
  862. } else if (fragLoaded.sn === 'initSegment') {
  863. this.state = State.IDLE;
  864. stats.tparsed = stats.tbuffered = window.performance.now();
  865. details.initSegment.data = data.payload;
  866. hls.trigger(Event.FRAG_BUFFERED, { stats: stats, frag: fragCurrent, id: 'main' });
  867. this.tick();
  868. } else {
  869. logger.log(`Parsing ${fragCurrent.sn} of [${details.startSN} ,${details.endSN}],level ${fragCurrent.level}, cc ${fragCurrent.cc}`);
  870. this.state = State.PARSING;
  871. this.pendingBuffering = true;
  872. this.appended = false;
  873.  
  874. // Bitrate test frags are not usually buffered so the fragment tracker ignores them. If Hls.js decides to buffer
  875. // it (and therefore ends up at this line), then the fragment tracker needs to be manually informed.
  876. if (fragLoaded.bitrateTest) {
  877. fragLoaded.bitrateTest = false;
  878. this.fragmentTracker.onFragLoaded({
  879. frag: fragLoaded
  880. });
  881. }
  882.  
  883. // time Offset is accurate if level PTS is known, or if playlist is not sliding (not live) and if media is not seeking (this is to overcome potential timestamp drifts between playlists and fragments)
  884. const accurateTimeOffset = !(media && media.seeking) && (details.PTSKnown || !details.live);
  885. const initSegmentData = details.initSegment ? details.initSegment.data : [];
  886. const audioCodec = this._getAudioCodec(currentLevel);
  887.  
  888. // transmux the MPEG-TS data to ISO-BMFF segments
  889. const demuxer = this.demuxer = this.demuxer || new Demuxer(this.hls, 'main');
  890. demuxer.push(
  891. data.payload,
  892. initSegmentData,
  893. audioCodec,
  894. currentLevel.videoCodec,
  895. fragCurrent,
  896. details.totalduration,
  897. accurateTimeOffset
  898. );
  899. }
  900. }
  901. this.fragLoadError = 0;
  902. }
  903.  
  904. onFragParsingInitSegment (data) {
  905. const fragCurrent = this.fragCurrent;
  906. const fragNew = data.frag;
  907.  
  908. if (fragCurrent &&
  909. data.id === 'main' &&
  910. fragNew.sn === fragCurrent.sn &&
  911. fragNew.level === fragCurrent.level &&
  912. this.state === State.PARSING) {
  913. let tracks = data.tracks, trackName, track;
  914.  
  915. // if audio track is expected to come from audio stream controller, discard any coming from main
  916. if (tracks.audio && this.altAudio) {
  917. delete tracks.audio;
  918. }
  919.  
  920. // include levelCodec in audio and video tracks
  921. track = tracks.audio;
  922. if (track) {
  923. let audioCodec = this.levels[this.level].audioCodec,
  924. ua = navigator.userAgent.toLowerCase();
  925. if (audioCodec && this.audioCodecSwap) {
  926. logger.log('swapping playlist audio codec');
  927. if (audioCodec.indexOf('mp4a.40.5') !== -1) {
  928. audioCodec = 'mp4a.40.2';
  929. } else {
  930. audioCodec = 'mp4a.40.5';
  931. }
  932. }
  933. // in case AAC and HE-AAC audio codecs are signalled in manifest
  934. // force HE-AAC , as it seems that most browsers prefers that way,
  935. // except for mono streams OR on FF
  936. // these conditions might need to be reviewed ...
  937. if (this.audioCodecSwitch) {
  938. // don't force HE-AAC if mono stream
  939. if (track.metadata.channelCount !== 1 &&
  940. // don't force HE-AAC if firefox
  941. ua.indexOf('firefox') === -1) {
  942. audioCodec = 'mp4a.40.5';
  943. }
  944. }
  945. // HE-AAC is broken on Android, always signal audio codec as AAC even if variant manifest states otherwise
  946. if (ua.indexOf('android') !== -1 && track.container !== 'audio/mpeg') { // Exclude mpeg audio
  947. audioCodec = 'mp4a.40.2';
  948. logger.log(`Android: force audio codec to ${audioCodec}`);
  949. }
  950. track.levelCodec = audioCodec;
  951. track.id = data.id;
  952. }
  953. track = tracks.video;
  954. if (track) {
  955. track.levelCodec = this.levels[this.level].videoCodec;
  956. track.id = data.id;
  957. }
  958. this.hls.trigger(Event.BUFFER_CODECS, tracks);
  959. // loop through tracks that are going to be provided to bufferController
  960. for (trackName in tracks) {
  961. track = tracks[trackName];
  962. logger.log(`main track:${trackName},container:${track.container},codecs[level/parsed]=[${track.levelCodec}/${track.codec}]`);
  963. let initSegment = track.initSegment;
  964. if (initSegment) {
  965. this.appended = true;
  966. // arm pending Buffering flag before appending a segment
  967. this.pendingBuffering = true;
  968. this.hls.trigger(Event.BUFFER_APPENDING, { type: trackName, data: initSegment, parent: 'main', content: 'initSegment' });
  969. }
  970. }
  971. // trigger handler right now
  972. this.tick();
  973. }
  974. }
  975.  
  976. onFragParsingData (data) {
  977. const fragCurrent = this.fragCurrent;
  978. const fragNew = data.frag;
  979. if (fragCurrent &&
  980. data.id === 'main' &&
  981. fragNew.sn === fragCurrent.sn &&
  982. fragNew.level === fragCurrent.level &&
  983. !(data.type === 'audio' && this.altAudio) && // filter out main audio if audio track is loaded through audio stream controller
  984. this.state === State.PARSING) {
  985. let level = this.levels[this.level],
  986. frag = fragCurrent;
  987. if (!Number.isFinite(data.endPTS)) {
  988. data.endPTS = data.startPTS + fragCurrent.duration;
  989. data.endDTS = data.startDTS + fragCurrent.duration;
  990. }
  991.  
  992. if (data.hasAudio === true) {
  993. frag.addElementaryStream(ElementaryStreamTypes.AUDIO);
  994. }
  995.  
  996. if (data.hasVideo === true) {
  997. frag.addElementaryStream(ElementaryStreamTypes.VIDEO);
  998. }
  999.  
  1000. logger.log(`Parsed ${data.type},PTS:[${data.startPTS.toFixed(3)},${data.endPTS.toFixed(3)}],DTS:[${data.startDTS.toFixed(3)}/${data.endDTS.toFixed(3)}],nb:${data.nb},dropped:${data.dropped || 0}`);
  1001.  
  1002. // Detect gaps in a fragment and try to fix it by finding a keyframe in the previous fragment (see _findFragments)
  1003. if (data.type === 'video') {
  1004. frag.dropped = data.dropped;
  1005. if (frag.dropped) {
  1006. if (!frag.backtracked) {
  1007. const levelDetails = level.details;
  1008. if (levelDetails && frag.sn === levelDetails.startSN) {
  1009. logger.warn('missing video frame(s) on first frag, appending with gap', frag.sn);
  1010. } else {
  1011. logger.warn('missing video frame(s), backtracking fragment', frag.sn);
  1012. // Return back to the IDLE state without appending to buffer
  1013. // Causes findFragments to backtrack a segment and find the keyframe
  1014. // Audio fragments arriving before video sets the nextLoadPosition, causing _findFragments to skip the backtracked fragment
  1015. this.fragmentTracker.removeFragment(frag);
  1016. frag.backtracked = true;
  1017. this.nextLoadPosition = data.startPTS;
  1018. this.state = State.IDLE;
  1019. this.fragPrevious = frag;
  1020. this.tick();
  1021. return;
  1022. }
  1023. } else {
  1024. logger.warn('Already backtracked on this fragment, appending with the gap', frag.sn);
  1025. }
  1026. } else {
  1027. // Only reset the backtracked flag if we've loaded the frag without any dropped frames
  1028. frag.backtracked = false;
  1029. }
  1030. }
  1031.  
  1032. let drift = LevelHelper.updateFragPTSDTS(level.details, frag, data.startPTS, data.endPTS, data.startDTS, data.endDTS),
  1033. hls = this.hls;
  1034. hls.trigger(Event.LEVEL_PTS_UPDATED, { details: level.details, level: this.level, drift: drift, type: data.type, start: data.startPTS, end: data.endPTS });
  1035. // has remuxer dropped video frames located before first keyframe ?
  1036. [data.data1, data.data2].forEach(buffer => {
  1037. // only append in PARSING state (rationale is that an appending error could happen synchronously on first segment appending)
  1038. // in that case it is useless to append following segments
  1039. if (buffer && buffer.length && this.state === State.PARSING) {
  1040. this.appended = true;
  1041. // arm pending Buffering flag before appending a segment
  1042. this.pendingBuffering = true;
  1043. hls.trigger(Event.BUFFER_APPENDING, { type: data.type, data: buffer, parent: 'main', content: 'data' });
  1044. }
  1045. });
  1046. // trigger handler right now
  1047. this.tick();
  1048. }
  1049. }
  1050.  
  1051. onFragParsed (data) {
  1052. const fragCurrent = this.fragCurrent;
  1053. const fragNew = data.frag;
  1054. if (fragCurrent &&
  1055. data.id === 'main' &&
  1056. fragNew.sn === fragCurrent.sn &&
  1057. fragNew.level === fragCurrent.level &&
  1058. this.state === State.PARSING) {
  1059. this.stats.tparsed = window.performance.now();
  1060. this.state = State.PARSED;
  1061. this._checkAppendedParsed();
  1062. }
  1063. }
  1064.  
  1065. onAudioTrackSwitching (data) {
  1066. // if any URL found on new audio track, it is an alternate audio track
  1067. let altAudio = !!data.url,
  1068. trackId = data.id;
  1069. // if we switch on main audio, ensure that main fragment scheduling is synced with media.buffered
  1070. // don't do anything if we switch to alt audio: audio stream controller is handling it.
  1071. // we will just have to change buffer scheduling on audioTrackSwitched
  1072. if (!altAudio) {
  1073. if (this.mediaBuffer !== this.media) {
  1074. logger.log('switching on main audio, use media.buffered to schedule main fragment loading');
  1075. this.mediaBuffer = this.media;
  1076. let fragCurrent = this.fragCurrent;
  1077. // we need to refill audio buffer from main: cancel any frag loading to speed up audio switch
  1078. if (fragCurrent.loader) {
  1079. logger.log('switching to main audio track, cancel main fragment load');
  1080. fragCurrent.loader.abort();
  1081. }
  1082. this.fragCurrent = null;
  1083. this.fragPrevious = null;
  1084. // destroy demuxer to force init segment generation (following audio switch)
  1085. if (this.demuxer) {
  1086. this.demuxer.destroy();
  1087. this.demuxer = null;
  1088. }
  1089. // switch to IDLE state to load new fragment
  1090. this.state = State.IDLE;
  1091. }
  1092. let hls = this.hls;
  1093. // switching to main audio, flush all audio and trigger track switched
  1094. hls.trigger(Event.BUFFER_FLUSHING, { startOffset: 0, endOffset: Number.POSITIVE_INFINITY, type: 'audio' });
  1095. hls.trigger(Event.AUDIO_TRACK_SWITCHED, { id: trackId });
  1096. this.altAudio = false;
  1097. }
  1098. }
  1099.  
  1100. onAudioTrackSwitched (data) {
  1101. let trackId = data.id,
  1102. altAudio = !!this.hls.audioTracks[trackId].url;
  1103. if (altAudio) {
  1104. let videoBuffer = this.videoBuffer;
  1105. // if we switched on alternate audio, ensure that main fragment scheduling is synced with video sourcebuffer buffered
  1106. if (videoBuffer && this.mediaBuffer !== videoBuffer) {
  1107. logger.log('switching on alternate audio, use video.buffered to schedule main fragment loading');
  1108. this.mediaBuffer = videoBuffer;
  1109. }
  1110. }
  1111. this.altAudio = altAudio;
  1112. this.tick();
  1113. }
  1114.  
  1115. onBufferCreated (data) {
  1116. let tracks = data.tracks, mediaTrack, name, alternate = false;
  1117. for (let type in tracks) {
  1118. let track = tracks[type];
  1119. if (track.id === 'main') {
  1120. name = type;
  1121. mediaTrack = track;
  1122. // keep video source buffer reference
  1123. if (type === 'video') {
  1124. this.videoBuffer = tracks[type].buffer;
  1125. }
  1126. } else {
  1127. alternate = true;
  1128. }
  1129. }
  1130. if (alternate && mediaTrack) {
  1131. logger.log(`alternate track found, use ${name}.buffered to schedule main fragment loading`);
  1132. this.mediaBuffer = mediaTrack.buffer;
  1133. } else {
  1134. this.mediaBuffer = this.media;
  1135. }
  1136. }
  1137.  
  1138. onBufferAppended (data) {
  1139. if (data.parent === 'main') {
  1140. const state = this.state;
  1141. if (state === State.PARSING || state === State.PARSED) {
  1142. // check if all buffers have been appended
  1143. this.pendingBuffering = (data.pending > 0);
  1144. this._checkAppendedParsed();
  1145. }
  1146. }
  1147. }
  1148.  
  1149. _checkAppendedParsed () {
  1150. // trigger handler right now
  1151. if (this.state === State.PARSED && (!this.appended || !this.pendingBuffering)) {
  1152. const frag = this.fragCurrent;
  1153. if (frag) {
  1154. const media = this.mediaBuffer ? this.mediaBuffer : this.media;
  1155. logger.log(`main buffered : ${TimeRanges.toString(media.buffered)}`);
  1156. this.fragPrevious = frag;
  1157. const stats = this.stats;
  1158. stats.tbuffered = window.performance.now();
  1159. // we should get rid of this.fragLastKbps
  1160. this.fragLastKbps = Math.round(8 * stats.total / (stats.tbuffered - stats.tfirst));
  1161. this.hls.trigger(Event.FRAG_BUFFERED, { stats: stats, frag: frag, id: 'main' });
  1162. this.state = State.IDLE;
  1163. }
  1164. // Do not tick when _seekToStartPos needs to be called as seeking to the start can fail on live streams at this point
  1165. if (this.loadedmetadata || this.startPosition <= 0) {
  1166. this.tick();
  1167. }
  1168. }
  1169. }
  1170.  
  1171. onError (data) {
  1172. let frag = data.frag || this.fragCurrent;
  1173. // don't handle frag error not related to main fragment
  1174. if (frag && frag.type !== 'main') {
  1175. return;
  1176. }
  1177.  
  1178. // 0.5 : tolerance needed as some browsers stalls playback before reaching buffered end
  1179. let mediaBuffered = !!this.media && BufferHelper.isBuffered(this.media, this.media.currentTime) && BufferHelper.isBuffered(this.media, this.media.currentTime + 0.5);
  1180.  
  1181. switch (data.details) {
  1182. case ErrorDetails.FRAG_LOAD_ERROR:
  1183. case ErrorDetails.FRAG_LOAD_TIMEOUT:
  1184. case ErrorDetails.KEY_LOAD_ERROR:
  1185. case ErrorDetails.KEY_LOAD_TIMEOUT:
  1186. if (!data.fatal) {
  1187. // keep retrying until the limit will be reached
  1188. if ((this.fragLoadError + 1) <= this.config.fragLoadingMaxRetry) {
  1189. // exponential backoff capped to config.fragLoadingMaxRetryTimeout
  1190. let delay = Math.min(Math.pow(2, this.fragLoadError) * this.config.fragLoadingRetryDelay, this.config.fragLoadingMaxRetryTimeout);
  1191. logger.warn(`mediaController: frag loading failed, retry in ${delay} ms`);
  1192. this.retryDate = window.performance.now() + delay;
  1193. // retry loading state
  1194. // if loadedmetadata is not set, it means that we are emergency switch down on first frag
  1195. // in that case, reset startFragRequested flag
  1196. if (!this.loadedmetadata) {
  1197. this.startFragRequested = false;
  1198. this.nextLoadPosition = this.startPosition;
  1199. }
  1200. this.fragLoadError++;
  1201. this.state = State.FRAG_LOADING_WAITING_RETRY;
  1202. } else {
  1203. logger.error(`mediaController: ${data.details} reaches max retry, redispatch as fatal ...`);
  1204. // switch error to fatal
  1205. data.fatal = true;
  1206. this.state = State.ERROR;
  1207. }
  1208. }
  1209. break;
  1210. case ErrorDetails.LEVEL_LOAD_ERROR:
  1211. case ErrorDetails.LEVEL_LOAD_TIMEOUT:
  1212. if (this.state !== State.ERROR) {
  1213. if (data.fatal) {
  1214. // if fatal error, stop processing
  1215. this.state = State.ERROR;
  1216. logger.warn(`streamController: ${data.details},switch to ${this.state} state ...`);
  1217. } else {
  1218. // in case of non fatal error while loading level, if level controller is not retrying to load level , switch back to IDLE
  1219. if (!data.levelRetry && this.state === State.WAITING_LEVEL) {
  1220. this.state = State.IDLE;
  1221. }
  1222. }
  1223. }
  1224. break;
  1225. case ErrorDetails.BUFFER_FULL_ERROR:
  1226. // if in appending state
  1227. if (data.parent === 'main' && (this.state === State.PARSING || this.state === State.PARSED)) {
  1228. // reduce max buf len if current position is buffered
  1229. if (mediaBuffered) {
  1230. this._reduceMaxBufferLength(this.config.maxBufferLength);
  1231. this.state = State.IDLE;
  1232. } else {
  1233. // current position is not buffered, but browser is still complaining about buffer full error
  1234. // this happens on IE/Edge, refer to https://github.com/video-dev/hls.js/pull/708
  1235. // in that case flush the whole buffer to recover
  1236. logger.warn('buffer full error also media.currentTime is not buffered, flush everything');
  1237. this.fragCurrent = null;
  1238. // flush everything
  1239. this.flushMainBuffer(0, Number.POSITIVE_INFINITY);
  1240. }
  1241. }
  1242. break;
  1243. default:
  1244. break;
  1245. }
  1246. }
  1247.  
  1248. _reduceMaxBufferLength (minLength) {
  1249. let config = this.config;
  1250. if (config.maxMaxBufferLength >= minLength) {
  1251. // reduce max buffer length as it might be too high. we do this to avoid loop flushing ...
  1252. config.maxMaxBufferLength /= 2;
  1253. logger.warn(`main:reduce max buffer length to ${config.maxMaxBufferLength}s`);
  1254. return true;
  1255. }
  1256. return false;
  1257. }
  1258.  
  1259. /**
  1260. * Checks the health of the buffer and attempts to resolve playback stalls.
  1261. * @private
  1262. */
  1263. _checkBuffer () {
  1264. const { media } = this;
  1265. if (!media || media.readyState === 0) {
  1266. // Exit early if we don't have media or if the media hasn't bufferd anything yet (readyState 0)
  1267. return;
  1268. }
  1269.  
  1270. const mediaBuffer = this.mediaBuffer ? this.mediaBuffer : media;
  1271. const buffered = mediaBuffer.buffered;
  1272.  
  1273. if (!this.loadedmetadata && buffered.length) {
  1274. this.loadedmetadata = true;
  1275. this._seekToStartPos();
  1276. } else if (this.immediateSwitch) {
  1277. this.immediateLevelSwitchEnd();
  1278. } else {
  1279. this.gapController.poll(this.lastCurrentTime, buffered);
  1280. }
  1281. }
  1282.  
  1283. onFragLoadEmergencyAborted () {
  1284. this.state = State.IDLE;
  1285. // if loadedmetadata is not set, it means that we are emergency switch down on first frag
  1286. // in that case, reset startFragRequested flag
  1287. if (!this.loadedmetadata) {
  1288. this.startFragRequested = false;
  1289. this.nextLoadPosition = this.startPosition;
  1290. }
  1291. this.tick();
  1292. }
  1293.  
  1294. onBufferFlushed () {
  1295. /* after successful buffer flushing, filter flushed fragments from bufferedFrags
  1296. use mediaBuffered instead of media (so that we will check against video.buffered ranges in case of alt audio track)
  1297. */
  1298. const media = this.mediaBuffer ? this.mediaBuffer : this.media;
  1299. if (media) {
  1300. // filter fragments potentially evicted from buffer. this is to avoid memleak on live streams
  1301. this.fragmentTracker.detectEvictedFragments(ElementaryStreamTypes.VIDEO, media.buffered);
  1302. }
  1303. // move to IDLE once flush complete. this should trigger new fragment loading
  1304. this.state = State.IDLE;
  1305. // reset reference to frag
  1306. this.fragPrevious = null;
  1307. }
  1308.  
  1309. onLevelsUpdated (data) {
  1310. this.levels = data.levels;
  1311. }
  1312.  
  1313. swapAudioCodec () {
  1314. this.audioCodecSwap = !this.audioCodecSwap;
  1315. }
  1316. /**
  1317. * Seeks to the set startPosition if not equal to the mediaElement's current time.
  1318. * @private
  1319. */
  1320. _seekToStartPos () {
  1321. const { media, startPosition } = this;
  1322. const currentTime = media.currentTime;
  1323. // only adjust currentTime if different from startPosition or if startPosition not buffered
  1324. // at that stage, there should be only one buffered range, as we reach that code after first fragment has been buffered
  1325. if (currentTime !== startPosition && startPosition >= 0) {
  1326. if (media.seeking) {
  1327. logger.log(`could not seek to ${startPosition}, already seeking at ${currentTime}`);
  1328. return;
  1329. }
  1330. logger.log(`seek to target start position ${startPosition} from current time ${currentTime}. ready state ${media.readyState}`);
  1331. media.currentTime = startPosition;
  1332. }
  1333. }
  1334.  
  1335. _getAudioCodec (currentLevel) {
  1336. let audioCodec = this.config.defaultAudioCodec || currentLevel.audioCodec;
  1337. if (this.audioCodecSwap) {
  1338. logger.log('swapping playlist audio codec');
  1339. if (audioCodec) {
  1340. if (audioCodec.indexOf('mp4a.40.5') !== -1) {
  1341. audioCodec = 'mp4a.40.2';
  1342. } else {
  1343. audioCodec = 'mp4a.40.5';
  1344. }
  1345. }
  1346. }
  1347.  
  1348. return audioCodec;
  1349. }
  1350.  
  1351. get liveSyncPosition () {
  1352. return this._liveSyncPosition;
  1353. }
  1354.  
  1355. set liveSyncPosition (value) {
  1356. this._liveSyncPosition = value;
  1357. }
  1358. }
  1359. export default StreamController;