feat: add video merging tool with multiple video input component

This commit is contained in:
AshAnand34
2025-07-07 22:44:26 -07:00
parent 816a098971
commit de19febda7
7 changed files with 255 additions and 1 deletions

View File

@@ -0,0 +1,92 @@
import React from 'react';
import { Box, Typography, IconButton } from '@mui/material';
import BaseFileInput from './BaseFileInput';
import { BaseFileInputProps } from './file-input-utils';
import DeleteIcon from '@mui/icons-material/Delete';
interface ToolMultipleVideoInputProps
extends Omit<BaseFileInputProps, 'accept' | 'value' | 'onChange'> {
value: File[] | null;
onChange: (files: File[]) => void;
accept?: string[];
title?: string;
}
export default function ToolMultipleVideoInput({
value,
onChange,
accept = ['video/*', '.mkv'],
title,
...props
}: ToolMultipleVideoInputProps) {
// For preview, use the first file if available
const preview =
value && value.length > 0 ? URL.createObjectURL(value[0]) : undefined;
// Handler for file selection
const handleFileChange = (file: File | null) => {
if (file) {
// Add to existing files, avoiding duplicates by name
const files = value ? [...value] : [];
if (!files.some((f) => f.name === file.name && f.size === file.size)) {
onChange([...files, file]);
}
}
};
// Handler for removing a file
const handleRemove = (idx: number) => {
if (!value) return;
const newFiles = value.slice();
newFiles.splice(idx, 1);
onChange(newFiles);
};
return (
<BaseFileInput
value={null} // We handle preview manually
onChange={handleFileChange}
accept={accept}
title={title || 'Input Videos'}
type="video"
{...props}
>
{() => (
<Box
sx={{
position: 'relative',
width: '100%',
height: '100%',
display: 'flex',
flexDirection: 'column',
alignItems: 'center',
justifyContent: 'center'
}}
>
{preview && (
<video
src={preview}
controls
style={{ maxWidth: '100%', maxHeight: '100%' }}
/>
)}
{value && value.length > 0 && (
<Box mt={2} width="100%">
<Typography variant="subtitle2">Selected Videos:</Typography>
{value.map((file, idx) => (
<Box key={idx} display="flex" alignItems="center" mb={1}>
<Typography variant="body2" sx={{ flex: 1 }}>
{file.name}
</Typography>
<IconButton size="small" onClick={() => handleRemove(idx)}>
<DeleteIcon fontSize="small" />
</IconButton>
</Box>
))}
</Box>
)}
</Box>
)}
</BaseFileInput>
);
}

View File

@@ -1,3 +1,4 @@
import { tool as videoMergeVideo } from './merge-video/meta';
import { tool as videoToGif } from './video-to-gif/meta'; import { tool as videoToGif } from './video-to-gif/meta';
import { tool as changeSpeed } from './change-speed/meta'; import { tool as changeSpeed } from './change-speed/meta';
import { tool as flipVideo } from './flip/meta'; import { tool as flipVideo } from './flip/meta';
@@ -17,5 +18,6 @@ export const videoTools = [
flipVideo, flipVideo,
cropVideo, cropVideo,
changeSpeed, changeSpeed,
videoToGif videoToGif,
videoMergeVideo
]; ];

View File

@@ -0,0 +1,64 @@
import { Box } from '@mui/material';
import React, { useState } from 'react';
import ToolContent from '@components/ToolContent';
import { ToolComponentProps } from '@tools/defineTool';
import ToolFileResult from '@components/result/ToolFileResult';
import ToolMultipleVideoInput from '@components/input/ToolMultipleVideoInput';
import { main } from './service';
import { InitialValuesType } from './types';
const initialValues: InitialValuesType = {};
export default function MergeVideo({
title,
longDescription
}: ToolComponentProps) {
const [input, setInput] = useState<File[] | null>(null);
const [result, setResult] = useState<File | null>(null);
const [loading, setLoading] = useState(false);
const compute = async (_values: InitialValuesType, input: File[] | null) => {
if (!input || input.length < 2) return;
setLoading(true);
try {
const mergedBlob = await main(input, initialValues);
const mergedFile = new File([mergedBlob], 'merged-video.mp4', {
type: 'video/mp4'
});
setResult(mergedFile);
} catch (err) {
setResult(null);
} finally {
setLoading(false);
}
};
const getGroups = () => [];
return (
<ToolContent
title={title}
input={input}
inputComponent={
<ToolMultipleVideoInput
value={input}
onChange={setInput}
title="Input Videos"
/>
}
resultComponent={
<ToolFileResult
value={result}
title={loading ? 'Merging Videos...' : 'Merged Video'}
loading={loading}
extension={'mp4'}
/>
}
initialValues={initialValues}
getGroups={getGroups}
setInput={setInput}
compute={compute}
toolInfo={{ title: `What is a ${title}?`, description: longDescription }}
/>
);
}

View File

@@ -0,0 +1,20 @@
import { expect, describe, it } from 'vitest';
import { main } 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(main([], {})).rejects.toThrow();
await expect(main([createMockFile('a.mp4')], {})).rejects.toThrow();
});
it('merges two video files (mocked)', async () => {
// This will throw until ffmpeg logic is implemented
await expect(
main([createMockFile('a.mp4'), createMockFile('b.mp4')], {})
).rejects.toThrow('Video merging not yet implemented.');
});
});

View File

@@ -0,0 +1,14 @@
import { defineTool } from '@tools/defineTool';
import { lazy } from 'react';
export const tool = defineTool('video', {
name: 'Merge Videos',
path: 'merge-video',
icon: 'merge_type', // Material icon for merging
description: 'Combine multiple video files into one continuous video.',
shortDescription: 'Append and merge videos easily.',
keywords: ['merge', 'video', 'append', 'combine'],
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.',
component: lazy(() => import('./index'))
});

View File

@@ -0,0 +1,53 @@
import { InitialValuesType, MergeVideoInput, MergeVideoOutput } from './types';
import { FFmpeg } from '@ffmpeg/ffmpeg';
import { fetchFile } from '@ffmpeg/util';
const ffmpeg = new FFmpeg();
// This function will use ffmpeg.wasm to merge multiple video files in the browser.
// Returns a Promise that resolves to a Blob of the merged video.
export async function main(
input: MergeVideoInput,
options: InitialValuesType
): Promise<MergeVideoOutput> {
if (!Array.isArray(input) || input.length < 2) {
throw new Error('Please provide at least two video files to merge.');
}
if (!ffmpeg.loaded) {
await ffmpeg.load({
wasmURL:
'https://cdn.jsdelivr.net/npm/@ffmpeg/core@0.12.9/dist/esm/ffmpeg-core.wasm'
});
}
// Write all input files to ffmpeg FS
const fileNames = input.map((file, idx) => `input${idx}.mp4`);
for (let i = 0; i < input.length; i++) {
await ffmpeg.writeFile(fileNames[i], await fetchFile(input[i]));
}
// Create concat list file
const concatList = fileNames.map((name) => `file '${name}'`).join('\n');
await ffmpeg.writeFile(
'concat_list.txt',
new TextEncoder().encode(concatList)
);
// Run ffmpeg concat demuxer
const outputName = 'output.mp4';
await ffmpeg.exec([
'-f',
'concat',
'-safe',
'0',
'-i',
'concat_list.txt',
'-c',
'copy',
outputName
]);
const mergedData = await ffmpeg.readFile(outputName);
return new Blob([mergedData], { type: 'video/mp4' });
}

View File

@@ -0,0 +1,9 @@
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;