Skip to content

Instantly share code, notes, and snippets.

@Slyke
Last active August 16, 2021 06:51
Show Gist options
  • Save Slyke/31babc2a3d37501fdcca7d4c7ea64262 to your computer and use it in GitHub Desktop.
Save Slyke/31babc2a3d37501fdcca7d4c7ea64262 to your computer and use it in GitHub Desktop.
GoPro - Organise and merge video files
const fs = require('fs');
const path = require('path');
const { execSync } = require('child_process')
const baseDir = './';
const videoFileTypes = ['mp4', 'mov', 'avi', 'wmv', 'mkv', 'flv', 'mpg', 'mpeg', '3gp', '3g2'];
const allFiles = fs.readdirSync(baseDir);
const videoFiles = [];
const videoDirectories = [];
allFiles.forEach((file) => {
const ext = file.substring(file.lastIndexOf('.') + 1);
if (videoFileTypes.indexOf(ext.toLowerCase()) > -1) {
videoFiles.push(file);
}
});
videoFiles.forEach((videoFile) => {
console.log(`Moving file ${videoFile}`);
const fileNameWithoutExt = videoFile.substring(0, videoFile.lastIndexOf('.'));
const goproRecordingIndex = fileNameWithoutExt.slice(-4);
const vidDir = path.join(baseDir, goproRecordingIndex);
if (!fs.existsSync(vidDir)){
fs.mkdirSync(vidDir);
}
if (videoDirectories.indexOf(vidDir) < 0) {
videoDirectories.push(vidDir);
}
fs.renameSync(videoFile, path.join(vidDir, videoFile));
});
console.log(`Moving files complete\n`);
videoDirectories.forEach((dir) => {
const movieFiles = fs.readdirSync(path.join(baseDir, dir));
movieFiles.filter((videoFile) => {
const ext = videoFile.substring(videoFile.lastIndexOf('.') + 1);
if (videoFileTypes.indexOf(ext.toLowerCase()) > -1) {
const fileNameWithoutExt = videoFile.substring(0, videoFile.lastIndexOf('.'));
if (fileNameWithoutExt.indexOf('merged_') > -1) {
return false
}
return true;
}
});
const filePath = path.join(dir, 'filelist.txt');
fs.writeFileSync(filePath, '');
movieFiles.sort((a, b) => {
if (a > b) {
return 1;
}
if (b > a) {
return -1;
}
return 0;
});
console.log(`Generating file list for ${dir}`);
movieFiles.forEach((videoFile) => {
const ext = videoFile.substring(videoFile.lastIndexOf('.') + 1);
if (videoFileTypes.indexOf(ext.toLowerCase()) > -1) {
fs.appendFileSync(filePath, `file '${videoFile}'\n`);
}
});
});
console.log(`Generation files list complete\n`);
console.log(`Merging video files:`);
videoDirectories.forEach((dir) => {
const outputFile = `merged_${dir}.mp4`;
const command = `ffmpeg -f concat -safe 0 -i ${path.join(dir, 'filelist.txt')} -c copy ${path.join(dir, outputFile)}`;
console.log(command);
const result = execSync(command);
console.log(result);
});
console.log(`Merging videos complete\n`);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment