forked from asciinema/asciinema-player
-
Notifications
You must be signed in to change notification settings - Fork 0
/
recording.js
400 lines (316 loc) · 8.78 KB
/
recording.js
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
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
import { unparseAsciicastV2 } from '../parser/asciicast';
import Stream from '../stream';
function recording(src, { feed, onInput, now, setTimeout, setState, logger }, { idleTimeLimit, startAt, loop }) {
let cols;
let rows;
let outputs;
let inputs;
let duration;
let effectiveStartAt;
let outputTimeoutId;
let inputTimeoutId;
let nextOutputIndex = 0;
let nextInputIndex = 0;
let lastOutputTime = 0;
let startTime;
let pauseElapsedTime;
let playCount = 0;
async function init() {
const { parser, minFrameTime, inputOffset, dumpFilename } = src;
const recording = prepare(
await parser(await doFetch(src)),
logger,
{ idleTimeLimit, startAt, minFrameTime, inputOffset }
);
({ output: outputs, input: inputs, cols, rows, duration, effectiveStartAt } = recording);
if (outputs.length === 0) {
throw 'recording is missing output events';
}
if (dumpFilename !== undefined) {
dump(recording, dumpFilename);
}
return { cols, rows, duration };
}
function doFetch({ url, data, fetchOpts = {} }) {
if (typeof url === 'string') {
return doFetchOne(url, fetchOpts);
} else if (Array.isArray(url)) {
return Promise.all(url.map(url => doFetchOne(url, fetchOpts)));
} else if (data !== undefined) {
if (typeof data === 'function') {
data = data();
}
if (!(data instanceof Promise)) {
data = Promise.resolve(data);
}
return data.then(value => {
if (typeof value === 'string' || value instanceof ArrayBuffer) {
return new Response(value);
} else {
return value;
}
});
} else {
throw 'failed fetching recording file: url/data missing in src';
}
}
async function doFetchOne(url, fetchOpts) {
const response = await fetch(url, fetchOpts);
if (!response.ok) {
throw `failed fetching recording from ${url}: ${response.status} ${response.statusText}`;
}
return response;
}
function delay(targetTime) {
let delay = (targetTime * 1000) - (now() - startTime);
if (delay < 0) {
delay = 0;
}
return delay;
}
function scheduleNextOutput() {
const nextOutput = outputs[nextOutputIndex];
if (nextOutput) {
outputTimeoutId = setTimeout(runNextOutput, delay(nextOutput[0]));
} else {
onEnd();
}
}
function runNextOutput() {
let output = outputs[nextOutputIndex];
let elapsedWallTime;
do {
feed(output[1]);
lastOutputTime = output[0];
output = outputs[++nextOutputIndex];
elapsedWallTime = now() - startTime;
} while (output && (elapsedWallTime > output[0] * 1000));
scheduleNextOutput();
}
function cancelNextOutput() {
clearTimeout(outputTimeoutId);
outputTimeoutId = null;
}
function scheduleNextInput() {
const nextInput = inputs[nextInputIndex];
if (nextInput) {
inputTimeoutId = setTimeout(runNextInput, delay(nextInput[0]));
}
}
function runNextInput() {
onInput(inputs[nextInputIndex++][1]);
scheduleNextInput();
}
function cancelNextInput() {
clearTimeout(inputTimeoutId);
inputTimeoutId = null;
}
function onEnd() {
cancelNextOutput();
cancelNextInput();
playCount++;
if (loop === true || (typeof loop === 'number' && playCount < loop)) {
nextOutputIndex = 0;
nextInputIndex = 0;
startTime = now();
feed('\x1bc'); // reset terminal
scheduleNextOutput();
scheduleNextInput();
} else {
pauseElapsedTime = duration * 1000;
effectiveStartAt = null;
setState('stopped', { reason: 'ended' });
}
}
function play() {
if (outputTimeoutId) return true;
if (outputs[nextOutputIndex] === undefined) { // ended
effectiveStartAt = 0;
}
if (effectiveStartAt !== null) {
seek(effectiveStartAt);
}
resume();
return true;
}
function pause() {
if (!outputTimeoutId) return true;
cancelNextOutput();
cancelNextInput();
pauseElapsedTime = now() - startTime;
return true;
}
function resume() {
startTime = now() - pauseElapsedTime;
pauseElapsedTime = null;
scheduleNextOutput();
scheduleNextInput();
}
function seek(where) {
const isPlaying = !!outputTimeoutId;
pause();
if (typeof where === 'string') {
const currentTime = (pauseElapsedTime ?? 0) / 1000;
if (where === '<<') {
where = currentTime - 5;
} else if (where === '>>') {
where = currentTime + 5;
} else if (where === '<<<') {
where = currentTime - (0.1 * duration);
} else if (where === '>>>') {
where = currentTime + (0.1 * duration);
} else if (where[where.length - 1] === '%') {
where = (parseFloat(where.substring(0, where.length - 1)) / 100) * duration;
}
}
const targetTime = Math.min(Math.max(where, 0), duration);
if (targetTime < lastOutputTime) {
feed('\x1bc'); // reset terminal
nextOutputIndex = 0;
nextInputIndex = 0;
lastOutputTime = 0;
}
let output = outputs[nextOutputIndex];
while (output && (output[0] < targetTime)) {
feed(output[1]);
lastOutputTime = output[0];
output = outputs[++nextOutputIndex];
}
let input = inputs[nextInputIndex];
while (input && (input[0] < targetTime)) {
input = inputs[++nextInputIndex];
}
pauseElapsedTime = targetTime * 1000;
effectiveStartAt = null;
if (isPlaying) {
resume();
}
return true;
}
function step() {
let nextOutput = outputs[nextOutputIndex];
if (nextOutput !== undefined) {
feed(nextOutput[1]);
const targetTime = nextOutput[0];
lastOutputTime = targetTime;
pauseElapsedTime = targetTime * 1000;
nextOutputIndex++;
let input = inputs[nextInputIndex];
while (input && (input[0] < targetTime)) {
input = inputs[++nextInputIndex];
}
}
effectiveStartAt = null;
}
function getPoster(time) {
const posterTime = time * 1000;
const poster = [];
let nextOutputIndex = 0;
let output = outputs[0];
while (output && (output[0] * 1000 < posterTime)) {
poster.push(output[1]);
output = outputs[++nextOutputIndex];
}
return poster;
}
function getCurrentTime() {
if (outputTimeoutId) {
return (now() - startTime) / 1000;
} else {
return (pauseElapsedTime ?? 0) / 1000;
}
}
return {
init,
play,
pause,
seek,
step,
stop: pause,
getPoster,
getCurrentTime
}
}
function batcher(logger, minFrameTime = 1.0 / 60) {
let prevOutput;
return emit => {
let ic = 0;
let oc = 0;
return {
step: output => {
ic++;
if (prevOutput === undefined) {
prevOutput = output;
return;
}
if (output[0] - prevOutput[0] < minFrameTime) {
prevOutput[1] += output[1];
} else {
emit(prevOutput);
prevOutput = output;
oc++;
}
},
flush: () => {
if (prevOutput !== undefined) {
emit(prevOutput);
oc++;
}
logger.debug(`batched ${ic} frames to ${oc} frames`);
}
}
};
}
function prepare(recording, logger, { startAt = 0, idleTimeLimit, minFrameTime, inputOffset }) {
idleTimeLimit = idleTimeLimit ?? recording.idleTimeLimit ?? Infinity;
let { output, input = [] } = recording;
if (!(output instanceof Stream)) {
output = new Stream(output);
}
if (!(input instanceof Stream)) {
input = new Stream(input);
}
output = output
.transform(batcher(logger, minFrameTime))
.map(e => ['o', e]);
input = input.map(e => ['i', e]);
let prevT = 0;
let shift = 0;
let effectiveStartAt = startAt;
const compressed = output
.multiplex(input, (a, b) => a[1][0] < b[1][0])
.map(e => {
const delay = e[1][0] - prevT;
const delta = delay - idleTimeLimit;
prevT = e[1][0];
if (delta > 0) {
shift += delta;
if (e[1][0] < startAt) {
effectiveStartAt -= delta;
}
}
return [e[0], [e[1][0] - shift, e[1][1]]];
});
const streams = new Map([
['o', []],
['i', []]
]);
for (const e of compressed) {
streams.get(e[0]).push(e[1]);
}
output = streams.get('o');
input = streams.get('i');
if (inputOffset !== undefined) {
input = input.map(i => [i[0] + inputOffset, i[1]]);
}
const duration = output[output.length - 1][0];
return { ...recording, output, input, duration, effectiveStartAt };
}
function dump(recording, filename) {
const link = document.createElement('a');
const asciicast = unparseAsciicastV2(recording);
link.href = URL.createObjectURL(new Blob([asciicast], { type: 'text/plain' }));
link.download = filename;
link.click();
}
export { recording };