-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathrr-record.js
843 lines (712 loc) · 24.7 KB
/
rr-record.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
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
LogCanvas = (() => {
const GL = WebGL2RenderingContext;
const RECORDING_VERSION = 5;
const AUTO_RECORD_FRAMES = 3 * 60;
const SKIP_EMPTY_FRAMES = true;
const SNAPSHOT_LINE_WRAP = 100;
const MAX_SNAPSHOT_SIZE = 16384;
const SNAPSHOT_INLINE_LEN = 100;
const READABLE_SNAPSHOTS = false;
const DEDUPE_SNAPSHOTS = true;
const HOOK_GETTERS = false;
const LOG_CALL_NAME_LIST = [
//'drawImage',
//'getContext',
//'linkProgram', 'bindAttribLocation',
//'getParameter',
//'bindBuffer', 'bufferData', 'bufferSubData',
//'fillText',
//'texImage2D',
];
const LINK_PROGRAM_INJECT_BIND_ATTRIB_LOCATION = true;
const GET_PARAMETER_OVERRIDES = {};
//GET_PARAMETER_OVERRIDES[GL.MAX_TEXTURE_SIZE] = 8192;
const EAT_NONRECORDING_EXCEPTIONS = false;
let LIMIT_NUMBER_PRECISION = 0;
LIMIT_NUMBER_PRECISION = 6; // 1/1M
//LIMIT_NUMBER_PRECISION = 7; // 1/10M (f32 is ~1/16M)
let COMPRESS_IMAGES_ABOVE = 1000 * 1000; // 1MB
// -
// MS Fishbowl overrides window.performance with its own custom
// object for some reason, so save this before Fishbowl has a chance
// to mess with it.
const perf = window.performance;
function performance_now() {
return perf.now();
}
class SplitLogger {
prefix = ''
constructor(desc) {
if (desc) {
this.prefix = desc + ' ';
}
this.start = performance_now();
this.last_split = this.start;
}
log(text) {
let now = performance_now();
const split_diff = now - this.last_split;
const total_diff = now - this.start;
console.log(`[${this.prefix}${split_diff|0}/${total_diff|0}ms]`, text);
this.last_split = now;
}
};
// -
function suffix_scaled(val) {
const SUFFIX_LIST = ['n', 'u', 'm', '', 'K', 'M', 'G', 'T'];
const UNSCALED_SUFFIX = SUFFIX_LIST.indexOf('');
let tier = Math.floor((Math.log10(val) / 3));
tier += UNSCALED_SUFFIX;
tier = Math.max(0, Math.min(tier, SUFFIX_LIST.length-1));
tier -= UNSCALED_SUFFIX;
const tier_base = Math.pow(1000, tier);
return [val / tier_base, SUFFIX_LIST[tier + UNSCALED_SUFFIX]];
}
function to_suffixed(val, fixed) {
const [scaled, suffix] = suffix_scaled(val);
if (!suffix) return val;
if (fixed === undefined) {
fixed = 2 - (Math.log10(scaled) | 0);
}
return `${scaled.toFixed(fixed)}${suffix}`;
}
// -
const should_ignore_set = new WeakSet();
function new_ignored_c2d() {
const c = document.createElement('canvas');
should_ignore_set.add(c);
const c2d = c.getContext('2d');
should_ignore_set.add(c2d);
return c2d;
}
let TO_DATA_URL_C2D = new_ignored_c2d();
function to_data_url(src, w, h) {
function toDataURL_with_limit(src) {
let ret = src.toDataURL();
if (COMPRESS_IMAGES_ABOVE && ret.length >= COMPRESS_IMAGES_ABOVE) {
const compressed = src.toDataURL('image/jpeg');
console.warn(`[canvas-rr] (compressed ${to_suffixed(ret.length)}B PNG -> ${to_suffixed(compressed.length)}B JPEG)`);
ret = compressed;
}
return ret;
};
if (src.toDataURL) return toDataURL_with_limit(src);
w = w || src.naturalWidth || src.videoWidth || src.width;
h = h || src.naturalHeight || src.videoHeight || src.height;
while (Math.max(w, h) >= MAX_SNAPSHOT_SIZE) { // Too large for Firefox.
w = (w >> 1) || 1;
h = (h >> 1) || 1;
}
let c2d = TO_DATA_URL_C2D;
c2d.canvas.width = w;
c2d.canvas.height = h;
if (src instanceof ImageData) {
c2d.putImageData(src, 0, 0);
} else {
c2d.drawImage(src, 0, 0, w, h);
}
let ret;
try {
ret = toDataURL_with_limit(c2d.canvas);
} catch (e) {
if (e instanceof DOMException &&
e.name == 'SecurityError') {
console.warn('After', c2d, '.drawImage(', src, '), ', c2d.canvas, '.toDataURL() failed with', e.name, ', recording black:', e);
c2d = TO_DATA_URL_C2D = new_ignored_c2d();
c2d.canvas.width = w;
c2d.canvas.height = h;
ret = toDataURL_with_limit(c2d.canvas);
} else {
throw e;
}
}
if (ret == "data:,") throw 0; // Encoder failed.
if (src instanceof HTMLImageElement) {
src.toDataURL = function() {
return ret;
};
src.addEventListener('load', e => {
src.toDataURL = undefined;
}, {
capture: false,
once: true,
});
}
if (src instanceof ImageBitmap) {
src.toDataURL = function() {
return ret;
};
}
return ret;
}
// -
function Uint8Array_prototype_toBase64_polyfill() {
const data_u8a = this;
let remaining = data_u8a;
let data_bstr = "";
while (remaining.length) {
const chunk = remaining.slice(0, 1000);
remaining = remaining.slice(1000);
data_bstr += String.fromCodePoint(...chunk);
}
const base64_str = btoa(data_bstr);
return base64_str;
}
function Uint8Array_fromBase64_polyfill(base64_str) {
const data_bstr = atob(base64_str);
const data_u8a = new Uint8Array([].map.call(data_bstr, x => x.codePointAt(0)));
return data_u8a;
}
// -
{
const ref_data = new Uint8Array([ 226, 202, 61, 49, 158 ]);
const ref_base64 = '4so9MZ4=';
const was_base64 = Uint8Array_prototype_toBase64_polyfill.call(ref_data);
console.assert(was_base64 == ref_base64, {was_base64, ref_base64});
const was_data = Uint8Array_fromBase64_polyfill(ref_base64);
console.assert(was_data.toString() == ref_data.toString(), {was_data, ref_data});
// -
const INJECT_BASE64_POLYFILLS = false;
if (INJECT_BASE64_POLYFILLS) {
Uint8Array.prototype.toBase64 = Uint8Array.prototype.toBase64 || Uint8Array_prototype_toBase64_polyfill;
Uint8Array.fromBase64 = Uint8Array.fromBase64 || Uint8Array_fromBase64_polyfill;
}
}
// -
function Uint8Array_toBase64(data_u8a) {
if (data_u8a.toBase64) {
return data_u8a.toBase64();
}
return Uint8Array_prototype_toBase64_polyfill.call(data_u8a);
}
function Uint8Array_fromBase64(base64_str) {
if (Uint8Array.fromBase64) {
return Uint8Array.fromBase64(base64_str);
}
return Uint8Array_fromBase64_polyfill(base64_str);
}
// -
function typed_view(ctor, obj) {
if (ArrayBuffer.isView(obj)) {
return new ctor(obj.buffer, obj.byteOffset, obj.byteLength / ctor.BYTES_PER_ELEMENT);
}
if (obj instanceof ArrayBuffer) {
return new ctor(obj);
}
return undefined;
}
function snapshot_if_array_buffer(obj, length_only) {
const type = obj.constructor.name;
let view = obj;
if (obj instanceof ArrayBuffer || obj instanceof DataView) {
view = typed_view(Uint8Array, obj);
}
if (!view) return undefined;
if (length_only) {
return [type + ':*' + view.length];
}
let str;
if (READABLE_SNAPSHOTS) {
str = view.toString();
} else {
if (!(view instanceof Uint8Array)) {
view = typed_view(Uint8Array, view);
}
str = '^' + Uint8Array_toBase64(view);
}
let hash;
if (DEDUPE_SNAPSHOTS) {
if (!(view instanceof Uint8Array)) {
view = typed_view(Uint8Array, view);
}
// We must hash the type in too!
// I don't think it's worth it to de-dupe data across types.
hash = fnv1a_32(type);
hash = fnv1a_32(view, hash);
hash = '0x' + hash.toString(16);
}
return [type + ':' + str, hash];
}
// -
// Because Everything Is Doubles, we only have 53bit integer precision,
// so i32*i32 is imprecise (i.e. wrong) for larger numbers.
function mul_i32(a, b) {
const ah = (a >> 16) & 0xffff;
const al = a & 0xffff;
return ((ah*b << 16) + (al*b|0)) | 0;
}
// FNV-1a: A solid and simple non-cryptographic hash.
// https://en.wikipedia.org/wiki/Fowler%E2%80%93Noll%E2%80%93Vo_hash_function
// (Would be simpler if doing full-precision u32*u32 were easier in JS...)
function fnv1a_32(input, continue_from) {
let bytes = input;
if (typeof bytes == 'string') {
bytes = new Uint8Array([].map.call(bytes, x => x.codePointAt(0)));
} else if (ArrayBuffer.isView(bytes)) {
bytes = new Uint8Array(bytes.buffer, bytes.byteOffset, bytes.byteLength);
} else if (bytes instanceof ArrayBuffer) {
bytes = new Uint8Array(bytes.buffer);
} else {
throw input.constructor.name;
}
const PRIME = 0x01000193;
const OFFSET_BASIS = 0x811c9dc5;
if (continue_from === undefined) {
continue_from = OFFSET_BASIS;
}
let hash = continue_from;
bytes.forEach(c => {
// i32*i32->i32 has the same bit-result as u32*u32->u32.
hash = mul_i32(PRIME, hash ^ c);
});
const u32 = new Uint32Array(1);
u32[0] = hash;
return u32[0];
}
// -
class Recording {
// String prefixes:
// @: snapshot key
// $: element key
// ": actual string
snapshots = {};
snapshots_by_val = {};
elem_info_by_key = {};
frames = [];
new_frame() {
this.frames.push([]);
}
new_call(obj_key, func_name, args, ret) {
const frame = this.frames[this.frames.length-1];
const call = [obj_key, func_name, args];
if (ret !== undefined) {
call.push(ret);
}
frame.push(call);
}
last_id = 0;
new_id() {
return this.last_id += 1;
}
// -
snapshot_str(obj, func_name, arg_id) {
const type = obj.constructor.name;
switch (type) {
case 'HTMLCanvasElement':
case 'HTMLImageElement':
case 'HTMLVideoElement':
case 'ImageBitmap':
case 'ImageData':
return [to_data_url(obj)];
case 'CanvasRenderingContext2D':
case 'WebGLRenderingContext':
case 'WebGL2RenderingContext':
return undefined;
}
if (type == 'Object') {
const str = JSON.stringify(obj);
return [type + ':' + str];
}
const length_only = (func_name == 'readPixels');
const snapshot = snapshot_if_array_buffer(obj, length_only);
if (snapshot !== undefined) return snapshot;
console.error(`[LogCanvas@${window.origin}] Warning: Unrecognized type "${type}" in snapshot_str for ${func_name}.${arg_id}: `, obj);
return undefined;
}
key_by_obj = new WeakMap();
obj_key(obj) {
if (!obj) return null;
let key = this.key_by_obj.get(obj);
if (key) return key;
key = '$' + this.new_id();
this.key_by_obj.set(obj, key);
const info = {
type: obj.constructor.name,
};
if (['HTMLCanvasElement', 'OffscreenCanvas'].includes(info.type)) {
info.width = obj.width;
info.height = obj.height;
this.elem_info_by_key[key] = info;
}
return key;
}
prev_snapshot_key_by_obj = new WeakMap();
pickle_obj(obj, func_name, arg_id) {
if (!obj) return null;
{
const key = this.key_by_obj.get(obj);
if (key) return key;
}
if (arg_id == -1) {
// Return values can be ignored.
const ctor = obj.constructor;
if (ctor == ImageData || ctor == TextMetrics) {
return '#' + ctor.name;
}
}
let snapshot;
if (arg_id != -1) {
// Don't snapshot return values.
snapshot = this.snapshot_str(obj, func_name, arg_id);
}
if (snapshot) {
// Snapshot instead of just tagging with object key.
const [val_str, hash] = snapshot;
if (!val_str.startsWith('data:') && val_str.length <= SNAPSHOT_INLINE_LEN) {
return '=' + val_str;
}
const prev_key = this.prev_snapshot_key_by_obj.get(obj);
if (prev_key) {
// Has previous snapshot, but data might have changed.
const prev_val_str = this.snapshots[prev_key];
if (val_str == prev_val_str) return prev_key;
}
function make_key(uuid, collision_id, obj) {
let key = '@' + uuid;
if (collision_id) {
key += '.' + collision_id;
}
if (obj.constructor.name == 'ImageData') {
key += ':' + [obj.constructor.name, obj.width, obj.height].join(',');
}
return key;
};
let uuid = hash;
if (!uuid) {
uuid = this.new_id();
}
let collision_id = 0;
let key = make_key(uuid, collision_id, obj);
while (this.snapshots[key]) {
//console.log(`Deduping ${key} (${val_str.length} chars)`);
if (this.snapshots[key] == val_str) break;
collision_id += 1;
key = make_key(uuid, collision_id, obj);
}
if (collision_id) {
console.warn(`Collision while de-duping snapshot -> ${key}`);
}
this.prev_snapshot_key_by_obj.set(obj, key);
this.snapshots[key] = val_str;
return key;
}
return this.obj_key(obj);
}
pickle_arg(arg, func_name, i, spew) {
if (spew) {
console.log('pickle_arg', {arg});
}
if (typeof arg == 'string') return '"' + arg;
if (!arg) return arg;
if (arg instanceof Array) return arg.map(x => this.pickle_arg(x, func_name, i));
if (typeof arg == 'object') return this.pickle_obj(arg, func_name, i);
if (typeof arg == 'number' && LIMIT_NUMBER_PRECISION && arg == arg) { // NaN != NaN
let p = LIMIT_NUMBER_PRECISION;
p = Math.max(p, 1+Math.log10(Math.abs(arg))); // Never round above the decimal point.
arg = +(arg.toPrecision(p)); // number -> string -> number
}
return arg;
}
pickle_call(obj, func_name, call_args, call_ret) {
const begin = performance.now();
if (LOG_CALL_NAME_LIST.includes(func_name)) {
console.log('pickle_call', ...arguments);
}
const obj_key = this.obj_key(obj);
const args = [].map.call(call_args, (x,i) => this.pickle_arg(x, func_name, i));
const ret = this.pickle_arg(call_ret, func_name, -1);
this.new_call(obj_key, func_name, args, ret);
const ms = performance.now() - begin;
if (ms >= 10.0) {
console.warn(`pickle_call(`, {obj, func_name, call_args, call_ret}, `) took ${ms}ms`);
}
}
to_json_arr() {
const slog = new SplitLogger('to_json_arr');
const elem_info_json = JSON.stringify(this.elem_info_by_key, null, 3);
slog.log(`${to_suffixed(elem_info_json.length)} bytes of elem_info_json.`);
function chunk(src, chunk_size) {
const ret = [];
let pos = 0;
while (pos < src.length) {
const end = pos + chunk_size;
ret.push(src.slice(pos, end));
pos = end;
}
return ret;
}
const parts = [];
parts.push(
'{', // begin root object
`\n"version": ${RECORDING_VERSION},`,
`\n"elem_info_by_key": ${elem_info_json},`,
'\n"frames": [', // begin frames
'\n [' // begin frame
);
let add_comma = false;
for (const [i, frame] of Object.entries(this.frames)) {
if (add_comma) {
parts.push('\n ],[');
}
add_comma = true;
if (frame.length) {
let add_comma2 = false;
for (const call of frame) {
if (add_comma2) {
parts.push(',');
}
add_comma2 = true;
parts.push('\n ', JSON.stringify(call));
}
}
}
const chunked_snapshots = {};
for (const [k, v] of Object.entries(this.snapshots)) {
chunked_snapshots[k] = chunk(v, SNAPSHOT_LINE_WRAP);
}
const snapshots_json = JSON.stringify(chunked_snapshots, null, 3);
parts.push(
'\n ]', // end of frame
'\n],', // end of frames
'\n"snapshots": ',
snapshots_json,
'\n}', // end of root object
'\n'
);
// -
let size = 0;
for (const x of parts) {
size += x.length;
}
slog.log(`${to_suffixed(size)} bytes in ${to_suffixed(parts.length)} parts...`);
let join = '';
for (const x of parts) {
join += x;
}
slog.log(`done`);
return [join];
}
};
// -
const DONT_HOOK = {
'constructor': true,
'toDataURL': true,
};
function hook_props(obj, fn_observe) {
const descs = Object.getOwnPropertyDescriptors(obj);
for (const k in descs) {
if (DONT_HOOK[k]) continue;
const desc = descs[k];
if (HOOK_GETTERS && desc.get) {
//console.log(`hooking getter: ${obj.constructor.name}.${k}`);
const was = desc.get;
desc.get = function() {
const ret = was.call(this);
try {
fn_observe(this, 'get ' + k, [], ret);
} catch (e) {
console.error(e);
throw e;
}
return ret;
};
continue;
}
if (desc.set) {
//console.log(`hooking setter: ${obj.constructor.name}.${k}`);
const was = desc.set;
desc.set = function(v) {
was.call(this, v);
try {
fn_observe(this, 'set ' + k, [v], undefined);
} catch (e) {
console.error(e);
throw e;
}
};
continue;
}
if (typeof desc.value === 'function') {
//console.log(`hooking func: ${obj.constructor.name}.${k}`);
const was = desc.value;
desc.value = function() {
let ret;
if (!RECORDING_FRAMES && !LogCanvas.EAT_NONRECORDING_EXCEPTIONS) {
ret = was.apply(this, arguments);
} else {
try {
ret = was.apply(this, arguments);
} catch (e) {
console.error(e, 'from', obj, `.${k}(`, ...arguments, `)`);
}
}
try {
ret = fn_observe(this, k, arguments, ret);
} catch (e) {
console.error(e);
throw e;
}
return ret;
};
continue;
}
}
Object.defineProperties(obj, descs);
}
/*
function log_observe(obj, name, args, ret) {
console.log(`${obj.constructor.name}.${name}(${JSON.stringify([].slice.call(args))}) -> ${ret}`);
}
hook_props(HTMLCanvasElement.prototype, log_observe);
hook_props(CanvasRenderingContext2D.prototype, log_observe);
*/
// -
let RECORDING_FRAMES = 0;
let RECORDING = null;
// -
const HOOK_LIST = [
HTMLCanvasElement,
//HTMLImageElement,
OffscreenCanvas,
CanvasRenderingContext2D,
Path2D,
WebGLRenderingContext,
WebGL2RenderingContext,
];
const HOOK_CTOR_LIST = [
Path2D,
];
const IGNORED_FUNCS = {
'toDataURL': true,
'getTransform': true,
//'getParameter': true,
};
const is_hooked_set = new WeakSet();
function inject_observer() {
console.log(`[LogCanvas@${window.origin}] Injecting for`, window.location, ':', window.LogCanvas);
function fn_observe(obj, k, args, ret) {
if (should_ignore_set.has(obj)) return ret;
if (!RECORDING_FRAMES) return ret;
if (IGNORED_FUNCS[k]) return ret;
RECORDING.pickle_call(obj, k, args, ret);
if (k == 'getExtension') {
if (ret && !is_hooked_set.has(ret.__proto__)) {
//console.log(`[LogCanvas@${window.origin}] getExtension`, args);
is_hooked_set.add(ret.__proto__);
hook_props(ret.__proto__, fn_observe);
}
}
if (k == 'getParameter') {
const override = GET_PARAMETER_OVERRIDES[args[0]];
if (override !== undefined) {
console.log(`getParameter(0x${args[0].toString(16)}) -> ${ret} -> ${override}`);
ret = override;
}
}
if (LINK_PROGRAM_INJECT_BIND_ATTRIB_LOCATION && k == 'linkProgram') {
const was = RECORDING_FRAMES;
RECORDING_FRAMES = 0; // Prevent re-entrancy.
const gl = obj;
const prog = args[0];
const n = gl.getProgramParameter(prog, gl.ACTIVE_ATTRIBUTES);
for (let i = 0; i < n; i++) {
const aa = gl.getActiveAttrib(prog, i);
const loc = gl.getAttribLocation(prog, aa.name);
console.assert(loc != -1, {i, aa, loc});
RECORDING.pickle_call(gl, 'bindAttribLocation', [prog, loc, aa.name]);
}
RECORDING.pickle_call(gl, 'linkProgram', [prog]);
RECORDING_FRAMES = was;
}
return ret;
}
for (const cur of HOOK_LIST) {
hook_props(cur.prototype, fn_observe);
}
for (const cur of HOOK_CTOR_LIST) {
const name = cur.prototype.constructor.name;
const hook_class = class extends cur {
constructor() {
super(...arguments);
RECORDING.pickle_call(null, 'new ' + name, arguments, this);
}
};
hook_class.prototype.constructor.name = name;
window[name] = hook_class;
}
if (AUTO_RECORD_FRAMES) {
record_frames(AUTO_RECORD_FRAMES); // Grab initial.
}
};
function download_text_arr(dry_run, filename, textArr, mimetype='text/plain') {
const blob = new Blob(textArr, {type: mimetype});
const url = URL.createObjectURL(blob);
const link = document.createElement('a');
link.href = url;
link.download = filename;
document.body.appendChild(link);
if (!dry_run) {
link.click();
}
document.body.removeChild(link);
}
function record_frames(n) {
console.log(`[LogCanvas@${window.origin}] Recording ${n} frames...`);
RECORDING_FRAMES = n+1;
RECORDING = new Recording();
function per_frame() {
if (RECORDING_FRAMES) {
const cur_frame = RECORDING.frames[RECORDING.frames.length-1];
if (SKIP_EMPTY_FRAMES && cur_frame && !cur_frame.length) {
requestAnimationFrame(per_frame);
return;
}
RECORDING_FRAMES -= 1;
RECORDING_FRAMES |= 0;
}
if (!RECORDING_FRAMES) {
let calls = 0;
RECORDING.frames.forEach(frame_calls => {
calls += frame_calls.length;
});
if (!calls) {
console.log(`[LogCanvas@${window.origin}]`,
`Recording ended with 0 calls.`);
return;
}
console.log(`[LogCanvas@${window.origin}]`,
`${RECORDING.frames.length}/${n} frames recorded!`,
`(${to_suffixed(calls)} calls)`);
return;
}
RECORDING.new_frame();
requestAnimationFrame(per_frame);
}
per_frame();
}
function record_next_frames(n) {
requestAnimationFrame(() => {
record_frames(n);
});
}
function download(dry_run = false) {
const slog = new SplitLogger('download');
const arr = RECORDING.to_json_arr();
dry_run && slog.log(`to_json_arr`);
download_text_arr(dry_run, 'recording.json', arr);
dry_run && slog.log(`done`);
}
function stop() {
RECORDING_FRAMES = 0;
console.log(`[LogCanvas@${window.origin}] Stopping...`);
}
return {
inject_observer,
record_frames,
record_next_frames,
download,
stop,
EAT_NONRECORDING_EXCEPTIONS,
};
})();
LogCanvas.inject_observer();