-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathrecord.mjs
381 lines (343 loc) · 9.06 KB
/
record.mjs
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
import mime from 'mime';
import fs from 'fs';
import path from 'path';
import child_process from 'child_process';
import module from 'module';
import Sunniesnow from './sunniesnow.mjs';
import DEFAULT_GAME_SETTINGS from './default-settings.mjs'
const require = module.createRequire(import.meta.url);
const audioBufferToWav = require('audiobuffer-to-wav');
Sunniesnow.Record = class Record {
static DEFAULT_SETTINGS = {
levelFile: 'upload',
levelFileOnline: '',
levelFileUpload: null,
musicSelect: '',
chartSelect: '',
lyrica5: true,
speed: 2,
noteSize: 1,
background: 'online',
backgroundOnline: 'default.svg',
backgroundFromLevel: '',
backgroundUpload: null,
backgroundBlur: 100,
backgroundBrightness: 0.5,
skin: 'default',
skinOnline: '',
skinUpload: null,
fx: 'default',
fxOnline: '',
fxUpload: null,
hudTopCenter: 'combo',
hudTopLeft: 'title',
hudTopRight: 'score',
doubleLineTap: true,
doubleLineHold: false,
doubleLineDrag: false,
doubleLineFlick: false,
hideFxInFront: false,
hideFxPerfect: false,
hideFxHoldStart: false,
scrollJudgementLine: 0.8,
scrollDistance: 1,
hideTipPoints: false,
hideNotes: false,
hideCircles: false,
hideBgNotes: false,
hideFx: false,
hideBgPattern: false,
fadingStart: 1,
fadingDuration: 0.2,
reverseNoteOrder: false,
circleMovesWithNote: false,
se: 'default',
seOnline: '',
seUpload: null,
volumeSe: 1,
volumeMusic: 1,
delay: 0,
scroll: false,
chartOffset: 0,
gameSpeed: 1,
horizontalFlip: false,
verticalFlip: false,
start: 0,
end: 1,
beginningPreparationTime: 1,
nickname: 'New Poet',
avatar: 'online',
avatarOnline: 'default.svg',
avatarUpload: null,
avatarGravatar: '',
width: 1920,
height: 1080,
avoidDownloadingFonts: false,
plugin: [],
pluginOnline: [],
pluginUpload: [],
help: false,
fps: 60,
quiet: false,
suppressWarnings: false,
tempDir: process.env.TMPDIR || process.env.TEMP || '/tmp',
output: process.env.SUNNIESNOW_OUTPUT || 'output.mkv',
resultsDuration: 1,
waitForMusic: false,
clean: false,
ffmpeg: 'ffmpeg',
ffmpegOptions: process.env.SUNNIESNOW_FFMPEG_OPTIONS || ''
}
static HELP_MESSAGE = `Usage: sunniesnow-record [options]
--help=false print this message
--fps=60 frame rate of the output video
--quiet=false do not print anything to stdout
--suppress-warnings do not print warnings to stderr
--temp-dir=$TMPDIR directory to store temporary files
--output=output.mkv output file name
--results-duration=1 duration of the results screen in seconds
--wait-for-music=false do not end the video until music finishes
--clean=false do not use assets downloaded before
--ffmpeg=ffmpeg path to ffmpeg executable
--ffmpeg-options= extra options to pass to ffmpeg
See https://sunniesnow.github.io/game/help about following options:
--level-file
--level-file-online
--level-file-upload
--music-select
--chart-select
--lyrica-5
--speed
--note-size
--background
--background-online
--background-from-level
--background-upload
--background-blur
--background-brightness
--skin
--skin-online
--skin-upload
--fx
--fx-online
--fx-upload
--hud-top-center
--hud-top-left
--hud-top-right
--double-line-tap
--double-line-hold
--double-line-drag
--double-line-flick
--hide-fx-in-front
--hide-fx-perfect
--hide-fx-hold-start
--scroll-judgement-line
--scroll-distance
--hide-tip-points
--hide-notes
--hide-circles
--hide-bg-notes
--hide-fx
--hide-bg-pattern
--fading-start
--fading-duration
--reverse-note-order
--circle-moves-with-note
--se
--se-online
--se-upload
--volume-se
--volume-music
--delay
--scroll
--chart-offset
--game-speed
--horizontal-flip
--vertical-flip
--start
--end
--beginning-preparation-time
--nickname
--avatar
--avatar-online
--avatar-upload
--avatar-gravatar
--width
--height
--avoid-downloading-fonts
--plugin
--plugin-online
--plugin-upload`
static toBlob(obj) {
if (typeof obj === 'string') {
return new Blob([fs.readFileSync(obj)], {type: mime.getType(obj)});
}
if (obj instanceof Array) {
return obj.map(this.toBlob.bind(this));
}
if (obj instanceof Blob) {
return obj;
}
return new Blob([obj]);
}
static replaceWithBlob(options) {
for (const key in options) {
if (key.endsWith('Upload')) {
options[key] = this.toBlob(options[key]);
}
}
}
constructor(options) {
options = Object.assign({}, this.constructor.DEFAULT_SETTINGS, options);
this.quiet = options.quiet;
delete options.quiet;
this.suppressWarnings = options.suppressWarnings;
delete options.suppressWarnings;
this.fps = options.fps;
delete options.fps;
this.width = options.width;
this.height = options.height;
this.resultsDuration = options.resultsDuration;
delete options.resultsDuration;
this.tempDir = options.tempDir;
delete options.tempDir;
this.output = options.output;
delete options.output;
this.waitForMusic = options.waitForMusic;
delete options.waitForMusic;
this.clean = options.clean;
delete options.clean;
this.ffmpeg = options.ffmpeg;
delete options.ffmpeg;
this.ffmpegOptions = options.ffmpegOptions;
delete options.ffmpegOptions;
this.constructor.replaceWithBlob(options);
this.gameSettings = options;
}
makeFfmpegOptions(options) {
if (this.ffmpegOptions) {
return [...this.ffmpegOptions.split(' '), ...options];
} else {
return options;
}
}
async createVideoGeneratingFfmpeg() {
this.videoGeneratingFfmpeg = child_process.spawn(this.ffmpeg, this.makeFfmpegOptions([
// video input
'-f', 'rawvideo',
'-pixel_format', 'rgba',
'-framerate', this.fps.toString(),
'-video_size', `${this.width}x${this.height}`,
'-i', 'pipe:0',
// output
'-y',
'-vf', 'vflip',
path.join(this.tempDir, 'video.mkv')
]), {stdio: ['pipe', 'inherit', 'inherit']});
this.videoPipe = this.videoGeneratingFfmpeg.stdin;
this.tempPixels = new Uint8Array(this.width * this.height * 4);
}
print(string) {
if (!this.quiet) {
process.stdout.write(string);
}
}
reprint(string) {
if (!this.quiet) {
process.stdout.clearLine();
process.stdout.cursorTo(0);
process.stdout.write(string);
}
}
println(string) {
if (!this.quiet) {
process.stdout.write(string + '\n');
}
}
async load() {
this.println('Loading...')
fs.mkdirSync(this.tempDir, {recursive: true});
Sunniesnow.game = new Sunniesnow.Game();
Sunniesnow.game.settings = Object.assign({}, DEFAULT_GAME_SETTINGS, this.gameSettings);
await Sunniesnow.Loader.loadChart();
Sunniesnow.Loader.load();
await Sunniesnow.Utils.until(time => {
Sunniesnow.game.app?.ticker?.update(time);
return Sunniesnow.game.scene && !(Sunniesnow.game.scene instanceof Sunniesnow.SceneLoading);
});
this.createVideoGeneratingFfmpeg();
}
async screenshot() {
const gl = Sunniesnow.game.canvas._gl;
// use RGBA instead of RGB because of https://github.com/stackgl/headless-gl/issues/265
gl.readPixels(0, 0, this.width, this.height, gl.RGBA, gl.UNSIGNED_BYTE, this.tempPixels);
await new Promise(resolve => this.videoPipe.write(this.tempPixels, resolve));
}
async exportAudio() {
this.println('Exporting audio...');
const audioBuffer = await Sunniesnow.Audio.context.startRendering();
fs.writeFileSync(
path.join(this.tempDir, 'audio.wav'),
Buffer.from(audioBufferToWav(audioBuffer))
);
}
async runFfmpeg() {
this.println('Combining video and audio...');
fs.mkdirSync(path.dirname(this.output), {recursive: true});
this.ffmpegProcess = child_process.spawn(this.ffmpeg, this.makeFfmpegOptions([
'-i', path.join(this.tempDir, 'video.mkv'),
'-i', path.join(this.tempDir, 'audio.wav'),
'-y',
'-nostdin',
'-map', '0:v',
'-map', '1:a',
'-c:v', 'copy',
'-shortest',
this.output
]), {stdio: 'inherit'});
await new Promise(resolve => this.ffmpegProcess.on('exit', resolve));
}
async end() {
this.println('');
this.println('Waiting for FFmpeg to finish eating the video...')
await new Promise(resolve => this.videoPipe.end(resolve));
await new Promise(resolve => this.videoGeneratingFfmpeg.on('exit', resolve));
}
async run() {
await this.load();
Sunniesnow.game.app.ticker.lastTime = -1;
let frameCount = 0;
let firstResultFrame;
while (true) {
let breakCondition = !!firstResultFrame;
breakCondition &&= (frameCount - firstResultFrame) / this.fps > this.resultsDuration
breakCondition &&= !this.waitForMusic || Sunniesnow.Music.finished
if (breakCondition) {
break;
}
const currentTime = frameCount / this.fps;
//this.reprint(`Rendering ${currentTime.toFixed(2)}s...`)
Sunniesnow.Audio.currentTime = currentTime;
Sunniesnow.game.app.ticker.update(currentTime * 1000);
await this.screenshot();
if (Sunniesnow.game.level.finished && !firstResultFrame) {
firstResultFrame = frameCount;
}
frameCount++;
}
await this.end();
await this.exportAudio();
await this.runFfmpeg();
this.println('Done!');
}
static async run(options) {
if (options.help) {
console.log(this.HELP_MESSAGE);
process.exit();
}
Sunniesnow.record = new this(options);
await Sunniesnow.record.run();
process.exit();
}
};
export default Sunniesnow.Record;