Home Reference Source

src/utils/texttrack-utils.ts

  1.  
  2. export function sendAddTrackEvent (track: TextTrack, videoEl: HTMLMediaElement) {
  3. let event: Event;
  4. try {
  5. event = new Event('addtrack');
  6. } catch (err) {
  7. // for IE11
  8. event = document.createEvent('Event');
  9. event.initEvent('addtrack', false, false);
  10. }
  11. (event as any).track = track;
  12. videoEl.dispatchEvent(event);
  13. }
  14.  
  15. export function clearCurrentCues (track: TextTrack) {
  16. if (track && track.cues) {
  17. while (track.cues.length > 0) {
  18. track.removeCue(track.cues[0]);
  19. }
  20. }
  21. }
  22.  
  23. /**
  24. * Given a list of Cues, finds the closest cue matching the given time.
  25. * Modified verison of binary search O(log(n)).
  26. *
  27. * @export
  28. * @param {(TextTrackCueList | TextTrackCue[])} cues - List of cues.
  29. * @param {number} time - Target time, to find closest cue to.
  30. * @returns {TextTrackCue}
  31. */
  32. export function getClosestCue (cues: TextTrackCueList | TextTrackCue[], time: number): TextTrackCue {
  33. // If the offset is less than the first element, the first element is the closest.
  34. if (time < cues[0].endTime) {
  35. return cues[0];
  36. }
  37. // If the offset is greater than the last cue, the last is the closest.
  38. if (time > cues[cues.length - 1].endTime) {
  39. return cues[cues.length - 1];
  40. }
  41.  
  42. let left = 0;
  43. let right = cues.length - 1;
  44.  
  45. while (left <= right) {
  46. const mid = Math.floor((right + left) / 2);
  47.  
  48. if (time < cues[mid].endTime) {
  49. right = mid - 1;
  50. } else if (time > cues[mid].endTime) {
  51. left = mid + 1;
  52. } else {
  53. // If it's not lower or higher, it must be equal.
  54. return cues[mid];
  55. }
  56. }
  57. // At this point, left and right have swapped.
  58. // No direct match was found, left or right element must be the closest. Check which one has the smallest diff.
  59. return (cues[left].endTime - time) < (time - cues[right].endTime) ? cues[left] : cues[right];
  60. }