-
Notifications
You must be signed in to change notification settings - Fork 160
Expand file tree
/
Copy pathprocessQueue.js
More file actions
745 lines (658 loc) · 19.9 KB
/
Copy pathprocessQueue.js
File metadata and controls
745 lines (658 loc) · 19.9 KB
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
import os from 'os'
import fs from 'fs/promises'
import path from 'path'
import childProcess from 'child_process'
import treeKill from 'tree-kill'
import sanitizeFilename from 'sanitize-filename'
import { app, BrowserWindow, powerSaveBlocker } from 'electron'
let statusUpdateCallback = null,
donateUpdateCallback = null
let ytCacheDir = null
let curItems = [],
curChildProcess = null
let curProgressFtStemIdx = null
function getPathToThirdPartyApps() {
if (process.env.NODE_ENV === 'dev') {
if (process.platform === 'win32') {
return path.resolve(path.join(import.meta.dirname, '..', 'win-extra-files', 'ThirdPartyApps'))
} else if (process.platform === 'darwin') {
return path.resolve(path.join(import.meta.dirname, '..', 'mac-extra-files', 'ThirdPartyApps'))
} else {
return null
}
} else {
if (process.platform === 'win32' || process.platform === 'darwin') {
return path.resolve(path.join(process.resourcesPath, '..', 'ThirdPartyApps'))
} else {
return null
}
}
}
function getPathToModels() {
if (process.env.NODE_ENV === 'dev') {
if (process.platform === 'win32' || process.platform === 'darwin') {
return path.resolve(path.join(import.meta.dirname, '..', 'anyos-extra-files', 'Models'))
} else {
return null
}
} else {
if (process.platform === 'win32' || process.platform === 'darwin') {
return path.resolve(path.join(process.resourcesPath, '..', 'Models'))
} else {
return null
}
}
}
const PATH_TO_THIRD_PARTY_APPS = getPathToThirdPartyApps()
const PATH_TO_MODELS = getPathToModels()
const PATH_TO_DEMUCS = PATH_TO_THIRD_PARTY_APPS
? path.join(PATH_TO_THIRD_PARTY_APPS, 'demucs-cxfreeze')
: null
const PATH_TO_FFMPEG = PATH_TO_THIRD_PARTY_APPS
? path.join(PATH_TO_THIRD_PARTY_APPS, 'ffmpeg', 'bin')
: null
const PATH_TO_YT_DLP = PATH_TO_THIRD_PARTY_APPS
? path.join(PATH_TO_THIRD_PARTY_APPS, 'yt-dlp')
: null
const DEMUCS_EXE_NAME = PATH_TO_THIRD_PARTY_APPS ? 'demucs-cxfreeze' : 'demucs'
const FFMPEG_EXE_NAME = 'ffmpeg'
const YT_DLP_EXE_NAME = 'yt-dlp'
const CHILD_PROCESS_ENV = {
...process.env,
LANG: null, // Will be set when ready to split, since we can only check system locale after `app` is ready
}
if (PATH_TO_THIRD_PARTY_APPS) {
// Override the system's PATH with the path to our own bundled third-party apps
CHILD_PROCESS_ENV.PATH =
PATH_TO_DEMUCS +
(process.platform === 'win32' ? ';' : ':') +
PATH_TO_FFMPEG +
(process.platform === 'win32' ? ';' : ':') +
PATH_TO_YT_DLP
}
const TMP_PREFIX = 'StemRoller-'
function getJobCount() {
const MAX_NUM_JOBS = 4
const numMemories = Math.floor(os.freemem() / 2000000000) // Need approximately 2GB per track
const numCpus = os.cpus().length
return Math.max(1, Math.min(Math.min(numCpus, numMemories), MAX_NUM_JOBS))
}
function killCurChildProcess() {
if (curChildProcess) {
try {
console.trace(`treeKill process ${curChildProcess.pid}`)
treeKill(curChildProcess.pid)
} catch (err) {
console.trace(`treeKill failed: ${err}`)
}
curChildProcess = null
}
}
function updateProgressRaw(videoId, progress) {
let mainWindow = BrowserWindow.getAllWindows()[0]
if (!mainWindow) {
return
}
mainWindow.webContents.send('videoStatusUpdate', {
videoId,
status: {
step: 'processing',
progress,
},
})
}
function updateDemucsProgress(videoId, data) {
// Check if the output contains the progress update
const progressMatch = data.toString().match(/\r\s+\d+%\|/)
if (progressMatch) {
let progress = parseInt(progressMatch)
if (isNaN(progress)) {
return
}
if (curProgressFtStemIdx !== null && progress === 0) {
++curProgressFtStemIdx
}
progress /= 100
updateProgressRaw(
videoId,
(curProgressFtStemIdx === null ? progress : (curProgressFtStemIdx - 1) / 4 + progress / 4) *
0.95
)
}
}
function spawnAndWait(videoId, cwd, command, args, isDemucs) {
return new Promise((resolve, reject) => {
killCurChildProcess()
CHILD_PROCESS_ENV.LANG = `${(app.getSystemLocale() || 'en-US').replace('-', '_')}.UTF-8` // Set here instead of when CHILD_PROCESS_ENV defined, because app must be ready before we can read the system locale
curChildProcess = childProcess.spawn(command, args, {
cwd,
env: CHILD_PROCESS_ENV,
})
curChildProcess.stdout.on('data', (data) => {
console.log(`child stdout:\n${data}`)
})
curChildProcess.stderr.on('data', (data) => {
console.log(`child stderr:\n${data}`)
if (isDemucs) {
// For some reason the progress displays in stderr instead of stdout
updateDemucsProgress(videoId, data)
}
})
curChildProcess.on('error', (error) => {
reject(error)
killCurChildProcess()
})
curChildProcess.on('exit', (code, signal) => {
if (signal !== null) {
reject(new Error(`Child process exited due to signal: ${signal}`))
} else {
resolve(code)
}
curChildProcess = null
})
})
}
async function createYtCacheDir() {
if (ytCacheDir) {
return
}
ytCacheDir = await fs.mkdtemp(path.join(os.tmpdir(), 'StemRoller-cache-'))
}
export async function deleteYtCacheDir() {
if (!ytCacheDir) {
return
}
try {
await fs.rm(ytCacheDir, {
recursive: true,
maxRetries: 5,
retryDelay: 1000,
})
console.log(`Deleted cache folder "${ytCacheDir}"`)
} catch (error) {
console.trace(error)
}
}
async function downloadYoutube(videoId, downloadPath) {
await createYtCacheDir()
const videoUrl = `https://www.youtube.com/watch?v=${videoId}`
const ytDlpExeArgs = [
'-f',
'bestaudio',
'--cache-dir',
ytCacheDir,
'-o',
path.basename(downloadPath),
'--newline',
'--progress',
videoUrl,
]
await spawnAndWait(videoId, path.dirname(downloadPath), YT_DLP_EXE_NAME, ytDlpExeArgs, false)
}
async function findDemucsOutputDir(basePath) {
const entries = await fs.readdir(basePath, {
withFileTypes: true,
})
for (const entry of entries) {
if (entry.isDirectory()) {
return path.join(basePath, entry.name)
}
}
const hasFilesInBasePath = entries.some((entry) => entry.isFile())
if (hasFilesInBasePath) {
return basePath
}
throw new Error('Unable to find Demucs output directory')
}
async function listDemucsOutputFiles(basePath) {
const files = []
const entries = await fs.readdir(basePath, {
withFileTypes: true,
})
for (const entry of entries) {
if (entry.isFile()) {
files.push(path.join(basePath, entry.name))
}
}
return files
}
async function ensureFileExists(path) {
try {
await fs.access(path)
return true
} catch (error) {
return false
}
}
async function convertDemucsFiles({ videoId, tmpDir, filesList, filetype, compressionArgs }) {
console.log(`Converting files to format "${filetype}"`)
const result = []
for (const oldFilename of filesList) {
const parsedOldFilename = path.parse(oldFilename)
const newFilename = `${path.join(parsedOldFilename.dir, parsedOldFilename.name)}.${filetype}`
await spawnAndWait(
videoId,
tmpDir,
FFMPEG_EXE_NAME,
['-i', oldFilename, ...compressionArgs, newFilename],
false
)
const success = await ensureFileExists(newFilename)
if (!success) {
throw new Error(`Unable to access converted file "${newFilename}" - ffmpeg probably failed`)
}
result.push(newFilename)
}
return result
}
function getFfmpegCompressionArguments(filetype) {
if (filetype === 'mp3') {
return ['-q:a', '0']
} else if (filetype === 'flac') {
return ['-compression_level', '5']
} else if (filetype === 'wav') {
return []
}
throw new Error(`Unrecognized filetype: ${filetype}`)
}
async function _processVideo(video, tmpDir) {
const demucsModelName = getModelName()
const demucsStemsFiletype = getOutputFormat()
const compressionArgs = getFfmpegCompressionArguments(demucsStemsFiletype)
const needsPrefix = getPrefixStemFilenameWithSongName()
const needsOriginal = getPreserveOriginalAudio()
const beginTime = Date.now()
console.log(`BEGIN downloading/processing video "${video.videoId}" - "${video.title}"`)
setVideoStatusAndPath(video.videoId, { step: 'downloading' }, null)
let mediaPath = null
if (video.mediaSource === 'youtube') {
const ytFilename = 'yt-audio'
const ytPath = path.join(tmpDir, ytFilename)
console.log(`Downloading YouTube video "${video.videoId}"; storing in "${ytPath}"`)
await downloadYoutube(video.videoId, ytPath)
mediaPath = ytPath
} else if (video.mediaSource === 'local') {
mediaPath = video.localInputPath
} else {
throw new Error(`Invalid mediaSource: ${video.mediaSource}`)
}
const outputFolderName =
video.mediaSource === 'youtube'
? sanitizeFilename(`${video.title}-${video.videoId}`)
: sanitizeFilename(video.title)
const outputFilenamesPrefix = needsPrefix ? `${outputFolderName} - ` : ''
setVideoStatusAndPath(
video.videoId,
{
step: 'processing',
progress: 0,
},
null
)
const jobCount = getJobCount()
console.log(
`Splitting video "${video.videoId}"; ${jobCount} jobs using model "${demucsModelName}"...`
)
const demucsExeArgs = [mediaPath, '-n', demucsModelName, '-j', jobCount]
demucsExeArgs.push('--filename', '{stem}.{ext}')
if (getPyTorchBackend() === 'cpu') {
console.log('Running with "-d cpu" to force CPU instead of CUDA')
demucsExeArgs.push('-d', 'cpu')
} else if (process.platform === 'darwin') {
// Maybe need to apply https://github.com/facebookresearch/demucs/pull/575/files instead, in case MPS is not available on Intel Macs ??
console.log('Running with "-d mps" to force MPS instead of CPU/CUDA')
demucsExeArgs.push('-d', 'mps')
}
if (PATH_TO_MODELS) {
demucsExeArgs.push('--repo', PATH_TO_MODELS)
}
if (demucsModelName.indexOf('_ft') >= 0) {
curProgressFtStemIdx = 0
} else {
curProgressFtStemIdx = null
}
await spawnAndWait(video.videoId, tmpDir, DEMUCS_EXE_NAME, demucsExeArgs, true)
curProgressFtStemIdx = null
updateProgressRaw(video.videoId, 0.95)
const demucsBasePath = await findDemucsOutputDir(path.join(tmpDir, 'separated', demucsModelName))
const demucsWavFilesList = await listDemucsOutputFiles(demucsBasePath)
if (demucsWavFilesList.length === 0) {
throw new Error('No .wav output stems written - Demucs probably failed')
}
const demucsConvertedFilesList =
demucsStemsFiletype === 'wav'
? demucsWavFilesList
: await convertDemucsFiles({
videoId: video.videoId,
tmpDir,
filesList: demucsWavFilesList,
filetype: demucsStemsFiletype,
compressionArgs,
})
updateProgressRaw(video.videoId, 0.97)
const instrumentalPath = path.join(tmpDir, `instrumental.${demucsStemsFiletype}`)
console.log(`Mixing down instrumental stems to "${instrumentalPath}"`)
const ffmpegInstrumentalSourceFiles = []
for (const filename of demucsWavFilesList) {
const baseName = path.parse(filename).name
if (baseName === 'vocals') {
continue
}
ffmpegInstrumentalSourceFiles.push('-i')
ffmpegInstrumentalSourceFiles.push(filename)
}
await spawnAndWait(
video.videoId,
tmpDir,
FFMPEG_EXE_NAME,
[
...ffmpegInstrumentalSourceFiles,
...compressionArgs,
'-filter_complex',
`amix=inputs=${ffmpegInstrumentalSourceFiles.length / 2}:normalize=0`,
instrumentalPath,
],
false
)
const instrumentalSuccess = await ensureFileExists(instrumentalPath)
if (!instrumentalSuccess) {
throw new Error(
`Unable to access instrumental file "${instrumentalPath}" - ffmpeg probably failed`
)
}
updateProgressRaw(video.videoId, 0.98)
let originalOutPath = null
if (needsOriginal) {
originalOutPath = path.join(tmpDir, `original.${demucsStemsFiletype}`)
await spawnAndWait(
video.videoId,
tmpDir,
FFMPEG_EXE_NAME,
['-i', mediaPath, ...compressionArgs, originalOutPath],
false
)
const originalSuccess = await ensureFileExists(originalOutPath)
if (!originalSuccess) {
throw new Error(
`Unable to access instrumental file "${originalOutPath}" - ffmpeg probably failed`
)
}
}
updateProgressRaw(video.videoId, 0.99)
const outputBasePathContainingFolder =
video.mediaSource === 'local' && getLocalFileOutputToContainingDir()
? path.dirname(mediaPath)
: getOutputPath()
const outputBasePath = path.join(outputBasePathContainingFolder, outputFolderName)
await fs.mkdir(outputBasePath, { recursive: true })
console.log(`Copying all stems to "${outputBasePath}"`)
for (const filename of demucsConvertedFilesList) {
const baseName = path.parse(filename).name
const outputPath = path.join(
outputBasePath,
`${outputFilenamesPrefix}${baseName}.${demucsStemsFiletype}`
)
await fs.copyFile(filename, outputPath)
}
await fs.copyFile(
instrumentalPath,
path.join(outputBasePath, `${outputFilenamesPrefix}instrumental.${demucsStemsFiletype}`)
)
if (needsOriginal) {
await fs.copyFile(
originalOutPath,
path.join(outputBasePath, `${outputFilenamesPrefix}original.${demucsStemsFiletype}`)
)
}
const elapsedSeconds = (Date.now() - beginTime) * 0.001
console.log(
`DONE processing video "${video.videoId}" - "${video.title}" (finished in ${Math.round(
elapsedSeconds
)} seconds`
)
setVideoStatusAndPath(video.videoId, { step: 'done' }, outputBasePath)
}
async function processVideo(video) {
let powerSaveBlockId = null
try {
powerSaveBlockId = powerSaveBlocker.start('prevent-app-suspension')
console.log('Successfully blocked power-save using policy: "prevent-app-suspension"')
} catch (err) {
powerSaveBlockId = null
console.trace(err)
}
const tmpDir = await fs.mkdtemp(path.join(os.tmpdir(), TMP_PREFIX))
try {
await _processVideo(video, tmpDir)
} catch (err) {
console.trace(err)
const status = getVideoStatus(video.videoId)
if (status === null) {
console.log('Task was canceled by user.')
} else {
setVideoStatusAndPath(video.videoId, { step: 'error' }, null)
}
} finally {
curProgressFtStemIdx = null
try {
await fs.rm(tmpDir, {
recursive: true,
maxRetries: 5,
retryDelay: 1000,
})
} catch (err) {
console.trace(err)
}
// Will filter out the current (completed) video
setItems(curItems)
if (powerSaveBlockId !== null) {
try {
powerSaveBlocker.stop(powerSaveBlockId)
console.log('Successfully unblocked power-save')
} catch (err) {
console.error('Failed to unblock power-save')
console.trace(err)
}
powerSaveBlockId = null
}
}
}
export const setItems = async (items) => {
items = items.filter((video) => {
let status = getVideoStatus(video.videoId)
if (status === null) {
status = { step: 'queued' }
setVideoStatusAndPath(video.videoId, status, null)
}
return status.step !== 'done' && status.step !== 'error'
})
const oldVideoId = curItems.length > 0 ? curItems[0].videoId : null
const newVideoId = items.length > 0 ? items[0].videoId : null
const interrupt = oldVideoId !== newVideoId
curItems = items
if (interrupt) {
killCurChildProcess()
if (curItems.length > 0) {
// Avoid recursion when processVideo calls this function
setTimeout(() => processVideo(curItems[0]), 0)
}
}
}
let electronStore = null
let videosDb = {}
async function loadVideosDb() {
const loaded = electronStore.get('videosDb') || {}
const filtered = {}
for (const videoId in loaded) {
let exists = false
try {
await fs.access(loaded[videoId].path)
exists = true
} catch (error) {
exists = false
}
if (exists) {
filtered[videoId] = loaded[videoId]
}
}
videosDb = filtered
electronStore.set('videosDb', videosDb)
}
function saveFinishedToVideosDb() {
let numFinished = 0
const filtered = {}
for (const videoId in videosDb) {
if (videosDb[videoId].status.step === 'done') {
filtered[videoId] = videosDb[videoId]
++numFinished
}
}
electronStore.set('videosDb', filtered)
if (numFinished >= 3 && electronStore.get('canShowDonatePopup') !== false) {
donateUpdateCallback({
showDonatePopup: true,
})
}
}
function setVideoStatusAndPath(videoId, status, path) {
videosDb[videoId] = {
status,
path,
}
saveFinishedToVideosDb()
statusUpdateCallback({
videoId,
...videosDb[videoId],
})
}
export const setElectronStore = (store) => {
electronStore = store
loadVideosDb()
}
export const getOutputPath = () => {
if (electronStore) {
const outputPath = electronStore.get('outputPath')
if (outputPath) {
return outputPath
}
}
return path.join(os.homedir(), 'Music', 'StemRoller')
}
export const getModelName = () => {
if (electronStore) {
const modelName = electronStore.get('modelName')
if (modelName) {
return modelName
}
}
return 'htdemucs'
}
export const getLocalFileOutputToContainingDir = () => {
return electronStore.get('localFileOutputToContainingDir') || false
}
export const getPrefixStemFilenameWithSongName = () => {
return electronStore.get('prefixStemFilenameWithSongName') || false
}
export const getPreserveOriginalAudio = () => {
return electronStore.get('preserveOriginalAudio') || false
}
export const setOutputPath = (outputPath) => {
electronStore.set('outputPath', outputPath)
}
export const setModelName = (name) => {
electronStore.set('modelName', name)
}
export const setLocalFileOutputToContainingDir = (value) => {
electronStore.set('localFileOutputToContainingDir', value)
}
export const setPrefixStemFilenameWithSongName = (value) => {
electronStore.set('prefixStemFilenameWithSongName', value)
}
export const setPreserveOriginalAudio = (value) => {
electronStore.set('preserveOriginalAudio', value)
}
export const getOutputFormat = () => {
if (electronStore) {
const outputFormat = electronStore.get('outputFormat')
if (outputFormat) {
return outputFormat
}
}
return 'wav'
}
export const setOutputFormat = (outputFormat) => {
electronStore.set('outputFormat', outputFormat)
}
export const getPyTorchBackend = () => {
if (electronStore) {
const backend = electronStore.get('pyTorchBackend')
if (backend) {
return backend
}
}
return 'auto'
}
export const setPyTorchBackend = (backend) => {
electronStore.set('pyTorchBackend', backend)
}
export const getVideoStatus = (videoId) => {
if (videoId in videosDb) {
return videosDb[videoId].status
} else {
return null
}
}
export const getVideoPath = (videoId) => {
if (videoId in videosDb) {
return videosDb[videoId].path
} else {
return null
}
}
export const deleteVideoStatusAndPath = (videoId) => {
if (videoId in videosDb) {
const nulledEntry = videosDb[videoId]
for (const i in nulledEntry) {
nulledEntry[i] = null
}
delete videosDb[videoId]
saveFinishedToVideosDb()
statusUpdateCallback({
videoId,
...nulledEntry,
})
}
}
export const isBusy = () => {
return (
curItems.filter((video) => {
const status = getVideoStatus(video.videoId)
return status.step === 'processing' || status.step === 'downloading'
}).length > 0
)
}
export const registerStatusUpdateCallback = (callback) => {
statusUpdateCallback = callback
}
export const registerDonateUpdateCallback = (callback) => {
donateUpdateCallback = callback
}
export const deleteTmpFolders = async () => {
const tmpBasePath = os.tmpdir()
const items = await fs.readdir(tmpBasePath)
for (const itemName of items) {
if (itemName.indexOf(TMP_PREFIX) === 0) {
try {
const itemPath = path.join(tmpBasePath, itemName)
await fs.rm(itemPath, {
recursive: true,
maxRetries: 5,
retryDelay: 1000,
})
console.log(`Deleted temporary folder "${itemPath}"`)
} catch (error) {
console.trace(error)
}
}
}
}