-
Notifications
You must be signed in to change notification settings - Fork 1
/
mkvmerge.js
109 lines (92 loc) · 2.66 KB
/
mkvmerge.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
const os = require('os');
const fs = require('fs');
const glob = require("glob")
const path = require('path')
const util = require('util')
const execFile = util.promisify(require('child_process').execFile);
const { execSync } = require('child_process');
require('tagslog')()
let mkvmerge = path.join(__dirname, 'tools/mkvmerge.exe');
// Function to find mkvmerge in system PATH
const findMkvmergeInPath = () => {
const pathDirs = process.env.PATH.split(path.delimiter);
for (const dir of pathDirs) {
const mkvmergePath = path.join(dir, 'mkvmerge');
const mkvmergeExePath = path.join(dir, 'mkvmerge.exe');
if (fs.existsSync(mkvmergePath)) {
return mkvmergePath;
}
if (fs.existsSync(mkvmergeExePath)) {
return mkvmergeExePath;
}
}
return null;
};
// Check if mkvmerge is available in the system PATH
const mkvmergePath = findMkvmergeInPath();
if (mkvmergePath) {
mkvmerge = mkvmergePath;
} else {
logT('mkvmerge', 'mkvmerge not found in PATH, using local version if available.');
}
logT('mkvmerge', mkvmerge)
if (!fs.existsSync(mkvmerge)) {
throw new Error('Cannot find mkvmerge');
}
const randomName = () => Math.random().toString(36).slice(2);
const merge = async (video, audios) => {
if (audios.length == 0) {
return;
}
logT('merge', `Merging video: ${video} with audios: ${audios.length === 1 ? audios[0] : audios}`);
const newFile = `${randomName()}.mkv`;
await execFile(path.resolve(mkvmerge), [
'--default-track', '0:yes',
...audios,
'--default-track', '1:no',
video,
'-o', newFile
])
fs.unlinkSync(video);
fs.renameSync(newFile, video);
}
let videoNow = 0
const mergeAudios = (videos) => {
const video = videos[videoNow++];
if((typeof existCalled === 'undefined' || !existCalled) && videoNow === videos.length + 2)
{
existCalled = true;
onExit()
}
if(!video)
return
const videoFileName = path.parse(video).name
glob(`**/*.{aac,mka,mp3,opus,flac,ogg}`, async (er, audios) => {
if(!audios)
return;
audios = audios.filter(audio => audio.includes(videoFileName));
if (audios.length === 0) {
return;
}
await merge(video, audios)
mergeAudios(videos)
})
}
if(mkvmerge.includes('snapshot'))
{
logT('mkvmerge', 'Unpacking temporary files');
const buffer = fs.readFileSync(mkvmerge)
mkvmerge = os.tmpdir() + '/' + path.basename(mkvmerge);
fs.writeFileSync(mkvmerge, buffer)
}
onExit = () => {
if (mkvmerge === path.join(__dirname, 'tools/mkvmerge.exe')) {
logT('cleanup', 'Cleaning up temporary files');
fs.unlinkSync(mkvmerge);
}
}
glob("**/*.+(mp4|mkv)", (er, videos) => {
// multiprocess
mergeAudios(videos)
mergeAudios(videos)
})