-
Notifications
You must be signed in to change notification settings - Fork 2.6k
/
Copy pathwebvtt-parser.ts
214 lines (187 loc) · 6.05 KB
/
webvtt-parser.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
import { VTTParser } from './vttparser';
import { utf8ArrayToStr } from '../demux/id3';
import {
RationalTimestamp,
toMpegTsClockFromTimescale,
} from './timescale-conversion';
import { normalizePts } from '../remux/mp4-remuxer';
import type { VTTCCs } from '../types/vtt';
const LINEBREAKS = /\r\n|\n\r|\n|\r/g;
// String.prototype.startsWith is not supported in IE11
const startsWith = function (
inputString: string,
searchString: string,
position: number = 0
) {
return (
inputString.slice(position, position + searchString.length) === searchString
);
};
const cueString2millis = function (timeString: string) {
let ts = parseInt(timeString.slice(-3));
const secs = parseInt(timeString.slice(-6, -4));
const mins = parseInt(timeString.slice(-9, -7));
const hours =
timeString.length > 9
? parseInt(timeString.substring(0, timeString.indexOf(':')))
: 0;
if (
!Number.isFinite(ts) ||
!Number.isFinite(secs) ||
!Number.isFinite(mins) ||
!Number.isFinite(hours)
) {
throw Error(`Malformed X-TIMESTAMP-MAP: Local:${timeString}`);
}
ts += 1000 * secs;
ts += 60 * 1000 * mins;
ts += 60 * 60 * 1000 * hours;
return ts;
};
// From https://github.com/darkskyapp/string-hash
const hash = function (text: string) {
let hash = 5381;
let i = text.length;
while (i) {
hash = (hash * 33) ^ text.charCodeAt(--i);
}
return (hash >>> 0).toString();
};
// Create a unique hash id for a cue based on start/end times and text.
// This helps timeline-controller to avoid showing repeated captions.
export function generateCueId(
startTime: number,
endTime: number,
text: string
) {
return hash(startTime.toString()) + hash(endTime.toString()) + hash(text);
}
const calculateOffset = function (vttCCs: VTTCCs, cc, presentationTime) {
let currCC = vttCCs[cc];
let prevCC = vttCCs[currCC.prevCC];
// This is the first discontinuity or cues have been processed since the last discontinuity
// Offset = current discontinuity time
if (!prevCC || (!prevCC.new && currCC.new)) {
vttCCs.ccOffset = vttCCs.presentationOffset = currCC.start;
currCC.new = false;
return;
}
// There have been discontinuities since cues were last parsed.
// Offset = time elapsed
while (prevCC?.new) {
vttCCs.ccOffset += currCC.start - prevCC.start;
currCC.new = false;
currCC = prevCC;
prevCC = vttCCs[currCC.prevCC];
}
vttCCs.presentationOffset = presentationTime;
};
export function parseWebVTT(
vttByteArray: ArrayBuffer,
initPTS: RationalTimestamp,
vttCCs: VTTCCs,
cc: number,
timeOffset: number,
callBack: (cues: VTTCue[]) => void,
errorCallBack: (error: Error) => void
) {
const parser = new VTTParser();
// Convert byteArray into string, replacing any somewhat exotic linefeeds with "\n", then split on that character.
// Uint8Array.prototype.reduce is not implemented in IE11
const vttLines = utf8ArrayToStr(new Uint8Array(vttByteArray))
.replace(LINEBREAKS, '\n')
.split('\n');
const cues: VTTCue[] = [];
const init90kHz = toMpegTsClockFromTimescale(
initPTS.baseTime,
initPTS.timescale
);
let cueTime = '00:00.000';
let timestampMapMPEGTS = 0;
let timestampMapLOCAL = 0;
let parsingError: Error;
let inHeader = true;
parser.oncue = function (cue: VTTCue) {
// Adjust cue timing; clamp cues to start no earlier than - and drop cues that don't end after - 0 on timeline.
const currCC = vttCCs[cc];
let cueOffset = vttCCs.ccOffset;
// Calculate subtitle PTS offset
const webVttMpegTsMapOffset = (timestampMapMPEGTS - init90kHz) / 90000;
// Update offsets for new discontinuities
if (currCC?.new) {
if (timestampMapLOCAL !== undefined) {
// When local time is provided, offset = discontinuity start time - local time
cueOffset = vttCCs.ccOffset = currCC.start;
} else {
calculateOffset(vttCCs, cc, webVttMpegTsMapOffset);
}
}
if (webVttMpegTsMapOffset) {
// If we have MPEGTS, offset = presentation time + discontinuity offset
cueOffset = webVttMpegTsMapOffset - vttCCs.presentationOffset;
}
const duration = cue.endTime - cue.startTime;
const startTime =
normalizePts(
(cue.startTime + cueOffset - timestampMapLOCAL) * 90000,
timeOffset * 90000
) / 90000;
cue.startTime = Math.max(startTime, 0);
cue.endTime = Math.max(startTime + duration, 0);
//trim trailing webvtt block whitespaces
const text = cue.text;
// Fix encoding of special characters
cue.text = decodeURIComponent(encodeURIComponent(text));
// If the cue was not assigned an id from the VTT file (line above the content), create one.
if (!cue.id) {
cue.id = generateCueId(cue.startTime, cue.endTime, text.trim());
}
if (cue.endTime > 0) {
cues.push(cue);
}
};
parser.onparsingerror = function (error: Error) {
parsingError = error;
};
parser.onflush = function () {
if (parsingError) {
errorCallBack(parsingError);
return;
}
callBack(cues);
};
// Go through contents line by line.
vttLines.forEach((line) => {
if (inHeader) {
// Look for X-TIMESTAMP-MAP in header.
if (startsWith(line, 'X-TIMESTAMP-MAP=')) {
// Once found, no more are allowed anyway, so stop searching.
inHeader = false;
// Extract LOCAL and MPEGTS.
line
.slice(16)
.split(',')
.forEach((timestamp) => {
if (startsWith(timestamp, 'LOCAL:')) {
cueTime = timestamp.slice(6);
} else if (startsWith(timestamp, 'MPEGTS:')) {
timestampMapMPEGTS = parseInt(timestamp.slice(7));
}
});
try {
// Convert cue time to seconds
timestampMapLOCAL = cueString2millis(cueTime) / 1000;
} catch (error) {
parsingError = error;
}
// Return without parsing X-TIMESTAMP-MAP line.
return;
} else if (line === '') {
inHeader = false;
}
}
// Parse line by default.
parser.parse(line + '\n');
});
parser.flush();
}