Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat(v2): convert with ffmpeg #110

Merged
merged 12 commits into from
Dec 28, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 4 additions & 2 deletions .eslintignore
Original file line number Diff line number Diff line change
@@ -1,4 +1,6 @@
dist-electron

# TODO temp fix for eslint/ts error in electron/file.types.ts
electron/file.types.ts
# TODO temp fix for eslint/ts error
electron/convert/index.ts
electron/convert/convert.utils.ts
schema/index.ts
54 changes: 43 additions & 11 deletions electron/ConversionManager.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import { ipcMain } from 'electron';
import type { VideoFile } from './file.types';
import { convert } from './convert';
import type { ConversionSettings, VideoFile } from '../schema';
import type { BrowserWindow } from 'electron';

export class ConversionManager {
Expand All @@ -10,10 +11,41 @@ export class ConversionManager {
this.mainWindow = mainWindow;
this.isConversionInterrupted = false;

ipcMain.handle('start-conversion', (_event, { files }: { files: VideoFile[] }) => {
this.isConversionInterrupted = false;
this.handleFileConversionStart(files[0].path);
});
ipcMain.handle(
'start-conversion',
async (
_event,
{
conversionSettings,
destinationPath,
files,
}: { conversionSettings: ConversionSettings; destinationPath: string; files: VideoFile[] },
) => {
this.isConversionInterrupted = false;

for (let i = 0; i < files.length; i++) {
if (this.isConversionInterrupted) {
break;
}

try {
const file = files[i];
await convert(
{ conversionSettings, file, destinationPath },
{
onFileConversionEnd: filePath => this.handleFileConversionEnd(filePath),
onFileConversionProgress: (filePath, progress) => this.handleFileConversionProgress(filePath, progress),
onFileConversionStart: filePath => this.handleFileConversionStart(filePath),
onFileConversionError: (filePath, error) => this.handleFileConversionError(filePath, error),
},
);
} catch (error) {
// eslint-disable-next-line no-console
console.error(error);
}
}
},
);

ipcMain.handle('stop-conversion', () => {
this.isConversionInterrupted = true;
Expand All @@ -24,15 +56,15 @@ export class ConversionManager {
this.mainWindow.webContents.send('file-conversion-start', { filePath });
}

handleFileConversionProgress() {
this.mainWindow.webContents.send('file-conversion-progress');
handleFileConversionProgress(filePath: string, progress: number) {
this.mainWindow.webContents.send('file-conversion-progress', { filePath, progress });
}

handleFileConversionEnd() {
this.mainWindow.webContents.send('file-conversion-end');
handleFileConversionEnd(filePath: string) {
this.mainWindow.webContents.send('file-conversion-end', { filePath });
}

handleFileConversionError() {
this.mainWindow.webContents.send('file-conversion-error');
handleFileConversionError(filePath: string, error: string) {
this.mainWindow.webContents.send('file-conversion-error', { filePath, error });
}
}
54 changes: 54 additions & 0 deletions electron/convert/convert.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
/// <reference types="fluent-ffmpeg" />
import { getOutputOptions, getOutputPath } from './convert.utils';
import type { ConversionSettings, VideoFile } from '../../schema';

const ffmpegPath = require('@ffmpeg-installer/ffmpeg').path;
const ffmpeg = require('fluent-ffmpeg');

ffmpeg.setFfmpegPath(ffmpegPath);

type ConvertParams = {
conversionSettings: ConversionSettings;
destinationPath: string;
file: VideoFile;
};

type ConvertCallbacks = {
onFileConversionEnd: (filePath: string) => void;
onFileConversionError: (filePath: string, error: string) => void;
onFileConversionProgress: (filePath: string, progress: number) => void;
onFileConversionStart: (filePath: string, commandLine: string) => void;
};

export function convert(
{ conversionSettings, file, destinationPath }: ConvertParams,
{ onFileConversionEnd, onFileConversionError, onFileConversionProgress, onFileConversionStart }: ConvertCallbacks,
) {
const inputPath = file.path;
const outputPath = getOutputPath(inputPath, destinationPath);
const outputOptions = getOutputOptions(conversionSettings);

const command = ffmpeg().input(inputPath).output(outputPath).outputOptions(outputOptions);

return new Promise<void>((resolve, reject) => {
command
.on('start', (commandLine: string) => {
// eslint-disable-next-line no-console
console.log(commandLine);
onFileConversionStart(inputPath, commandLine);
})
.on('progress', ({ percent }: { percent?: number }) => {
onFileConversionProgress(inputPath, percent ?? 0);
})
.on('end', () => {
onFileConversionEnd(inputPath);
resolve();
})
.on('error', (error: Error) => {
onFileConversionError(inputPath, error.message);
reject(error);
});

command.run();
});
}
47 changes: 47 additions & 0 deletions electron/convert/convert.utils.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
import fs from 'node:fs';
import path from 'node:path';
import { bitrateSchema, channelsSchema, codecSchema, sampleRateSchema } from '../../schema';
import type { ConversionSettings } from '../../schema';

const baseOutputOptions = ['-map 0', '-codec copy'];
const audioCodecFlag = '-c:a';
const audioBitrateFlag = '-c:a';
const audioChannelsFlag = '-ac';
const audioSampleReteFlag = '-ar';

export function getOutputOptions({ bitrate, channels, codec, sampleRate }: ConversionSettings) {
const options = [...baseOutputOptions];

if (codec && codec !== codecSchema.enum.default) {
options.push(`${audioCodecFlag} ${codec}`);
}

if (bitrate && bitrate !== bitrateSchema.enum.default) {
options.push(`${audioBitrateFlag} ${bitrate}`);
}

if (channels && channels !== channelsSchema.enum.default) {
options.push(`${audioChannelsFlag} ${channels}`);
}

if (sampleRate && sampleRate !== sampleRateSchema.enum.default) {
options.push(`${audioSampleReteFlag} ${sampleRate}`);
}

return options;
}

export function getOutputPath(inputPath: string, destinationPath: string) {
const { base, dir, ext, name } = path.parse(inputPath);
const outputDirectory = destinationPath || dir;

let index = 1;
let outputPath = path.join(outputDirectory, base);

while (fs.existsSync(outputPath)) {
outputPath = path.join(outputDirectory, `${name} (${index})${ext}`);
index++;
}

return outputPath;
}
1 change: 1 addition & 0 deletions electron/convert/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
export { convert } from './convert';
12 changes: 10 additions & 2 deletions electron/electron-env.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ import type {
FileConversionProgressCallback,
FileConversionStartCallback,
} from './conversion-events.types';
import type { VideoFile } from './file.types';
import type { ConversionSettings, VideoFile } from '../schema';

declare namespace NodeJS {
interface ProcessEnv {
Expand All @@ -22,7 +22,15 @@ export interface IConversion {
onFileConversionError: (callback: FileConversionErrorCallback) => void;
onFileConversionProgress: (callback: FileConversionProgressCallback) => void;
onFileConversionStart: (callback: FileConversionStartCallback) => void;
startConversion: ({ files }: { files: VideoFile[] }) => void;
startConversion: ({
conversionSettings,
destinationPath,
files,
}: {
conversionSettings: ConversionSettings;
destinationPath: string;
files: VideoFile[];
}) => void;
}

declare global {
Expand Down
8 changes: 0 additions & 8 deletions electron/file.types.ts

This file was deleted.

12 changes: 10 additions & 2 deletions electron/preload.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ import type {
FileConversionProgressCallback,
FileConversionStartCallback,
} from './conversion-events.types';
import type { VideoFile } from './file.types';
import type { ConversionSettings, VideoFile } from '../schema';

contextBridge.exposeInMainWorld('dialog', {
openDirectory: () => ipcRenderer.invoke('dialog:openDirectory'),
Expand All @@ -17,5 +17,13 @@ contextBridge.exposeInMainWorld('conversion', {
onFileConversionProgress: (callback: FileConversionProgressCallback) =>
ipcRenderer.on('file-conversion-progress', callback),
onFileConversionStart: (callback: FileConversionStartCallback) => ipcRenderer.on('file-conversion-start', callback),
startConversion: ({ files }: { files: VideoFile[] }) => ipcRenderer.invoke('start-conversion', { files }),
startConversion: ({
conversionSettings,
destinationPath,
files,
}: {
conversionSettings: ConversionSettings;
destinationPath: string;
files: VideoFile[];
}) => ipcRenderer.invoke('start-conversion', { conversionSettings, destinationPath, files }),
});
3 changes: 3 additions & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@
"test": "vitest"
},
"dependencies": {
"@ffmpeg-installer/ffmpeg": "1.1.0",
"@formkit/auto-animate": "0.8.1",
"@hookform/resolvers": "3.3.2",
"@radix-ui/react-label": "2.0.2",
Expand All @@ -34,6 +35,7 @@
"@radix-ui/react-tooltip": "1.0.7",
"class-variance-authority": "0.7.0",
"clsx": "2.0.0",
"fluent-ffmpeg": "2.1.2",
"i18next": "23.6.0",
"immer": "10.0.3",
"lucide-react": "0.292.0",
Expand All @@ -53,6 +55,7 @@
"@testing-library/jest-dom": "6.1.4",
"@testing-library/react": "14.1.0",
"@testing-library/user-event": "14.5.1",
"@types/fluent-ffmpeg": "2.1.24",
"@types/react": "18.2.31",
"@types/react-dom": "18.2.14",
"@typescript-eslint/eslint-plugin": "6.12.0",
Expand Down
Loading