-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathvideo.js
More file actions
260 lines (234 loc) · 11.1 KB
/
Copy pathvideo.js
File metadata and controls
260 lines (234 loc) · 11.1 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
const fs = require("fs");
const path = require("path");
const ffmpeg = require('fluent-ffmpeg');
const command = ffmpeg();
const asyncPool = require('tiny-async-pool');
// const Ciseaux = require("ciseaux/node");
// const Tape = require("ciseaux/lib/tape");
// Video support
// https://askubuntu.com/questions/59383/extract-part-of-a-video-with-a-one-line-command/59388
// https://github.com/fluent-ffmpeg/node-fluent-ffmpeg
// equivalent of what I need to do:
// 1. take in .input streams
// 2. use .seek
// 3. use .duration
// 4. use .mergeToFile
// maybe REALLY slow?
// https://ffmpeg.org/ffmpeg.html
const beatswap = (options) => {
const {
inFilePath,
outFilePath,
beatLength,
sequenceOrder,
startPoint,
useExistingSliceFiles,
} = options;
console.log('Warning: beatswapping video can take a long time!')
const tmpDir = path.resolve(process.cwd(), 'beatswaptmp')
console.log('Setting up temporary directory:', tmpDir);
if (!fs.existsSync(tmpDir)) {
fs.mkdirSync(tmpDir);
}
const outputPathParse = path.parse(outFilePath);
const outputPathName = outputPathParse.name;
const outputPathExt = outputPathParse.ext;
let duration;
ffmpeg.ffprobe(inFilePath, function (err, metadata) {
if (err) {
console.log('Error occurred while analyzing input:', err);
process.exit(-1);
}
duration = metadata.format.duration;
// @TODO: Incorporate start/endpoints.
// @TODO: Add truncate flag with start/end.
const beatCount = duration / beatLength;
// const beatCount = 20;
console.log('Found', Math.floor(beatCount), 'beats in video. Slicing into parts...');
let doneCount = 0;
const beatarr = [];
for (let i = 0; i < beatCount; i++) {
// Because the startPoint could push the actual beats up
// to past the end of the file, we need to ensure we don't
// seek to a point off the end of the video file. Otherwise
// we'll encounter an error.
if (startPoint + (i * beatLength) < duration) {
beatarr.push(i);
}
}
// @KLUDGE: Pretty sure this can just be fixed up at beatCount but too
// tired to fix atm
const actualBeatCount = beatarr.length;
const generateSliceOutPath = (i) => {
const tmpName = outputPathName + '_' + i + outputPathExt;
return path.resolve(tmpDir, tmpName);
};
const kickOffFfmpeg = (i) => {
const outPath = generateSliceOutPath(i);
const seek = startPoint + (i * beatLength);
return new Promise((resolve, reject) => {
ffmpeg(inFilePath)
.seekInput(seek)
.duration(beatLength)
// @TODO: Customize codec outputs
.on('start', function (commandLine) {
if (global.verbose) {
console.log('Spawned ffmpeg with command: ' + commandLine);
}
})
.on('error', function (err) {
console.log('An error occurred while trying to slice video:', err.message);
reject();
process.exit(-1);
})
.on('end', () => {
doneCount++;
if (doneCount % 10 === 0) {
const percentageDone = Math.round(doneCount / actualBeatCount * 100, 2);
console.log(percentageDone + '%', 'done...');
}
resolve(outPath);
})
.save(outPath)
});
};
let sliceFileResults;
// Debug trick for creating a ton of slices that failed while trying to merge.
if (useExistingSliceFiles) {
// https://superuser.com/questions/1200118/ffmpeg-command-line-any-way-around-the-maximum-character-limit
// ffmpeg -i /Users/way/Projects/Miscellaneous/beatswap/beatswaptmp/Bad_Romance_betascrewed_2.mkv -i /Users/way/Projects/Miscellaneous/beatswap/beatswaptmp/Bad_Romance_betascrewed_8.mkv -i /Users/way/Projects/Miscellaneous/beatswap/beatswaptmp/Bad_Romance_betascrewed_7.mkv -i /Users/way/Projects/Miscellaneous/beatswap/beatswaptmp/Bad_Romance_betascrewed_3.mkv -i /Users/way/Projects/Miscellaneous/beatswap/beatswaptmp/Bad_Romance_betascrewed_4.mkv -i /Users/way/Projects/Miscellaneous/beatswap/beatswaptmp/Bad_Romance_betascrewed_4.mkv -i /Users/way/Projects/Miscellaneous/beatswap/beatswaptmp/Bad_Romance_betascrewed_6.mkv -i /Users/way/Projects/Miscellaneous/beatswap/beatswaptmp/Bad_Romance_betascrewed_2.mkv -i /Users/way/Projects/Miscellaneous/beatswap/beatswaptmp/Bad_Romance_betascrewed_8.mkv -i /Users/way/Projects/Miscellaneous/beatswap/beatswaptmp/Bad_Romance_betascrewed_9.mkv -y -filter_complex concat=n=10:v=1:a=1 /Users/way/Projects/Miscellaneous/beatswap/Bad_Romance_betascrewed.mkv
// TODO: Work around lack of complex_filter_script functionality
sliceFileResults = new Promise((resolve) => {
resolve(beatarr.map(generateSliceOutPath));
});
} else {
sliceFileResults = asyncPool(20, beatarr, kickOffFfmpeg);
}
sliceFileResults.then(results => {
// console.log(results);
console.log('Done slicing videos.');
console.log('Rebuilding into sequence.');
let merge = ffmpeg();
const reorderedClips = [];
// Lifted wholesale from the audio beatswapping.
let currentSequenceIndex = 0;
let currentSequenceFrame = 0;
for (let i = 0; i < actualBeatCount; i++) {
const beatTarget = sequenceOrder[currentSequenceIndex];
const sequenceFrameOffset = currentSequenceFrame * sequenceOrder.length;
// @TODO: Implement outputting null
if (beatTarget !== null) {
const clipTargetIndex = sequenceFrameOffset + beatTarget;
if (clipTargetIndex > actualBeatCount - 1) {
reorderedClips.push(results[i]);
} else {
reorderedClips.push(results[clipTargetIndex]);
}
}
currentSequenceIndex++;
if (currentSequenceIndex > sequenceOrder.length - 1) {
currentSequenceIndex = 0;
currentSequenceFrame++;
}
}
// console.log(reorderedClips);
reorderedClips.forEach(clip => {
merge = merge.input(clip);
});
merge
.on('progress', progress => {
// @TODO: Make this format better
console.log(progress);
})
.on('start', commandLine => {
if (global.verbose) {
console.log('Spawned ffmpeg with command: ' + commandLine);
}
})
.on('error', err => {
console.log('An error occurred while trying to merge videos:', err.message);
process.exit(-1);
})
.on('end', () => {
console.log('Done. Whew! Output file to:', outFilePath);
})
.mergeToFile(outFilePath);
})
.catch((err) => {
console.log(err);
process.exit(-1);
});
});
};
// const beatswap = (options) => {
// const {
// inFilePath,
// outFilePath,
// beatLength,
// sequenceOrder,
// startPoint,
// useSilence,
// } = options;
// // create a tape instance from the filepath
// console.log('Attempting to read file from:', inFilePath);
// Ciseaux.from(inFilePath).then((originalTape) => {
// console.log('Done.');
// const measureCount = originalTape.duration / beatLength;
// // Create a blank Tape to append to
// let runningTape = new Tape();
// // Split all of the tapes out by the number of beats there are. Bump by the startPoint, too.
// let allSlices = originalTape.slice(startPoint).split(measureCount);
// console.log('Processing', allSlices.length, 'beats...');
// let currentSequenceIndex = 0;
// // The index of the set of audio clips that will be picked
// // from to populate the current sequence
// let currentSequenceFrame = 0;
// for (let i = 0; i < allSlices.length; i++) {
// // This is the beat in the sequence we want to put in this slot
// const beatTarget = sequenceOrder[currentSequenceIndex];
// // This is the adjustment we want to make for the current sequence frame,
// // given the sequence length
// const sequenceFrameOffset = currentSequenceFrame * sequenceOrder.length;
// // Is the target actually null, indicating a beat omission?
// if (beatTarget === null) {
// // If we set useSilence to true, then replace the beat drop with silence.
// if (useSilence) {
// runningTape = runningTape.concat(Ciseaux.silence(beatLength));
// }
// // Otherwise, we omit adding the slice, resulting in a shorter file.
// } else {
// // This is the clip we actually want to get
// const clipTargetIndex = sequenceFrameOffset + beatTarget;
// // Is there nothing to grab because we're at the end? Then just pop in
// // the current clip.
// if (clipTargetIndex > allSlices.length - 1) {
// runningTape = runningTape.concat(allSlices[i]);
// } else {
// // Otherwise, just grab that dang clip and put it in there.
// runningTape = runningTape.concat(allSlices[clipTargetIndex]);
// }
// }
// // Wrap around the sequence index when we're at the end and then bump the frame
// // so we target the clips for the next sequence
// currentSequenceIndex++;
// if (currentSequenceIndex > sequenceOrder.length - 1) {
// currentSequenceIndex = 0;
// currentSequenceFrame++;
// }
// }
// return runningTape.render();
// }).then(legacyBuffer => {
// // Ciseaux seems to return an old-style buffer that doesn't write out
// // properly so we just rewrap it.
// const buffer = Buffer.from(legacyBuffer);
// return new Promise(resolve => {
// console.log('Writing beatswapped file to:', outFilePath);
// fs.writeFile(outFilePath, buffer, resolve);
// }).then(() => {
// console.log('Done. Enjoy!');
// });
// });
// };
module.exports = {
beatswap: beatswap,
};