From 42fa7bf854cdf52bfbcbf2dc1d28a18db074184c Mon Sep 17 00:00:00 2001 From: Chesterkxng Date: Wed, 5 Aug 2026 15:37:10 +0200 Subject: [PATCH] chore: merge video updated --- public/locales/en/video.json | 4 +- src/pages/tools/video/merge-video/index.tsx | 25 ++- .../merge-video/merge-video.service.test.ts | 62 ------- src/pages/tools/video/merge-video/service.ts | 160 +++++------------- src/pages/tools/video/merge-video/types.ts | 9 - 5 files changed, 59 insertions(+), 201 deletions(-) delete mode 100644 src/pages/tools/video/merge-video/merge-video.service.test.ts delete mode 100644 src/pages/tools/video/merge-video/types.ts diff --git a/public/locales/en/video.json b/public/locales/en/video.json index bf71e36b..e477015d 100644 --- a/public/locales/en/video.json +++ b/public/locales/en/video.json @@ -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)", diff --git a/src/pages/tools/video/merge-video/index.tsx b/src/pages/tools/video/merge-video/index.tsx index 8a7de659..57d77f02 100644 --- a/src/pages/tools/video/merge-video/index.tsx +++ b/src/pages/tools/video/merge-video/index.tsx @@ -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([]); const [result, setResult] = useState(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={ @@ -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 }} /> ); } diff --git a/src/pages/tools/video/merge-video/merge-video.service.test.ts b/src/pages/tools/video/merge-video/merge-video.service.test.ts deleted file mode 100644 index 311c0673..00000000 --- a/src/pages/tools/video/merge-video/merge-video.service.test.ts +++ /dev/null @@ -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'); - }); -}); diff --git a/src/pages/tools/video/merge-video/service.ts b/src/pages/tools/video/merge-video/service.ts index 6089125b..0ca3916c 100644 --- a/src/pages/tools/video/merge-video/service.ts +++ b/src/pages/tools/video/merge-video/service.ts @@ -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 { +export async function mergeVideos(input: File[]): Promise { 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' } + ); + }); } diff --git a/src/pages/tools/video/merge-video/types.ts b/src/pages/tools/video/merge-video/types.ts deleted file mode 100644 index 7cb6a522..00000000 --- a/src/pages/tools/video/merge-video/types.ts +++ /dev/null @@ -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;