chore: merge video updated

This commit is contained in:
Chesterkxng committed 2026-08-05 15:37:10 +02:00
1 parent 18f8b7e6ec
commit 42fa7bf854
5 files changed
+59 -201

No files matched your search

+3 -1
View File
@@ -115,7 +115,9 @@
"description": "Combine multiple video files into one continuous video.",
"longDescription": "This tool allows you to merge or append multiple video files into a single continuous video. Simply upload your video files, arrange them in the desired order, and merge them into one file for easy sharing or editing.",
"shortDescription": "Append and merge videos easily.",
"title": "Merge videos"
"title": "Merge videos",
"inputTitle": "Input Videos",
"resultTitle": "Merged Video"
},
"rotate": {
"180Degrees": "180° (Upside down)",
+12 -13
View File
@@ -1,4 +1,3 @@
import { Box } from '@mui/material';
import React, { useState } from 'react';
import ToolContent from '@components/ToolContent';
import { ToolComponentProps } from '@tools/defineTool';
@@ -7,14 +6,17 @@ import ToolMultipleVideoInput, {
MultiVideoInput
} from '@components/input/ToolMultipleVideoInput';
import { mergeVideos } from './service';
import { InitialValuesType } from './types';
import { useTranslation } from 'react-i18next';
const initialValues: InitialValuesType = {};
const initialValues = {};
type InitialValuesType = typeof initialValues;
export default function MergeVideo({
title,
longDescription
}: ToolComponentProps) {
const { t } = useTranslation('video');
const [input, setInput] = useState<MultiVideoInput[]>([]);
const [result, setResult] = useState<File | null>(null);
const [loading, setLoading] = useState(false);
@@ -28,12 +30,9 @@ export default function MergeVideo({
}
setLoading(true);
try {
const files = input.map((item) => item.file);
const mergedBlob = await mergeVideos(files, initialValues);
const mergedFile = new File([mergedBlob], 'merged-video.mp4', {
type: 'video/mp4'
});
setResult(mergedFile);
const resultFile = await mergeVideos(input.map((item) => item.file));
setResult(resultFile);
} catch (err) {
setResult(null);
} finally {
@@ -51,15 +50,15 @@ export default function MergeVideo({
onChange={(newInput) => {
setInput(newInput);
}}
accept={['video/*', '.mp4', '.avi', '.mov', '.mkv']}
title="Input Videos"
accept={['video/*']}
title={t('mergeVideo.inputTitle')}
type="video"
/>
}
resultComponent={
<ToolFileResult
value={result}
title={loading ? 'Merging Videos...' : 'Merged Video'}
title={t('mergeVideo.resultTitle')}
loading={loading}
extension={'mp4'}
/>
@@ -68,7 +67,7 @@ export default function MergeVideo({
getGroups={null}
setInput={setInput}
compute={compute}
toolInfo={{ title: `What is a ${title}?`, description: longDescription }}
toolInfo={{ title: `${title} ?`, description: longDescription }}
/>
);
}
@@ -1,62 +0,0 @@
import { expect, describe, it, vi } from 'vitest';
// Mock FFmpeg and fetchFile to avoid Node.js compatibility issues
vi.mock('@ffmpeg/ffmpeg', () => ({
FFmpeg: vi.fn().mockImplementation(() => ({
loaded: false,
load: vi.fn().mockResolvedValue(undefined),
writeFile: vi.fn().mockResolvedValue(undefined),
exec: vi.fn().mockResolvedValue(undefined),
readFile: vi.fn().mockResolvedValue(new Uint8Array([1, 2, 3, 4])),
deleteFile: vi.fn().mockResolvedValue(undefined)
}))
}));
vi.mock('@ffmpeg/util', () => ({
fetchFile: vi.fn().mockResolvedValue(new Uint8Array([1, 2, 3, 4]))
}));
// Import after mocking
import { mergeVideos } from './service';
function createMockFile(name: string, type = 'video/mp4') {
return new File([new Uint8Array([0, 1, 2])], name, { type });
}
describe('merge-video', () => {
it('throws if less than two files are provided', async () => {
await expect(mergeVideos([], {})).rejects.toThrow(
'Please provide at least two video files to merge.'
);
await expect(mergeVideos([createMockFile('a.mp4')], {})).rejects.toThrow(
'Please provide at least two video files to merge.'
);
});
it('throws if input is not an array', async () => {
// @ts-ignore - testing invalid input
await expect(mergeVideos(null, {})).rejects.toThrow(
'Please provide at least two video files to merge.'
);
});
it('successfully merges video files (mocked)', async () => {
const mockFile1 = createMockFile('video1.mp4');
const mockFile2 = createMockFile('video2.mp4');
const result = await mergeVideos([mockFile1, mockFile2], {});
expect(result).toBeInstanceOf(Blob);
expect(result.type).toBe('video/mp4');
});
it('handles different video formats by re-encoding', async () => {
const mockFile1 = createMockFile('video1.avi', 'video/x-msvideo');
const mockFile2 = createMockFile('video2.mov', 'video/quicktime');
const result = await mergeVideos([mockFile1, mockFile2], {});
expect(result).toBeInstanceOf(Blob);
expect(result.type).toBe('video/mp4');
});
});
+44 -116
View File
@@ -1,134 +1,62 @@
import { InitialValuesType, MergeVideoInput, MergeVideoOutput } from './types';
import { FFmpeg } from '@ffmpeg/ffmpeg';
import { fetchFile } from '@ffmpeg/util';
import { runFFmpegTask } from 'lib/ffmpeg';
export async function mergeVideos(
input: MergeVideoInput,
options: InitialValuesType
): Promise<MergeVideoOutput> {
export async function mergeVideos(input: File[]): Promise<File> {
if (!Array.isArray(input) || input.length < 2) {
throw new Error('Please provide at least two video files to merge.');
}
// Create a new FFmpeg instance for each operation to avoid conflicts
const ffmpeg = new FFmpeg();
return runFFmpegTask(async ({ ffmpeg, tempFile }) => {
const fileNames: string[] = [];
const outputName = tempFile('.mp4');
const concatListName = tempFile('.txt');
const fileNames: string[] = [];
const outputName = 'output.mp4';
try {
// Load FFmpeg with proper error handling
if (!ffmpeg.loaded) {
await ffmpeg.load({
wasmURL:
'https://cdn.jsdelivr.net/npm/@ffmpeg/core@0.12.9/dist/esm/ffmpeg-core.wasm',
workerURL:
'https://cdn.jsdelivr.net/npm/@ffmpeg/core@0.12.9/dist/esm/ffmpeg-core.worker.js'
});
}
// Write all input files to ffmpeg FS with better error handling
for (let i = 0; i < input.length; i++) {
const fileName = `input${i}.mp4`;
const fileName = tempFile('.mp4');
fileNames.push(fileName);
try {
const fileData = await fetchFile(input[i]);
await ffmpeg.writeFile(fileName, fileData);
console.log(`Successfully wrote ${fileName}`);
} catch (fileError) {
console.error(`Failed to write ${fileName}:`, fileError);
throw new Error(`Failed to process input file ${i + 1}: ${fileError}`);
}
await ffmpeg.writeFile(fileName, await fetchFile(input[i]));
}
// Build the filter_complex string for concat filter
const videoInputs = fileNames.map((_, idx) => `[${idx}:v]`).join(' ');
const audioInputs = fileNames.map((_, idx) => `[${idx}:a]`).join(' ');
const filterComplex = `${videoInputs} ${audioInputs} concat=n=${input.length}:v=1:a=1 [v] [a]`;
// Create concat file
const concatList = fileNames.map((name) => `file '${name}'`).join('\n');
// Build input arguments
const inputArgs = [];
for (const fileName of fileNames) {
inputArgs.push('-i', fileName);
}
await ffmpeg.writeFile(
concatListName,
new TextEncoder().encode(concatList)
);
console.log('Starting FFmpeg processing...');
console.log('Filter complex:', filterComplex);
await ffmpeg.exec([
'-f',
'concat',
'-safe',
'0',
'-i',
concatListName,
'-c:v',
'libx264',
'-preset',
'ultrafast',
'-crf',
'30',
'-c:a',
'aac',
outputName
]);
// Method 2: Fallback to concat demuxer
try {
console.log('Trying concat demuxer method...');
const data = await ffmpeg.readFile(outputName);
const concatList = fileNames.map((name) => `file '${name}'`).join('\n');
await ffmpeg.writeFile(
'concat_list.txt',
new TextEncoder().encode(concatList)
);
const blob = new Blob([new Uint8Array(data as Uint8Array)], {
type: 'video/mp4'
});
await ffmpeg.exec([
'-f',
'concat',
'-safe',
'0',
'-i',
'concat_list.txt',
'-c:v',
'libx264',
'-preset',
'ultrafast',
'-crf',
'30',
'-threads',
'0',
'-y',
outputName
]);
// Check if output was created
try {
const testRead = await ffmpeg.readFile(outputName);
if (testRead && testRead.length > 0) {
console.log('Concat demuxer method succeeded');
}
} catch (readError) {
console.log('Concat demuxer method failed to produce output');
}
} catch (execError) {
console.error('Concat demuxer method failed:', execError);
}
// Check if output file exists and read it
let mergedData;
try {
mergedData = await ffmpeg.readFile(outputName);
console.log('Successfully read output file');
} catch (readError) {
console.error('Failed to read output file:', readError);
throw new Error('Failed to read merged video file');
}
if (!mergedData || mergedData.length === 0) {
throw new Error('Output file is empty or corrupted');
}
return new Blob([mergedData as any], { type: 'video/mp4' });
} catch (error) {
console.error('Error merging videos:', error);
throw error instanceof Error
? error
: new Error('Unknown error occurred during video merge');
} finally {
// Clean up temporary files with better error handling
const filesToClean = [...fileNames, outputName, 'concat_list.txt'];
for (const fileName of filesToClean) {
try {
await ffmpeg.deleteFile(fileName);
} catch (cleanupError) {
// Ignore cleanup errors - they're not critical
console.warn(`Could not delete ${fileName}:`, cleanupError);
}
}
}
return new File(
[blob],
`${input[0].name.replace(/\.[^/.]+$/, '')}_merged_with_${
input.length - 1
}_videos.mp4`,
{ type: 'video/mp4' }
);
});
}
@@ -1,9 +0,0 @@
export type InitialValuesType = {
// Add any future options here (e.g., output format, resolution)
};
// Type for the main function input
export type MergeVideoInput = File[];
// Type for the main function output
export type MergeVideoOutput = Blob;