-
Notifications
You must be signed in to change notification settings - Fork 4
/
slp_to_video.js
600 lines (571 loc) · 16.9 KB
/
slp_to_video.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
// Copyright (C) 2020 Kevin J. Sung
//
// This program is free software; you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation; either version 2 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License along
// with this program; if not, write to the Free Software Foundation, Inc.,
// 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
const { spawn } = require("child_process")
const crypto = require("crypto")
const fs = require("fs")
const fsPromises = require("fs").promises
const os = require("os")
const path = require("path")
const readline = require("readline")
const dir = require("node-dir")
const { default: SlippiGame } = require("slp-parser-js")
const EFB_SCALE = {
"1x": 2,
"2x": 4,
"3x": 6,
"4x": 7,
"5x": 8,
"6x": 9,
}
const generateReplayConfigs = async (replays, basedir) => {
const dirname = path.join(
basedir,
`tmp-${crypto.randomBytes(12).toString("hex")}`
)
await fsPromises.mkdir(dirname)
await fsPromises.writeFile(
path.join(dirname, "outputPath.txt"),
replays.outputPath
)
await fsPromises.mkdir(dirname, { recursive: true })
for (const [index, replay] of replays.queue.entries()) {
generateReplayConfig(replay, index, dirname)
}
}
const generateReplayConfig = async (replay, index, basedir) => {
const game = new SlippiGame(replay.path)
const metadata = game.getMetadata()
let startFrame = replay.startFrame
if (!startFrame && startFrame !== 0) {
startFrame = -123
}
let endFrame = replay.endFrame
if (!endFrame && endFrame !== 0) {
endFrame = metadata.lastFrame
}
endFrame = Math.min(endFrame, metadata.lastFrame)
const config = {
mode: "normal",
replay: replay.path,
startFrame,
endFrame,
isRealTimeMode: false,
commandId: `${crypto.randomBytes(12).toString("hex")}`,
overlayPath: replay.overlayPath,
}
const configFn = path.join(basedir, `${index}.json`)
await fsPromises.writeFile(configFn, JSON.stringify(config))
}
const exit = (process) =>
new Promise((resolve, reject) => {
process.on("exit", (code, signal) => {
resolve(code, signal)
})
})
const close = (stream) =>
new Promise((resolve, reject) => {
stream.on("close", (code, signal) => {
resolve(code, signal)
})
})
const executeFunctionInQueue = async (func, argsArray, numWorkers) => {
const numTasks = argsArray.length
let count = 0
if (process.stdout.isTTY) process.stdout.write(`${count}/${numTasks}`)
const worker = async () => {
let args
while ((args = argsArray.pop()) !== undefined) {
await func(args)
count++
if (process.stdout.isTTY) {
process.stdout.clearLine()
process.stdout.cursorTo(0)
process.stdout.write(`${count}/${numTasks}`)
}
}
}
const workers = []
while (workers.length < numWorkers) {
workers.push(worker())
}
while (workers.length > 0) {
await workers.pop()
}
if (process.stdout.isTTY) process.stdout.write("\n")
}
const executeCommandsInQueue = async (
command,
argsArray,
numWorkers,
options,
onSpawn
) => {
const numTasks = argsArray.length
let count = 0
if (process.stdout.isTTY) process.stdout.write(`${count}/${numTasks}`)
const worker = async () => {
let args
while ((args = argsArray.pop()) !== undefined) {
const process_ = spawn(command, args, options)
const exitPromise = exit(process_)
if (onSpawn) {
await onSpawn(process_, args)
}
await exitPromise
count++
if (process.stdout.isTTY) {
process.stdout.clearLine()
process.stdout.cursorTo(0)
process.stdout.write(`${count}/${numTasks}`)
}
}
}
const workers = []
while (workers.length < numWorkers) {
workers.push(worker())
}
while (workers.length > 0) {
await workers.pop()
}
if (process.stdout.isTTY) process.stdout.write("\n")
}
const killDolphinOnEndFrame = (process) => {
let endFrame = Infinity
process.stdout.setEncoding("utf8")
process.stdout.on("data", (data) => {
const lines = data.split("\r\n")
lines.forEach((line) => {
if (line.includes(`[PLAYBACK_END_FRAME]`)) {
const regex = /\[PLAYBACK_END_FRAME\] ([0-9]*)/
const match = regex.exec(line)
endFrame = match[1]
} else if (line.includes(`[CURRENT_FRAME] ${endFrame}`)) {
process.kill()
}
})
})
}
const processReplayConfigs = async (files, config) => {
const dolphinArgsArray = []
const ffmpegMergeArgsArray = []
const ffmpegOverlayArgsArray = []
const replaysWithOverlays = []
let promises = []
// Construct arguments to commands
files.forEach((file) => {
const promise = fsPromises.readFile(file).then((contents) => {
const overlayPath = JSON.parse(contents).overlayPath
const { dir, name } = path.parse(file)
const basename = path.join(dir, name)
// Arguments to Dolphin
dolphinArgsArray.push([
"-i",
file,
"-o",
name,
`--output-directory=${dir}`,
"-b",
"-e",
config.ssbmIsoPath,
"--cout",
])
// Arguments for ffmpeg merging
const ffmpegMergeArgs = [
"-i",
`${basename}.avi`,
"-i",
`${basename}.wav`,
"-b:v",
`${config.bitrateKbps}k`,
]
if (config.resolution === "2x" && !config.widescreenOff) {
// Slightly upscale to 1920x1080
ffmpegMergeArgs.push("-vf")
ffmpegMergeArgs.push("scale=1920:1080")
}
ffmpegMergeArgs.push(`${basename}-merged.avi`)
ffmpegMergeArgsArray.push(ffmpegMergeArgs)
// Arguments for adding overlays
if (overlayPath) {
ffmpegOverlayArgsArray.push([
"-i",
`${basename}-merged.avi`,
"-i",
overlayPath,
"-b:v",
`${config.bitrateKbps}k`,
"-filter_complex",
"[0:v][1:v] overlay",
`${basename}-overlaid.avi`,
])
replaysWithOverlays.push(basename)
}
})
promises.push(promise)
})
await Promise.all(promises)
// Dump frames to video and audio
console.log("Dumping video frames and audio...")
await executeCommandsInQueue(
config.dolphinPath,
dolphinArgsArray,
config.numProcesses,
{},
killDolphinOnEndFrame
)
// Merge video and audio files
console.log("Merging video and audio...")
await executeCommandsInQueue(
"ffmpeg",
ffmpegMergeArgsArray,
config.numProcesses,
{ stdio: "ignore" }
)
// Delete unmerged video and audio files to save space
promises = []
files.forEach((file) => {
const basename = path.join(path.dirname(file), path.basename(file, ".json"))
promises.push(fsPromises.unlink(`${basename}.avi`))
promises.push(fsPromises.unlink(`${basename}.wav`))
})
await Promise.all(promises)
// Add overlay
console.log("Adding overlays...")
await executeCommandsInQueue(
"ffmpeg",
ffmpegOverlayArgsArray,
config.numProcesses,
{ stdio: "ignore" }
)
// Delete non-overlaid video files
promises = []
replaysWithOverlays.forEach((basename) => {
promises.push(fsPromises.unlink(`${basename}-merged.avi`))
})
await Promise.all(promises)
}
const getMinimumDuration = async (videoFile) => {
const audioArgs = [
"-select_streams",
"a:0",
"-show_entries",
"stream=duration",
videoFile,
]
const videoArgs = [
"-select_streams",
"v:0",
"-show_entries",
"stream=duration",
videoFile,
]
const audioProcess = spawn("ffprobe", audioArgs)
const audioClose = close(audioProcess.stdout)
const videoProcess = spawn("ffprobe", videoArgs)
const videoClose = close(videoProcess.stdout)
audioProcess.stdout.setEncoding("utf8")
videoProcess.stdout.setEncoding("utf8")
const regex = /duration=([0-9]*\.[0-9]*)/
let audioDuration
let videoDuration
audioProcess.stdout.on("data", (data) => {
const match = regex.exec(data)
audioDuration = match[1]
})
videoProcess.stdout.on("data", (data) => {
const match = regex.exec(data)
videoDuration = match[1]
})
await audioClose
await videoClose
return Math.min(audioDuration, videoDuration)
}
const concatenateVideos = async (dir, config) => {
await fsPromises.readdir(dir).then(async (files) => {
// Get sorted list of video files to concatenate
let replayVideos = files.filter((file) => file.endsWith("merged.avi"))
replayVideos = replayVideos.concat(
files.filter((file) => file.endsWith("overlaid.avi"))
)
if (!replayVideos.length) return
const regex = /([0-9]*).*/
replayVideos.sort((file1, file2) => {
const index1 = regex.exec(file1)[1]
const index2 = regex.exec(file2)[1]
return index1 - index2
})
// Compute correct video durations (minimum of audio and video streams)
const durations = {}
const promises = []
replayVideos.forEach((file) => {
const promise = getMinimumDuration(path.join(dir, file)).then(
(duration) => {
durations[file] = duration
}
)
promises.push(promise)
})
await Promise.all(promises)
// Generate ffmpeg input file
const concatFn = path.join(dir, "concat.txt")
const stream = fs.createWriteStream(concatFn)
replayVideos.forEach((file) => {
stream.write(`file '${path.join(dir, file)}'\n`)
stream.write("inpoint 0.0\n")
stream.write(`outpoint ${durations[file]}\n`)
})
stream.end()
// Concatenate
await fsPromises
.readFile(path.join(dir, "outputPath.txt"), { encoding: "utf8" })
.then(async (outputPath) => {
const args = [
"-y",
"-f",
"concat",
"-safe",
"0",
"-segment_time_metadata",
"1",
"-i",
concatFn,
"-vf",
"select=concatdec_select",
"-af",
"aselect=concatdec_select,aresample=async=1",
"-b:v",
`${config.bitrateKbps}k`,
outputPath,
]
const process = spawn("ffmpeg", args, { stdio: "ignore" })
await exit(process)
})
})
}
const files = (rootdir) =>
new Promise((resolve, reject) => {
dir.files(rootdir, (err, files) => {
if (err) reject(err)
resolve(files)
})
})
const subdirs = (rootdir) =>
new Promise((resolve, reject) => {
dir.subdirs(rootdir, (err, subdirs) => {
if (err) reject(err)
resolve(subdirs)
})
})
const configureDolphin = async (config) => {
const dolphinDirname = path.dirname(config.dolphinPath)
const gameSettingsFilename = path.join(
dolphinDirname,
"User",
"GameSettings",
"GALE01.ini"
)
const graphicsSettingsFilename = path.join(
dolphinDirname,
"User",
"Config",
"GFX.ini"
)
// Game settings
// TODO maybe preserve existing settings here, would require parsing file
let newSettings = ["[Gecko]", "[Gecko_Enabled]"]
if (!config.gameMusicOn) newSettings.push("$Optional: Game Music OFF")
if (config.hideHud) newSettings.push("$Optional: Hide HUD")
if (config.hideTags) newSettings.push("$Optional: Hide Tags")
if (config.disableChants)
newSettings.push("$Optional: Prevent Character Crowd Chants")
if (config.fixedCamera) newSettings.push("$Optional: Fixed Camera Always")
if (!config.widescreenOff) newSettings.push("$Optional: Widescreen 16:9")
newSettings.push("[Gecko_Disabled]")
if (config.hideNames) newSettings.push("$Optional: Show Player Names")
await fsPromises.writeFile(gameSettingsFilename, newSettings.join("\n"))
// Graphics settings
rl = readline.createInterface({
input: fs.createReadStream(graphicsSettingsFilename),
crlfDelay: Infinity,
})
newSettings = []
const aspectRatioSetting = config.widescreenOff ? 5 : 6
for await (const line of rl) {
if (line.startsWith("AspectRatio")) {
newSettings.push(`AspectRatio = ${aspectRatioSetting}`)
} else if (line.startsWith("BitrateKbps")) {
newSettings.push(`BitrateKbps = ${config.bitrateKbps}`)
} else if (line.startsWith("EFBScale")) {
newSettings.push(`EFBScale = ${EFB_SCALE[config.resolution]}`)
} else {
newSettings.push(line)
}
}
await fsPromises.writeFile(graphicsSettingsFilename, newSettings.join("\n"))
}
const slpToVideo = async (replayLists, config) => {
await fsPromises
.access(config.ssbmIsoPath)
.catch((err) => {
if (err.code === "ENOENT") {
throw new Error(
`Could not read SSBM iso from path ${config.ssbmIsoPath}. ` +
"Did you forget to specify the --ssbm-iso-path option?"
)
} else {
throw err
}
})
.then(() => fsPromises.access(config.dolphinPath))
.catch((err) => {
if (err.code === "ENOENT") {
throw new Error(
`Could not open Dolphin from path ${config.dolphinPath}. ` +
"Did you forget to specify the --dolphin-path option?"
)
} else {
throw err
}
})
.then(() => configureDolphin(config))
.then(() => fsPromises.mkdir(config.tmpdir))
.then(async () => {
const promises = []
replayLists.forEach((replays) =>
promises.push(generateReplayConfigs(replays, config.tmpdir))
)
await Promise.all(promises)
})
.then(() => files(config.tmpdir))
.then(async (files) => {
files = files.filter((file) => path.extname(file) === ".json")
await processReplayConfigs(files, config)
})
.then(() => subdirs(config.tmpdir))
.then(async (subdirs) => {
console.log("Concatenating videos...")
await executeFunctionInQueue(
(dir) => concatenateVideos(dir, config),
subdirs,
config.numProcesses
)
console.log("Done.")
})
.then(() => fsPromises.rm(config.tmpdir, { recursive: true }))
.catch((err) => {
console.error(err)
})
}
const main = () => {
const argv = require("yargs").command(
"$0 INPUT_FILE",
"Convert .slp files to video.",
(yargs) => {
yargs.positional("INPUT_FILE", {
describe:
"Describes the input .slp files and output filenames. " +
"See example_input.json for an example.",
type: "string",
})
yargs.option("num-processes", {
describe: "The number of processes to use.",
default: 1,
type: "number",
})
yargs.option("dolphin-path", {
describe: "Path to the Dolphin executable.",
default: path.join("Ishiiruka", "build", "Binaries", "dolphin-emu"),
type: "string",
})
yargs.option("ssbm-iso-path", {
describe: "Path to the SSBM ISO image.",
default: "SSBM.iso",
type: "string",
})
yargs.option("game-music-on", {
describe: "Turn game music on.",
type: "boolean",
})
yargs.option("hide-hud", {
describe: "Hide percentage and stock icons.",
type: "boolean",
})
yargs.option("hide-tags", {
describe: "Hide tags.",
type: "boolean",
})
yargs.option("hide-names", {
describe: "Hide player names.",
type: "boolean",
})
yargs.option("disable-chants", {
describe: "Disable character crowd chants.",
type: "boolean",
})
yargs.option("fixed-camera", {
describe: "Fixed camera mode.",
type: "boolean",
})
yargs.option("widescreen-off", {
describe: "Turn off widescreen.",
type: "boolean",
})
yargs.option("bitrate-kbps", {
describe: "Bitrate in kbps.",
default: 15000,
type: "number",
})
yargs.option("resolution", {
describe: "Internal resolution multiplier.",
default: "2x",
type: "string",
})
yargs.option("tmpdir", {
describe: "Temporary directory to use (temporary files may be large).",
default: path.join(
os.tmpdir(),
`tmp-${crypto.randomBytes(12).toString("hex")}`
),
type: "string",
})
}
).argv
const config = {
numProcesses: argv.numProcesses,
dolphinPath: path.resolve(argv.dolphinPath),
ssbmIsoPath: path.resolve(argv.ssbmIsoPath),
tmpdir: path.resolve(argv.tmpdir),
gameMusicOn: argv.gameMusicOn,
hideHud: argv.hideHud,
hideTags: argv.hideTags,
hideNames: argv.hideNames,
disableChants: argv.disableChants,
fixedCamera: argv.fixedCamera,
widescreenOff: argv.widescreenOff,
bitrateKbps: argv.bitrateKbps,
resolution: argv.resolution,
}
fsPromises
.readFile(path.resolve(argv.INPUT_FILE))
.then((contents) => JSON.parse(contents))
.then((replays) =>
slpToVideo(Array.isArray(replays) ? replays : [replays], config)
)
}
if (module === require.main) {
main()
}
module.exports = slpToVideo