-
-
Notifications
You must be signed in to change notification settings - Fork 19
/
Copy pathvingester-browser.js
790 lines (730 loc) · 32.2 KB
/
vingester-browser.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
/*
** Vingester ~ Ingest Web Contents as Video Streams
** Copyright (c) 2021-2022 Dr. Ralf S. Engelschall <[email protected]>
** Licensed under GPL 3.0 <https://spdx.org/licenses/GPL-3.0-only>
*/
/* require internal modules */
const os = require("os")
const fs = require("fs")
const path = require("path")
const rimraf = require("rimraf")
/* require external modules */
const electron = require("electron")
const contextMenu = require("electron-context-menu")
const bluebird = require("bluebird")
const util = require("./vingester-util.js")
const pkg = require("./package.json")
/* browser abstraction */
module.exports = class Browser {
/* create new browser */
constructor (log, id, cfg, control, ffmpeg) {
this.log = log
this.id = id
this.cfg = {}
this.control = control
this.ffmpeg = ffmpeg
this.reset()
this.reconfigure(cfg)
}
/* reset internal state */
reset () {
this.worker = null
this.content = null
this.subscribed = false
this.subscriber = null
this.starting = false
this.stopping = false
this.tally = "unconnected"
this.framerateSource = -1
this.framerateTarget = -1
this.framerateNow = -1
this.framesToSkip = -1
this.devToolsEnabled = false
}
/* reconfigure browser */
reconfigure (cfg) {
this.log.info("browser: reconfigure")
/* take over configuration */
Object.assign(this.cfg, cfg)
/* pre-parse configuration strings */
this.cfg.w = parseInt(this.cfg.w)
this.cfg.h = parseInt(this.cfg.h)
this.cfg.x = parseInt(this.cfg.x)
this.cfg.y = parseInt(this.cfg.y)
this.cfg.f = parseInt(this.cfg.f)
this.cfg.O = parseInt(this.cfg.O)
this.cfg.o = parseInt(this.cfg.o)
this.cfg.C = parseInt(this.cfg.C)
this.cfg.k = parseInt(this.cfg.k)
this.cfg.z = parseFloat(this.cfg.z)
/* recalculate capture framerate */
this.recalcCaptureFramerate()
/* optionally reconfigure already running worker instance */
this.update()
/* control devTools window */
if (this.content !== null) {
if (!this.devToolsEnabled && this.cfg.E) {
this.content.webContents.openDevTools({ mode: "detach", activate: true })
this.devToolsEnabled = true
this.control.webContents.send("devtools", { id: this.id, enabled: true })
}
else if (this.devToolsEnabled && !this.cfg.E) {
this.content.webContents.closeDevTools()
this.devToolsEnabled = false
this.control.webContents.send("devtools", { id: this.id, enabled: false })
}
}
}
/* explicitly allow the content browser windows certain permissions */
static prepare () {
const session = electron.session.fromPartition("vingester-browser-content")
const allowedPermissions = [ "media", "mediaKeySystem", "geolocation" ]
session.setPermissionRequestHandler((webContents, permission, callback) => {
if (allowedPermissions.includes(permission))
callback(true)
else
callback(false)
})
}
/* recalculate capturing framerate */
recalcCaptureFramerate () {
/* determine framerate */
let framerate = this.framerateTarget
if (framerate < 0)
framerate = 0
/* optionally adapt framerate */
if (this.cfg.D && !this.cfg.N && !this.cfg.P)
framerate = 0
else if (this.cfg.N && this.cfg.a && framerate > 0) {
if (this.cfg.l) {
/* for NDI Adaptive with Tally Reload mode, we drop the framerate
dramatically down if we are not in preview or program */
if (this.tally === "unconnected" || this.tally === "connected")
framerate = this.cfg.P ? 1 : 0
}
else {
/* for standard NDI Adaptive mode, we adjust the
framerate in a dynamic and reasonable way */
if (this.tally === "unconnected" && !this.cfg.P)
framerate = 1
else if (this.tally === "unconnected" && this.cfg.P)
framerate = 5
else if (this.tally === "connected") {
framerate = Math.trunc(framerate / 3)
if (framerate < 5)
framerate = 5
}
}
}
/* set capture framerate (if changed) */
if (framerate !== this.framerateNow && this.framerateTarget !== -1 && this.framerateSource !== -1) {
if (this.framerateNow === -1)
this.log.info(`browser/worker-${this.id}: setting capture framerate to ` +
`${framerate}/${this.framerateTarget}/${this.framerateSource} (initially)`)
else
this.log.info(`browser/worker-${this.id}: setting capture framerate to ` +
`${framerate}/${this.framerateTarget}/${this.framerateSource} (subsequently)`)
this.framerateNow = framerate
}
}
/* check whether browser is running */
running () {
return (this.content !== null && this.worker !== null)
}
/* check whether browser has a valid configuration */
valid () {
return (
(this.cfg.D || this.cfg.N)
&& (!this.cfg.N || (this.cfg.N && (this.cfg.n || this.cfg.m)))
&& this.cfg.t !== ""
&& this.cfg.u !== ""
)
}
/* start browser */
async start () {
if (this.starting)
return
this.starting = true
this.log.info("browser: start")
/* create worker browser window (offscreen only) */
const worker = new electron.BrowserWindow({
offscreen: true,
show: false,
width: 200,
height: 200,
title: "Vingester Browser Worker",
webPreferences: {
devTools: (process.env.DEBUG === "2"),
backgroundThrottling: false,
nodeIntegration: true,
nodeIntegrationInWorker: true,
contextIsolation: false,
enableRemoteModule: false,
disableDialogs: true,
autoplayPolicy: "no-user-gesture-required",
spellcheck: false,
additionalArguments: [ "vingester-cfg-" + btoa(unescape(encodeURIComponent(JSON.stringify({
...this.cfg,
controlId: this.control.webContents.id,
ffmpeg: this.ffmpeg,
ffmpegCwd: electron.app.getPath("videos")
})))) ]
}
})
worker.removeMenu()
if (process.env.DEBUG === "2") {
setTimeout(() => {
worker.webContents.openDevTools()
}, 1000)
}
/* receive worker browser console outputs */
worker.webContents.on("console-message", (ev, level, message, line, sourceId) => {
let method = "debug"
switch (level) {
case 0: method = "debug"; break
case 1: method = "info"; break
case 2: method = "warn"; break
case 3: method = "error"; break
}
this.log[method](`browser/worker-${this.id}: console: ${message.replace(/\s+/g, " ")}`)
})
/* notify content of tally information */
const changeVisibilityState = (state) => {
if (this.content === null)
return
if (this.cfg.D)
return
this.content.webContents.executeJavaScript(`
vingester.visibility(${JSON.stringify(state)});
document.dispatchEvent(new Event("visibilitychange", {
bubbles: false, cancelable: false
}))
`)
}
const raiseContentEvent = (name, detail) => {
if (this.content === null)
return
this.content.webContents.executeJavaScript(`
window.dispatchEvent(new CustomEvent("${name}", {
bubbles: false, cancelable: false,
detail: ${JSON.stringify(detail)}
}))
`)
}
let activeLast = null
let visibleLast = null
const notifyContent = (tally) => {
/* provide original event */
raiseContentEvent("vingesterTallyChanged", { tally })
/* track visibility */
let visible = false /* OBS Studio: visible on preview/program or any display */
let active = false /* OBS Studio: visible on preview/program and stream/recording */
if (tally === "preview")
visible = true
else if (tally === "program") {
visible = true
active = true
}
if (visibleLast !== visible) {
if (this.cfg.B) {
raiseContentEvent("obsSourceVisibleChanged", { visible })
this.log.info(`browser: new OBS DOM VISIBLE state: ${visible}`)
}
visibleLast = visible
}
if (activeLast !== active) {
this.log.info(`browser: new DOM VISIBILITY state: ${active}`)
changeVisibilityState(active ? "visible" : "hidden")
if (this.cfg.B) {
raiseContentEvent("obsSourceActiveChanged", { active })
this.log.info(`browser: new OBS DOM ACTIVE state: ${active}`)
}
activeLast = active
}
}
/* receive worker information */
let tallyLast = ""
worker.webContents.on("ipc-message", (ev, channel, msg) => {
if (channel === "tally") {
/* receive tally status */
this.tally = msg.status
if (this.tally !== tallyLast) {
tallyLast = this.tally
this.recalcCaptureFramerate()
this.update()
this.log.info(`browser: new NDI TALLY state: ${this.tally}`)
notifyContent(this.tally)
if (this.cfg.l && (this.tally === "preview" || this.tally === "program")) {
this.log.info("browser: reloading content because of new tally state")
this.content.reload()
}
}
}
})
/* load content into worker browser window */
await new Promise((resolve, reject) => {
worker.webContents.once("did-fail-load", (ev, code, desc, url, isMainFrame) => {
ev.preventDefault()
this.log.info(`browser: worker: failed (code: ${code}, desc: ${desc}, url: ${url}, isMainFrame: ${isMainFrame})`)
this.control.webContents.send("message", `browser: worker: failed (code: ${code}, desc: ${desc}, url: ${url}, isMainFrame: ${isMainFrame})`)
resolve(false)
})
worker.webContents.once("did-finish-load", (ev) => {
ev.preventDefault()
this.log.info("browser: worker: started")
resolve(true)
})
worker.loadURL(`file://${path.join(__dirname, "vingester-browser-worker.html")}`)
})
/* remember worker object */
this.worker = worker
/* determine window title */
const title = (this.cfg.t == null ? "Vingester" : this.cfg.t)
/* determine target display of browser window */
const displays = util.AvailableDisplays.determine(electron)
let D = electron.screen.getPrimaryDisplay()
if (this.cfg.D) {
let display = displays.find((display) => display.num === this.cfg.d)
if (display === undefined)
display = displays.find((display) => display.num === 0)
D = electron.screen.getDisplayMatching({
x: display.x,
y: display.y,
width: display.w,
height: display.h
})
}
/* determine position of browser window (on its target display) */
let pos = {}
if (this.cfg.D && this.cfg.x !== null && this.cfg.y !== null) {
const x = D.bounds.x + this.cfg.x
const y = D.bounds.y + this.cfg.y
pos = { x, y }
}
/* create browser session */
let session = electron.session.fromPartition("vingester-browser-content")
if (this.cfg.S) {
const name = `vingester-browser-content-${this.id.toLowerCase()}`
session = electron.session.fromPartition(`persist:${name}`)
const allowedPermissions = [ "media", "mediaKeySystem", "geolocation" ]
session.setPermissionRequestHandler((webContents, permission, callback) => {
if (allowedPermissions.includes(permission))
callback(true)
else
callback(false)
})
}
/* create content browser window (visible or offscreen) */
this.log.info(`browser: create (${this.cfg.w}x${this.cfg.h} @ ${this.cfg.z})`)
const content = new electron.BrowserWindow({
width: this.cfg.w,
height: this.cfg.h,
minWidth: this.cfg.w,
minHeight: this.cfg.h,
maxWidth: this.cfg.w,
maxHeight: this.cfg.h,
useContentSize: true,
...(this.cfg.c === "transparent" ? {
transparent: true
} : {
backgroundColor: this.cfg.c
}),
...(this.cfg.D ? {
...pos,
resizable: false,
movable: false,
minimizable: false,
maximizable: false,
closable: false,
autoHideMenuBar: true,
roundedCorners: false,
frame: false,
hasShadow: false,
enableLargerThanScreen: true,
fullscreenable: true,
titleBarStyle: "hidden",
thickFrame: false,
title
} : {
show: false
}),
webPreferences: {
...(this.cfg.D ? {
offscreen: false
} : {
offscreen: true
}),
zoomFactor: this.cfg.z,
session,
devTools: true,
backgroundThrottling: false,
preload: path.join(__dirname, "vingester-browser-preload.js"),
nodeIntegration: this.cfg.I ? true : false,
nodeIntegrationInWorker: this.cfg.I ? true : false,
contextIsolation: true,
enableRemoteModule: false,
disableDialogs: true,
autoplayPolicy: "no-user-gesture-required",
spellcheck: false,
additionalArguments: [ "vingester-cfg-" + btoa(unescape(encodeURIComponent(JSON.stringify({
...this.cfg,
controlId: this.control.webContents.id,
workerId: this.worker.webContents.id
})))) ]
}
})
if (os.platform() === "darwin")
content.setWindowButtonVisibility(false)
/* support devTools */
if (this.cfg.E) {
this.log.info("browser: open")
setTimeout(() => {
content.webContents.openDevTools({ mode: "detach", activate: false })
this.devToolsEnabled = true
this.control.webContents.send("devtools", { id: this.id, enabled: true })
}, 1000)
}
content.webContents.on("devtools-opened", (ev) => {
this.devToolsEnabled = true
this.control.webContents.send("devtools", { id: this.id, enabled: true })
})
content.webContents.on("devtools-closed", (ev) => {
this.devToolsEnabled = false
this.control.webContents.send("devtools", { id: this.id, enabled: false })
})
/* determine user-agent identifier */
let ua = content.webContents.getUserAgent()
ua += ` Vingester/${pkg.version}`
content.webContents.setUserAgent(ua)
this.log.info(`browser: content: user-agent: "${ua}"`)
/* allow insecure HTTPS connections */
content.webContents.session.setCertificateVerifyProc((request, callback) => {
if (request.hostname === "localhost"
|| request.hostname === "127.0.0.1"
|| request.hostname === "::1"
|| this.cfg.H)
callback(0)
else
callback(-3)
})
/* control audio (we unmute for "frameless" window and "headless" with no audio channels) */
if (this.cfg.D || (this.cfg.N && this.cfg.C === 0))
content.webContents.setAudioMuted(false)
else
content.webContents.setAudioMuted(true)
/* force aspect ratio */
content.setAspectRatio(this.cfg.w / this.cfg.h)
/* force always on top */
if (this.cfg.p) {
/* show window higher than all regular windows, but still behind
things like spotlight or the screen saver and allow the window to
show over a fullscreen window */
content.setAlwaysOnTop(true, "pop-up-menu", 1)
content.setVisibleOnAllWorkspaces(true)
}
else {
content.setAlwaysOnTop(false)
content.setVisibleOnAllWorkspaces(false)
}
/* capture and send browser frame content */
if (this.cfg.D) {
/* use Frame subscription where framerate cannot be controlled
(but which is available also for onscreen rendering) */
this.framerateSource = D.displayFrequency
this.framerateTarget = this.cfg.f
this.framerateNow = -1
this.recalcCaptureFramerate()
let framesSkipped = 0
this.subscriber = (image, dirty) => {
if (this.worker === null || this.worker.isDestroyed())
return
if (framesSkipped++ < this.framesToSkip)
return
framesSkipped = 0
const buffer = image.getBitmap()
const size = image.getSize()
const ratio = image.getAspectRatio()
this.worker.webContents.send("video-capture", buffer, size, ratio, dirty)
}
}
else if (this.cfg.N) {
/* use Paint hook where framerate can be controlled
(but which is available for offscreen rendering only) */
this.framerateSource = 240
this.framerateTarget = this.cfg.f
this.framerateNow = -1
this.recalcCaptureFramerate()
this.subscriber = (ev, dirty, image) => {
if (this.worker === null || this.worker.isDestroyed())
return
const buffer = image.getBitmap()
const size = image.getSize()
const ratio = image.getAspectRatio()
this.worker.webContents.send("video-capture", buffer, size, ratio, dirty)
}
}
/* receive content browser console outputs */
content.webContents.on("console-message", (ev, level, message, line, sourceId) => {
/* log centrally */
let method = "debug"
switch (level) {
case 0: method = "debug"; break
case 1: method = "info"; break
case 2: method = "warn"; break
case 3: method = "error"; break
}
this.log[method](`browser/content-${this.id}: console: ${message.replace(/\s+/g, " ")}`)
/* optionally send to control user interface */
if (this.control !== null && !this.control.isDestroyed())
this.control.webContents.send("trace", { level, message, id: this.id })
})
/* ignore any interactions on worker and content browser windows */
worker.setMenu(null)
worker.on("close", (ev) => { ev.preventDefault() })
worker.on("minimize", (ev) => { ev.preventDefault() })
worker.on("restore", (ev) => { ev.preventDefault() })
worker.on("maximize", (ev) => { ev.preventDefault() })
worker.on("unmaximize", (ev) => { ev.preventDefault() })
worker.on("enter-full-screen", (ev) => { ev.preventDefault() })
worker.on("leave-full-screen", (ev) => { ev.preventDefault() })
content.setMenu(null)
contextMenu({
window: content,
showLookUpSelection: false,
showSearchWithGoogle: false,
showCopyImage: false,
showCopyImageAddress: true,
showSaveImage: false,
showSaveImageAs: false,
showSaveLinkAs: false,
showInspectElement: true,
showServices: false,
labels: {
inspect: "Inspect in DevTools"
}
})
content.on("close", (ev) => { ev.preventDefault() })
content.on("minimize", (ev) => { ev.preventDefault() })
content.on("restore", (ev) => { ev.preventDefault() })
content.on("maximize", (ev) => { ev.preventDefault() })
content.on("unmaximize", (ev) => { ev.preventDefault() })
content.on("enter-full-screen", (ev) => { ev.preventDefault() })
content.on("leave-full-screen", (ev) => { ev.preventDefault() })
/* ignore certain window events */
content.on("page-title-updated", (ev) => {
ev.preventDefault()
})
/* remember window object */
this.content = content
/* adjust contents */
content.webContents.on("dom-ready", async (ev) => {
/* load postload script once the DOM is ready */
const code = await fs.promises.readFile(
path.join(__dirname, "vingester-browser-postload.js"),
{ encoding: "utf8" })
content.webContents.executeJavaScript(code)
/* optionally patch content */
if (this.cfg.q !== "" || this.cfg.Q !== "") {
setTimeout(async () => {
/* determine target frame */
const mainFrame = content.webContents.mainFrame
let frame
if (this.cfg.j === "")
frame = mainFrame.top
else {
const regexp = new RegExp(this.cfg.j)
frame = mainFrame.framesInSubtree.find((frame) => regexp.test(frame.url))
}
if (frame === undefined || frame === null)
return
/* patch content */
let script = ""
if (this.cfg.q !== "") {
let css = this.cfg.q
if (this.cfg.g === "file")
css = await fs.promises.readFile(css, { encoding: "utf8" })
css = css.replace(/[""]/g, "\\\"").replace(/\r?\n/g, "\\n")
script += `;(function () {
const style = document.createElement("style");
style.type = "text/css";
style.appendChild(document.createTextNode("${css}"));
const head = document.getElementsByTagName("head")[0];
head.appendChild(style);
})();`
}
if (this.cfg.Q !== "") {
let js = this.cfg.Q
if (this.cfg.G === "file")
js = await fs.promises.readFile(js, { encoding: "utf8" })
script += js
}
frame.executeJavaScript(script, true)
}, this.cfg.k)
}
/* force zoom level (sometimes Chromium keeps old factors if
just the "zoomFactor" attribute is used) */
content.webContents.setZoomFactor(this.cfg.z)
})
/* finally load the Web Content */
return new Promise((resolve, reject) => {
content.webContents.once("did-fail-load", (ev, code, desc, url, isMainFrame) => {
ev.preventDefault()
this.log.info(`browser: content: failed (code: ${code}, desc: ${desc}, url: ${url}, isMainFrame: ${isMainFrame})`)
this.control.webContents.send("message", `browser: content: failed (code: ${code}, desc: ${desc}, url: ${url}, isMainFrame: ${isMainFrame})`)
this.starting = false
resolve(isMainFrame ? false : true)
})
content.webContents.once("did-finish-load", (ev) => {
ev.preventDefault()
this.log.info("browser: content: started")
this.update()
this.starting = false
resolve(true)
})
content.loadURL(this.cfg.u)
})
}
/* update browser (after reconfiguration) */
update () {
this.log.info("browser: update")
/* optionally update already running worker browser instance */
if (this.worker !== null) {
this.worker.webContents.send("browser-worker-reconfigure", {
...this.cfg,
controlId: this.control.webContents.id,
workerId: this.worker.webContents.id
})
}
/* optionally update already running content browser instance */
if (this.content !== null) {
if (this.cfg.D) {
if (this.framerateNow <= 0) {
if (this.subscribed) {
this.log.info("browser: stopping frame capturing (method: frame)")
this.framesToSkip = this.framerateSource
this.content.webContents.endFrameSubscription()
this.subscribed = false
}
}
else {
const framesToSkip = Math.trunc((this.framerateSource / this.framerateNow) - 1)
if (this.framesToSkip !== framesToSkip) {
this.log.info("browser: changing capturing frame rate to " +
`${this.framerateNow} (method: frame)`)
this.framesToSkip = framesToSkip
}
if (!this.subscribed) {
this.log.info("browser: starting frame capturing (method: frame)")
this.content.webContents.beginFrameSubscription(false, this.subscriber)
this.subscribed = true
}
}
}
else if (this.cfg.N) {
if (this.framerateNow <= 0) {
if (this.subscribed) {
this.log.info("browser: stopping frame capturing (method: paint)")
this.content.webContents.stopPainting()
this.content.webContents.off("paint", this.subscriber)
this.subscribed = false
}
}
else {
if (this.content.webContents.getFrameRate() !== this.framerateNow) {
this.log.info("browser: changing capturing frame rate to " +
`${this.framerateNow} (method: paint)`)
this.content.webContents.setFrameRate(this.framerateNow)
}
if (!this.subscribed) {
this.log.info("browser: starting frame capturing (method: paint)")
this.content.webContents.on("paint", this.subscriber)
this.content.webContents.startPainting()
this.subscribed = true
}
}
}
}
}
/* reload browser */
reload () {
this.log.info("browser: reload")
if (this.content === null)
throw new Error("still not started")
this.content.reload()
}
/* stop browser */
async stop () {
/* stop just once */
if (this.stopping)
return
this.stopping = true
this.log.info("browser: stop")
/* sanity check situation */
if (this.content === null || this.worker === null)
throw new Error("browser still not started")
/* stop frame capturing */
if (this.cfg.D) {
if (this.subscribed) {
this.content.webContents.endFrameSubscription()
this.subscribed = false
}
}
else if (this.cfg.N) {
if (this.subscribed) {
this.content.webContents.off("paint", this.subscriber)
this.content.webContents.stopPainting()
this.subscribed = false
}
}
/* notify worker and wait until its processVideo/processAudio
callbacks were at least done one last time */
this.worker.webContents.send("browser-worker-stop")
await new Promise((resolve) => {
electron.ipcMain.on("browser-worker-stopped", () => {
resolve()
})
})
/* remove all listeners */
this.worker.removeAllListeners()
this.worker.webContents.removeAllListeners()
this.content.removeAllListeners()
this.content.webContents.removeAllListeners()
/* destroy content and worker browsers the soft way */
const p1 = new Promise((resolve) => this.worker.once("closed", resolve))
const p2 = new Promise((resolve) => this.content.once("closed", resolve))
const p3 = new Promise((resolve) => setTimeout(resolve, 1000))
this.worker.close()
this.content.close()
await bluebird.any([ Promise.all([ p1, p2 ]), p3 ])
/* destroy content and worker browsers the hard way */
if (!this.worker.isDestroyed())
this.worker.destroy()
if (!this.content.isDestroyed())
this.content.destroy()
/* reset the internal state */
this.reset()
this.log.info("browser: stopped")
this.stopping = false
return true
}
/* clear browser */
async clear () {
if (!this.cfg.S)
return
const name = `vingester-browser-content-${this.id.toLowerCase()}`
const session = electron.session.fromPartition(`persist:${name}`)
await session.clearCache()
await session.clearAuthCache()
await session.clearHostResolverCache()
await session.clearStorageData()
await new Promise((resolve, reject) => {
const p = path.join(electron.app.getPath("userData"), "Partitions", name)
this.log.info(`browser: clearing session persistance area: "${p}"`)
rimraf(p, { disableGlob: true }, (err) => {
if (err) reject(err)
else resolve()
})
})
return true
}
}