Home Reference Source

src/controller/timeline-controller.ts

  1. import Event from '../events';
  2. import EventHandler from '../event-handler';
  3. import Cea608Parser, { CaptionScreen } from '../utils/cea-608-parser';
  4. import OutputFilter from '../utils/output-filter';
  5. import WebVTTParser from '../utils/webvtt-parser';
  6. import { logger } from '../utils/logger';
  7. import { sendAddTrackEvent, clearCurrentCues } from '../utils/texttrack-utils';
  8. import Fragment from '../loader/fragment';
  9. import { HlsConfig } from '../config';
  10. import { CuesInterface } from '../utils/cues';
  11. import { MediaPlaylist } from '../types/media-playlist';
  12.  
  13. type TrackProperties = {
  14. label: string,
  15. languageCode: string,
  16. media?: MediaPlaylist
  17. };
  18.  
  19. type NonNativeCaptionsTrack = {
  20. _id?: string,
  21. label: string,
  22. kind: string,
  23. default: boolean,
  24. closedCaptions?: MediaPlaylist,
  25. subtitleTrack?: MediaPlaylist
  26. };
  27.  
  28. type VTTCCs = {
  29. ccOffset: number,
  30. presentationOffset: number,
  31. [key: number]: {
  32. start: number,
  33. prevCC: number,
  34. new: boolean
  35. }
  36. };
  37.  
  38. class TimelineController extends EventHandler {
  39. private media: HTMLMediaElement | null = null;
  40. private config: HlsConfig;
  41. private enabled: boolean = true;
  42. private Cues: CuesInterface;
  43. private textTracks: Array<TextTrack> = [];
  44. private tracks: Array<MediaPlaylist> = [];
  45. private initPTS: Array<number> = [];
  46. private unparsedVttFrags: Array<{ frag: Fragment, payload: ArrayBuffer }> = [];
  47. private cueRanges: Array<[number, number]> = [];
  48. private captionsTracks: Record<string, TextTrack> = {};
  49. private nonNativeCaptionsTracks: Record<string, NonNativeCaptionsTrack> = {};
  50. private captionsProperties: {
  51. textTrack1: TrackProperties
  52. textTrack2: TrackProperties
  53. textTrack3: TrackProperties
  54. textTrack4: TrackProperties
  55. };
  56. private readonly cea608Parser!: Cea608Parser;
  57. private lastSn: number = -1;
  58. private prevCC: number = -1;
  59. private vttCCs: VTTCCs = newVTTCCs();
  60.  
  61. constructor (hls) {
  62. super(hls,
  63. Event.MEDIA_ATTACHING,
  64. Event.MEDIA_DETACHING,
  65. Event.FRAG_PARSING_USERDATA,
  66. Event.FRAG_DECRYPTED,
  67. Event.MANIFEST_LOADING,
  68. Event.MANIFEST_LOADED,
  69. Event.FRAG_LOADED,
  70. Event.INIT_PTS_FOUND);
  71.  
  72. this.hls = hls;
  73. this.config = hls.config;
  74. this.Cues = hls.config.cueHandler;
  75.  
  76. this.captionsProperties = {
  77. textTrack1: {
  78. label: this.config.captionsTextTrack1Label,
  79. languageCode: this.config.captionsTextTrack1LanguageCode
  80. },
  81. textTrack2: {
  82. label: this.config.captionsTextTrack2Label,
  83. languageCode: this.config.captionsTextTrack2LanguageCode
  84. },
  85. textTrack3: {
  86. label: this.config.captionsTextTrack3Label,
  87. languageCode: this.config.captionsTextTrack3LanguageCode
  88. },
  89. textTrack4: {
  90. label: this.config.captionsTextTrack4Label,
  91. languageCode: this.config.captionsTextTrack4LanguageCode
  92. }
  93. };
  94.  
  95. if (this.config.enableCEA708Captions) {
  96. const channel1 = new OutputFilter(this, 'textTrack1');
  97. const channel2 = new OutputFilter(this, 'textTrack2');
  98. const channel3 = new OutputFilter(this, 'textTrack3');
  99. const channel4 = new OutputFilter(this, 'textTrack4');
  100. this.cea608Parser = new Cea608Parser(channel1, channel2, channel3, channel4);
  101. }
  102. }
  103.  
  104. addCues (trackName: string, startTime: number, endTime: number, screen: CaptionScreen) {
  105. // skip cues which overlap more than 50% with previously parsed time ranges
  106. const ranges = this.cueRanges;
  107. let merged = false;
  108. for (let i = ranges.length; i--;) {
  109. let cueRange = ranges[i];
  110. let overlap = intersection(cueRange[0], cueRange[1], startTime, endTime);
  111. if (overlap >= 0) {
  112. cueRange[0] = Math.min(cueRange[0], startTime);
  113. cueRange[1] = Math.max(cueRange[1], endTime);
  114. merged = true;
  115. if ((overlap / (endTime - startTime)) > 0.5) {
  116. return;
  117. }
  118. }
  119. }
  120. if (!merged) {
  121. ranges.push([startTime, endTime]);
  122. }
  123.  
  124. if (this.config.renderTextTracksNatively) {
  125. this.Cues.newCue(this.captionsTracks[trackName], startTime, endTime, screen);
  126. } else {
  127. const cues = this.Cues.newCue(null, startTime, endTime, screen);
  128. this.hls.trigger(Event.CUES_PARSED, { type: 'captions', cues, track: trackName });
  129. }
  130. }
  131.  
  132. // Triggered when an initial PTS is found; used for synchronisation of WebVTT.
  133. onInitPtsFound (data: { id: string, frag: Fragment, initPTS: number}) {
  134. const { frag, id, initPTS } = data;
  135. const { unparsedVttFrags } = this;
  136. if (id === 'main') {
  137. this.initPTS[frag.cc] = initPTS;
  138. }
  139.  
  140. // Due to asynchronous processing, initial PTS may arrive later than the first VTT fragments are loaded.
  141. // Parse any unparsed fragments upon receiving the initial PTS.
  142. if (unparsedVttFrags.length) {
  143. this.unparsedVttFrags = [];
  144. unparsedVttFrags.forEach(frag => {
  145. this.onFragLoaded(frag);
  146. });
  147. }
  148. }
  149.  
  150. getExistingTrack (trackName: string): TextTrack | null {
  151. const { media } = this;
  152. if (media) {
  153. for (let i = 0; i < media.textTracks.length; i++) {
  154. let textTrack = media.textTracks[i];
  155. if (textTrack[trackName]) {
  156. return textTrack;
  157. }
  158. }
  159. }
  160. return null;
  161. }
  162.  
  163. createCaptionsTrack (trackName: string) {
  164. if (this.config.renderTextTracksNatively) {
  165. this.createNativeTrack(trackName);
  166. } else {
  167. this.createNonNativeTrack(trackName);
  168. }
  169. }
  170.  
  171. createNativeTrack (trackName: string) {
  172. if (this.captionsTracks[trackName]) {
  173. return;
  174. }
  175. const { captionsProperties, captionsTracks, media } = this;
  176. const { label, languageCode } = captionsProperties[trackName];
  177. // Enable reuse of existing text track.
  178. const existingTrack = this.getExistingTrack(trackName);
  179. if (!existingTrack) {
  180. const textTrack = this.createTextTrack('captions', label, languageCode);
  181. if (textTrack) {
  182. // Set a special property on the track so we know it's managed by Hls.js
  183. textTrack[trackName] = true;
  184. captionsTracks[trackName] = textTrack;
  185. }
  186. } else {
  187. captionsTracks[trackName] = existingTrack;
  188. clearCurrentCues(captionsTracks[trackName]);
  189. sendAddTrackEvent(captionsTracks[trackName], media as HTMLMediaElement);
  190. }
  191. }
  192.  
  193. createNonNativeTrack (trackName: string) {
  194. // Create a list of a single track for the provider to consume
  195. const trackProperties: TrackProperties = this.captionsProperties[trackName];
  196. if (!trackProperties) {
  197. return;
  198. }
  199. const label = trackProperties.label as string;
  200. const track = {
  201. _id: trackName,
  202. label,
  203. kind: 'captions',
  204. default: trackProperties.media ? !!trackProperties.media.default : false,
  205. closedCaptions: trackProperties.media
  206. };
  207. this.nonNativeCaptionsTracks[trackName] = track;
  208. this.hls.trigger(Event.NON_NATIVE_TEXT_TRACKS_FOUND, { tracks: [track] });
  209. }
  210. createTextTrack (kind: TextTrackKind, label: string, lang?: string): TextTrack | undefined {
  211. const media = this.media;
  212. if (!media) {
  213. return;
  214. }
  215. return media.addTextTrack(kind, label, lang);
  216. }
  217.  
  218. destroy () {
  219. super.destroy();
  220. }
  221.  
  222. onMediaAttaching (data: { media: HTMLMediaElement }) {
  223. this.media = data.media;
  224. this._cleanTracks();
  225. }
  226.  
  227. onMediaDetaching () {
  228. const { captionsTracks } = this;
  229. Object.keys(captionsTracks).forEach(trackName => {
  230. clearCurrentCues(captionsTracks[trackName]);
  231. delete captionsTracks[trackName];
  232. });
  233. this.nonNativeCaptionsTracks = {};
  234. }
  235.  
  236. onManifestLoading () {
  237. this.lastSn = -1; // Detect discontiguity in fragment parsing
  238. this.prevCC = -1;
  239. this.vttCCs = newVTTCCs(); // Detect discontinuity in subtitle manifests
  240. this._cleanTracks();
  241. this.tracks = [];
  242. this.captionsTracks = {};
  243. this.nonNativeCaptionsTracks = {};
  244. }
  245.  
  246. _cleanTracks () {
  247. // clear outdated subtitles
  248. const { media } = this;
  249. if (!media) {
  250. return;
  251. }
  252. const textTracks = media.textTracks;
  253. if (textTracks) {
  254. for (let i = 0; i < textTracks.length; i++) {
  255. clearCurrentCues(textTracks[i]);
  256. }
  257. }
  258. }
  259.  
  260. onManifestLoaded (data: { subtitles: Array<MediaPlaylist>, captions: Array<MediaPlaylist> }) {
  261. this.textTracks = [];
  262. this.unparsedVttFrags = this.unparsedVttFrags || [];
  263. this.initPTS = [];
  264. this.cueRanges = [];
  265.  
  266. if (this.config.enableWebVTT) {
  267. const tracks = data.subtitles || [];
  268. const sameTracks = this.tracks && tracks && this.tracks.length === tracks.length;
  269. this.tracks = data.subtitles || [];
  270.  
  271. if (this.config.renderTextTracksNatively) {
  272. const inUseTracks = this.media ? this.media.textTracks : [];
  273.  
  274. this.tracks.forEach((track, index) => {
  275. let textTrack;
  276. if (index < inUseTracks.length) {
  277. let inUseTrack: TextTrack | null = null;
  278.  
  279. for (let i = 0; i < inUseTracks.length; i++) {
  280. if (canReuseVttTextTrack(inUseTracks[i], track)) {
  281. inUseTrack = inUseTracks[i];
  282. break;
  283. }
  284. }
  285.  
  286. // Reuse tracks with the same label, but do not reuse 608/708 tracks
  287. if (inUseTrack) {
  288. textTrack = inUseTrack;
  289. }
  290. }
  291. if (!textTrack) {
  292. textTrack = this.createTextTrack('subtitles', track.name, track.lang);
  293. }
  294.  
  295. if (track.default) {
  296. textTrack.mode = this.hls.subtitleDisplay ? 'showing' : 'hidden';
  297. } else {
  298. textTrack.mode = 'disabled';
  299. }
  300.  
  301. this.textTracks.push(textTrack);
  302. });
  303. } else if (!sameTracks && this.tracks && this.tracks.length) {
  304. // Create a list of tracks for the provider to consume
  305. const tracksList = this.tracks.map((track) => {
  306. return {
  307. label: track.name,
  308. kind: track.type.toLowerCase(),
  309. default: track.default,
  310. subtitleTrack: track
  311. };
  312. });
  313. this.hls.trigger(Event.NON_NATIVE_TEXT_TRACKS_FOUND, { tracks: tracksList });
  314. }
  315. }
  316.  
  317. if (this.config.enableCEA708Captions && data.captions) {
  318. data.captions.forEach(captionsTrack => {
  319. const instreamIdMatch = /(?:CC|SERVICE)([1-4])/.exec(captionsTrack.instreamId as string);
  320. if (!instreamIdMatch) {
  321. return;
  322. }
  323. const trackName = `textTrack${instreamIdMatch[1]}`;
  324. const trackProperties: TrackProperties = this.captionsProperties[trackName];
  325. if (!trackProperties) {
  326. return;
  327. }
  328. trackProperties.label = captionsTrack.name;
  329. if (captionsTrack.lang) { // optional attribute
  330. trackProperties.languageCode = captionsTrack.lang;
  331. }
  332. trackProperties.media = captionsTrack;
  333. });
  334. }
  335. }
  336.  
  337. onFragLoaded (data: { frag: Fragment, payload: ArrayBuffer }) {
  338. const { frag, payload } = data;
  339. const { cea608Parser, initPTS, lastSn, unparsedVttFrags } = this;
  340. if (frag.type === 'main') {
  341. const sn = frag.sn;
  342. // if this frag isn't contiguous, clear the parser so cues with bad start/end times aren't added to the textTrack
  343. if (frag.sn !== lastSn + 1) {
  344. if (cea608Parser) {
  345. cea608Parser.reset();
  346. }
  347. }
  348. this.lastSn = sn as number;
  349. } // eslint-disable-line brace-style
  350. // If fragment is subtitle type, parse as WebVTT.
  351. else if (frag.type === 'subtitle') {
  352. if (payload.byteLength) {
  353. // We need an initial synchronisation PTS. Store fragments as long as none has arrived.
  354. if (!Number.isFinite(initPTS[frag.cc])) {
  355. unparsedVttFrags.push(data);
  356. if (initPTS.length) {
  357. // finish unsuccessfully, otherwise the subtitle-stream-controller could be blocked from loading new frags.
  358. this.hls.trigger(Event.SUBTITLE_FRAG_PROCESSED, { success: false, frag });
  359. }
  360. return;
  361. }
  362.  
  363. let decryptData = frag.decryptdata;
  364. // If the subtitles are not encrypted, parse VTTs now. Otherwise, we need to wait.
  365. if ((decryptData == null) || (decryptData.key == null) || (decryptData.method !== 'AES-128')) {
  366. this._parseVTTs(frag, payload);
  367. }
  368. } else {
  369. // In case there is no payload, finish unsuccessfully.
  370. this.hls.trigger(Event.SUBTITLE_FRAG_PROCESSED, { success: false, frag });
  371. }
  372. }
  373. }
  374.  
  375. _parseVTTs (frag: Fragment, payload: ArrayBuffer) {
  376. const { hls, prevCC, textTracks, vttCCs } = this;
  377. if (!vttCCs[frag.cc]) {
  378. vttCCs[frag.cc] = { start: frag.start, prevCC, new: true };
  379. this.prevCC = frag.cc;
  380. }
  381. // Parse the WebVTT file contents.
  382. WebVTTParser.parse(payload, this.initPTS[frag.cc], vttCCs, frag.cc, (cues) => {
  383. if (this.config.renderTextTracksNatively) {
  384. const currentTrack = textTracks[frag.level];
  385. // WebVTTParser.parse is an async method and if the currently selected text track mode is set to "disabled"
  386. // before parsing is done then don't try to access currentTrack.cues.getCueById as cues will be null
  387. // and trying to access getCueById method of cues will throw an exception
  388. if (currentTrack.mode === 'disabled') {
  389. hls.trigger(Event.SUBTITLE_FRAG_PROCESSED, { success: false, frag: frag });
  390. return;
  391. }
  392. // Add cues and trigger event with success true.
  393. cues.forEach(cue => {
  394. // Sometimes there are cue overlaps on segmented vtts so the same
  395. // cue can appear more than once in different vtt files.
  396. // This avoid showing duplicated cues with same timecode and text.
  397. if (!currentTrack.cues.getCueById(cue.id)) {
  398. try {
  399. currentTrack.addCue(cue);
  400. if (!currentTrack.cues.getCueById(cue.id)) {
  401. throw new Error(`addCue is failed for: ${cue}`);
  402. }
  403. } catch (err) {
  404. logger.debug(`Failed occurred on adding cues: ${err}`);
  405. const textTrackCue = new (window as any).TextTrackCue(cue.startTime, cue.endTime, cue.text);
  406. textTrackCue.id = cue.id;
  407. currentTrack.addCue(textTrackCue);
  408. }
  409. }
  410. });
  411. } else {
  412. let trackId = this.tracks[frag.level].default ? 'default' : 'subtitles' + frag.level;
  413. hls.trigger(Event.CUES_PARSED, { type: 'subtitles', cues: cues, track: trackId });
  414. }
  415. hls.trigger(Event.SUBTITLE_FRAG_PROCESSED, { success: true, frag: frag });
  416. },
  417. function (e) {
  418. // Something went wrong while parsing. Trigger event with success false.
  419. logger.log(`Failed to parse VTT cue: ${e}`);
  420. hls.trigger(Event.SUBTITLE_FRAG_PROCESSED, { success: false, frag: frag });
  421. });
  422. }
  423.  
  424. onFragDecrypted (data: { frag: Fragment, payload: any}) {
  425. const { frag, payload } = data;
  426. if (frag.type === 'subtitle') {
  427. if (!Number.isFinite(this.initPTS[frag.cc])) {
  428. this.unparsedVttFrags.push(data);
  429. return;
  430. }
  431.  
  432. this._parseVTTs(frag, payload);
  433. }
  434. }
  435.  
  436. onFragParsingUserdata (data: { samples: Array<any> }) {
  437. if (!this.enabled || !this.cea608Parser) {
  438. return;
  439. }
  440.  
  441. // If the event contains captions (found in the bytes property), push all bytes into the parser immediately
  442. // It will create the proper timestamps based on the PTS value
  443. const cea608Parser = this.cea608Parser;
  444. for (let i = 0; i < data.samples.length; i++) {
  445. const ccBytes = data.samples[i].bytes;
  446. if (ccBytes) {
  447. const ccdatas = this.extractCea608Data(ccBytes);
  448. cea608Parser.addData(data.samples[i].pts, ccdatas[0], 1);
  449. cea608Parser.addData(data.samples[i].pts, ccdatas[1], 3);
  450. }
  451. }
  452. }
  453.  
  454. extractCea608Data (byteArray: Uint8Array): number[][] {
  455. const count = byteArray[0] & 31;
  456. let position = 2;
  457. const actualCCBytes: number[][] = [[], []];
  458.  
  459. for (let j = 0; j < count; j++) {
  460. const tmpByte = byteArray[position++];
  461. const ccbyte1 = 0x7F & byteArray[position++];
  462. const ccbyte2 = 0x7F & byteArray[position++];
  463. const ccValid = (4 & tmpByte) !== 0;
  464. const ccType = 3 & tmpByte;
  465.  
  466. if (ccbyte1 === 0 && ccbyte2 === 0) {
  467. continue;
  468. }
  469.  
  470. if (ccValid) {
  471. if (ccType === 0 || ccType === 1) {
  472. actualCCBytes[ccType].push(ccbyte1);
  473. actualCCBytes[ccType].push(ccbyte2);
  474. }
  475. }
  476. }
  477. return actualCCBytes;
  478. }
  479. }
  480.  
  481. function canReuseVttTextTrack (inUseTrack, manifestTrack): boolean {
  482. return inUseTrack && inUseTrack.label === manifestTrack.name && !(inUseTrack.textTrack1 || inUseTrack.textTrack2);
  483. }
  484.  
  485. function intersection (x1: number, x2: number, y1: number, y2: number): number {
  486. return Math.min(x2, y2) - Math.max(x1, y1);
  487. }
  488.  
  489. function newVTTCCs (): VTTCCs {
  490. return {
  491. ccOffset: 0,
  492. presentationOffset: 0,
  493. 0: {
  494. start: 0,
  495. prevCC: -1,
  496. new: false
  497. }
  498. };
  499. }
  500.  
  501. export default TimelineController;