-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsteelseries-processor.js
352 lines (297 loc) · 12 KB
/
steelseries-processor.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
const { promises: fs, statSync } = require('fs');
const path = require('path');
const { spawn } = require('child_process');
class SteelSeriesProcessor {
constructor(inputFolder, exportFolder, progressCallback, logCallback) {
this.inputFolder = inputFolder;
this.exportFolder = exportFolder;
this.metadataFolder = path.join(exportFolder, '.clip_metadata');
this.progressCallback = progressCallback;
this.logCallback = logCallback;
}
log(message) {
if (this.logCallback) {
this.logCallback(message);
}
}
async ensureFoldersExist() {
await fs.mkdir(this.exportFolder, { recursive: true });
await fs.mkdir(this.metadataFolder, { recursive: true });
}
async copyFileTimestamps(srcPath, dstPath) {
try {
const srcStat = statSync(srcPath);
await fs.utimes(dstPath, srcStat.atime, srcStat.mtime);
return true;
} catch (err) {
console.error(`Failed to copy timestamps: ${err.message}`);
return false;
}
}
async getAudioStreamCount(inputFile) {
return new Promise((resolve, reject) => {
const ffprobe = spawn('ffprobe', [
'-v', 'quiet',
'-print_format', 'json',
'-show_streams',
'-select_streams', 'a',
inputFile
]);
let outputData = '';
ffprobe.stdout.on('data', (data) => {
outputData += data;
});
ffprobe.on('close', (code) => {
try {
const data = JSON.parse(outputData);
const streamCount = data.streams ? data.streams.length : 0;
this.log(`Found ${streamCount} audio streams`);
resolve(streamCount);
} catch (err) {
console.error('Error parsing audio stream data:', err);
resolve(0);
}
});
ffprobe.on('error', (err) => {
console.error('FFprobe process error:', err);
resolve(0);
});
});
}
async extractSteelSeriesMetadata(inputFile) {
return new Promise((resolve, reject) => {
const ffprobe = spawn('ffprobe', [
'-v', 'quiet',
'-print_format', 'json',
'-show_format',
inputFile
]);
let outputData = '';
ffprobe.stdout.on('data', (data) => {
outputData += data;
});
ffprobe.on('close', async (code) => {
try {
const mediaInfo = JSON.parse(outputData);
const tags = mediaInfo.format.tags || {};
// Combine all STEELSERIES_META tags
let fullMeta = '';
const metaKeys = Object.keys(tags).filter(key => key.startsWith('STEELSERIES_META'));
metaKeys.sort(); // Ensure correct order (0000, 0001, etc.)
for (const key of metaKeys) {
fullMeta += tags[key];
}
try {
// Parse the combined JSON
const metadata = JSON.parse(fullMeta);
resolve({
name: metadata.name,
clip_start_point: metadata.clip_start_point,
clip_end_point: metadata.clip_end_point
});
} catch (parseErr) {
console.error('Error parsing combined metadata:', parseErr);
resolve(null);
}
} catch (err) {
console.error('Error processing metadata:', err);
resolve(null);
}
});
ffprobe.on('error', (err) => {
console.error('FFprobe process error:', err);
resolve(null);
});
});
}
async getAllMetadata(inputFile) {
return new Promise((resolve, reject) => {
const ffprobe = spawn('ffprobe', [
'-v', 'quiet',
'-print_format', 'json',
'-show_format',
'-show_streams',
inputFile
]);
let outputData = '';
ffprobe.stdout.on('data', (data) => {
outputData += data;
});
ffprobe.on('close', (code) => {
try {
const mediaInfo = JSON.parse(outputData);
this.log('Complete metadata:', JSON.stringify(mediaInfo, null, 2));
resolve(mediaInfo);
} catch (err) {
reject(err);
}
});
ffprobe.on('error', reject);
});
}
async combineAudioAndCopy(inputFile, outputFile) {
return new Promise(async (resolve) => {
const audioStreams = await this.getAudioStreamCount(inputFile);
if (audioStreams === 0) {
this.log(`No audio streams found in ${inputFile}`);
resolve(false);
return;
}
let ffmpegArgs;
if (audioStreams === 1) {
ffmpegArgs = [
'-i', inputFile,
'-c:v', 'copy',
'-c:a', 'copy',
'-y',
outputFile
];
} else {
// For multiple audio streams, mix them together
const filterInputs = Array.from({ length: audioStreams }, (_, i) => `[0:a:${i}]`).join('');
const filterString = `${filterInputs}amix=inputs=${audioStreams}:duration=longest[aout]`;
ffmpegArgs = [
'-i', inputFile,
'-c:v', 'copy',
'-filter_complex', filterString,
'-map', '0:v:0',
'-map', '[aout]',
'-y',
outputFile
];
}
const ffmpeg = spawn('ffmpeg', ffmpegArgs);
ffmpeg.stderr.on('data', (data) => {
this.log(`FFmpeg: ${data}`);
});
ffmpeg.on('close', (code) => {
if (code === 0) {
this.copyFileTimestamps(inputFile, outputFile);
resolve(true);
} else {
console.error(`FFmpeg process exited with code ${code}`);
resolve(false);
}
});
ffmpeg.on('error', (err) => {
console.error('FFmpeg process error:', err);
resolve(false);
});
});
}
async shouldProcessFile(inputFile) {
const fileName = path.basename(inputFile);
const outputFile = path.join(this.exportFolder, fileName);
const nameFile = path.join(this.metadataFolder, `${fileName}.customname`);
const trimFile = path.join(this.metadataFolder, `${fileName}.trim`);
try {
// Check if all files exist
await Promise.all([
fs.access(outputFile),
fs.access(nameFile),
fs.access(trimFile)
]);
// Compare timestamps
const inputStat = statSync(inputFile);
const outputStat = statSync(outputFile);
const nameStat = statSync(nameFile);
const trimStat = statSync(trimFile);
// Check if any timestamps don't match
const timestampsDiffer = [outputStat, nameStat, trimStat].some(
stat => Math.abs(stat.mtimeMs - inputStat.mtimeMs) > 1000
);
return timestampsDiffer;
} catch (err) {
// If any file doesn't exist or there's an error, we should process
return true;
}
}
async isFileReady(filePath) {
try {
// Try to open the file for writing - if it's locked, it's probably still being written
const fileHandle = await fs.open(filePath, 'r+');
await fileHandle.close();
// Check if file size is stable (hasn't changed in 1 second)
const size1 = (await fs.stat(filePath)).size;
await new Promise(resolve => setTimeout(resolve, 1000));
const size2 = (await fs.stat(filePath)).size;
return size1 === size2;
} catch (error) {
return false;
}
}
async processFile(inputFile) {
try {
if (!await this.shouldProcessFile(inputFile)) {
this.log(`Skipping ${path.basename(inputFile)} (already processed)`);
return;
}
// Check if file is ready before processing
if (!await this.isFileReady(inputFile)) {
this.log(`File ${path.basename(inputFile)} is still being written, skipping...`);
return;
}
this.log(`Processing ${path.basename(inputFile)}`);
// Debug: First print all metadata
this.log('Analyzing metadata for:', inputFile);
await this.getAllMetadata(inputFile);
const metadata = await this.extractSteelSeriesMetadata(inputFile);
if (!metadata) {
this.log(`No SteelSeries metadata found in ${inputFile}`);
return;
}
const fileName = path.basename(inputFile);
const outputFile = path.join(this.exportFolder, fileName);
const nameFile = path.join(this.metadataFolder, `${fileName}.customname`);
const trimFile = path.join(this.metadataFolder, `${fileName}.trim`);
const tagsFile = path.join(this.metadataFolder, `${fileName}.tags`);
const trimData = {
start: Math.round(metadata.clip_start_point * 10) / 10,
end: Math.round(metadata.clip_end_point * 10) / 10
};
if (await this.combineAudioAndCopy(inputFile, outputFile)) {
// Save metadata files
await fs.writeFile(nameFile, metadata.name, 'utf8');
await this.copyFileTimestamps(inputFile, nameFile);
await fs.writeFile(trimFile, JSON.stringify(trimData, null, 2), 'utf8');
await this.copyFileTimestamps(inputFile, trimFile);
// Add the "Imported" tag
await fs.writeFile(tagsFile, JSON.stringify(["Imported"]), 'utf8');
await this.copyFileTimestamps(inputFile, tagsFile);
this.log(`Processed ${fileName}`);
this.log(`Name: ${metadata.name}`);
this.log(`Trim: ${JSON.stringify(trimData)}`);
this.log('---');
} else {
this.log(`Failed to process ${fileName}`);
}
} catch (err) {
this.log(`Error processing ${inputFile}: ${err.message}`);
return false;
}
}
async processFolder() {
try {
await this.ensureFoldersExist();
const files = await fs.readdir(this.inputFolder);
const mp4Files = files.filter(file => file.toLowerCase().endsWith('.mp4'));
if (mp4Files.length === 0) {
this.log('No MP4 files found!');
return;
}
let processed = 0;
const total = mp4Files.length;
for (const file of mp4Files) {
await this.processFile(path.join(this.inputFolder, file));
processed++;
if (this.progressCallback) {
this.progressCallback(processed, total);
}
}
} catch (err) {
this.log(`Error processing folder: ${err.message}`);
throw err;
}
}
}
module.exports = SteelSeriesProcessor;