From 0dd15b934efaab386fd1deeb00293df3fa9931cf Mon Sep 17 00:00:00 2001 From: Chesterkxng Date: Wed, 5 Aug 2026 21:40:17 +0200 Subject: [PATCH] chore: video to gif updated --- public/locales/en/video.json | 14 +- src/pages/tools/video/video-to-gif/index.tsx | 191 ++++-------------- src/pages/tools/video/video-to-gif/service.ts | 55 +++++ src/pages/tools/video/video-to-gif/types.ts | 31 ++- 4 files changed, 135 insertions(+), 156 deletions(-) create mode 100644 src/pages/tools/video/video-to-gif/service.ts diff --git a/public/locales/en/video.json b/public/locales/en/video.json index 3c529e84..2378dce9 100644 --- a/public/locales/en/video.json +++ b/public/locales/en/video.json @@ -143,6 +143,18 @@ "videoToGif": { "description": "Convert video files to animated GIF format. Extract specific time ranges and create shareable animated images.", "shortDescription": "Convert video to animated GIF", - "title": "Video to GIF" + "title": "Video to GIF", + "inputTitle": "Input Video", + "resultTitle": "Output GIF", + "options": { + "quality": "Quality", + "low": "Low", + "mid": "Medium", + "high": "High", + "ultra": "Ultra", + "timestamps": "Timestamps", + "startTime": "Start Time", + "endTime": "End Time" + } } } diff --git a/src/pages/tools/video/video-to-gif/index.tsx b/src/pages/tools/video/video-to-gif/index.tsx index 4c0f61bc..b301d03f 100644 --- a/src/pages/tools/video/video-to-gif/index.tsx +++ b/src/pages/tools/video/video-to-gif/index.tsx @@ -1,172 +1,67 @@ import { Box } from '@mui/material'; -import React, { useState } from 'react'; -import * as Yup from 'yup'; +import React, { useState, useCallback } from 'react'; import ToolContent from '@components/ToolContent'; import { ToolComponentProps } from '@tools/defineTool'; import { GetGroupsType } from '@components/options/ToolOptions'; import TextFieldWithDesc from '@components/options/TextFieldWithDesc'; import { updateNumberField } from '@utils/string'; -import { InitialValuesType } from './types'; +import { InitialValuesType, GIF_PRESETS, Quality } from './types'; import ToolVideoInput from '@components/input/ToolVideoInput'; import ToolFileResult from '@components/result/ToolFileResult'; import SimpleRadio from '@components/options/SimpleRadio'; -import { FFmpeg } from '@ffmpeg/ffmpeg'; -import { fetchFile } from '@ffmpeg/util'; +import { useTranslation } from 'react-i18next'; +import { debounce } from 'lodash'; +import { videoToGif } from './service'; const initialValues: InitialValuesType = { quality: 'mid', - fps: '10', - scale: '320:-1:flags=bicubic', start: 0, end: 100 }; -const validationSchema = Yup.object({ - start: Yup.number().min(0, 'Start time must be positive'), - end: Yup.number().min( - Yup.ref('start'), - 'End time must be greater than start time' - ) -}); - -export default function VideoToGif({ - title, - longDescription -}: ToolComponentProps) { +export default function VideoToGif({ title }: ToolComponentProps) { + const { t } = useTranslation('video'); const [input, setInput] = useState(null); const [result, setResult] = useState(null); const [loading, setLoading] = useState(false); - const compute = (values: InitialValuesType, input: File | null) => { + const compute = async (values: InitialValuesType, input: File | null) => { if (!input) return; - const { fps, scale, start, end } = values; - let ffmpeg: FFmpeg | null = null; - let ffmpegLoaded = false; + setLoading(true); - const convertVideoToGif = async ( - file: File, - fps: string, - scale: string, - start: number, - end: number - ): Promise => { - setLoading(true); - - if (!ffmpeg) { - ffmpeg = new FFmpeg(); - } - - if (!ffmpegLoaded) { - await ffmpeg.load({ - wasmURL: - 'https://cdn.jsdelivr.net/npm/@ffmpeg/core@0.12.9/dist/esm/ffmpeg-core.wasm' - }); - ffmpegLoaded = true; - } - - const fileName = file.name; - const outputName = 'output.gif'; - - try { - ffmpeg.writeFile(fileName, await fetchFile(file)); - - await ffmpeg.exec([ - '-i', - fileName, - '-ss', - start.toString(), - '-to', - end.toString(), - '-vf', - `fps=${fps},scale=${scale},palettegen`, - 'palette.png' - ]); - - await ffmpeg.exec([ - '-i', - fileName, - '-i', - 'palette.png', - '-ss', - start.toString(), - '-to', - end.toString(), - '-filter_complex', - `fps=${fps},scale=${scale}[x];[x][1:v]paletteuse`, - outputName - ]); - - const data = await ffmpeg.readFile(outputName); - - const blob = new Blob([data as any], { type: 'image/gif' }); - const convertedFile = new File([blob], outputName, { - type: 'image/gif' - }); - - await ffmpeg.deleteFile(fileName); - await ffmpeg.deleteFile(outputName); - - setResult(convertedFile); - } catch (err) { - console.error(`Failed to convert video: ${err}`); - throw err; - } finally { - setLoading(false); - } - }; - - convertVideoToGif(input, fps, scale, start, end); + try { + const resultFile = await videoToGif(input, values); + setResult(resultFile); + } catch (error) { + console.error('Error converting video to gif:', error); + } finally { + setLoading(false); + } }; + const debouncedCompute = useCallback(debounce(compute, 1000), []); + const getGroups: GetGroupsType | null = ({ values, updateField }) => [ { - title: 'Set Quality', + title: t('videoToGif.options.quality'), component: ( - { - updateField('quality', 'low'); - updateField('fps', '5'); - updateField('scale', '240:-1:flags=bilinear'); - }} - checked={values.quality === 'low'} - /> - { - updateField('quality', 'mid'); - updateField('fps', '10'); - updateField('scale', '320:-1:flags=bicubic'); - }} - checked={values.quality === 'mid'} - /> - { - updateField('quality', 'high'); - updateField('fps', '15'); - updateField('scale', '480:-1:flags=lanczos'); - }} - checked={values.quality === 'high'} - /> - { - updateField('quality', 'ultra'); - updateField('fps', '15'); - updateField('scale', '640:-1:flags=lanczos'); - }} - checked={values.quality === 'ultra'} - /> + {(Object.keys(GIF_PRESETS) as Quality[]).map((quality) => ( + updateField('quality', quality)} + /> + ))} ) }, { - title: 'Timestamps', + title: t('videoToGif.options.timestamps'), component: ( ) @@ -198,7 +93,7 @@ export default function VideoToGif({ { setFieldValue('start', start); @@ -210,25 +105,17 @@ export default function VideoToGif({ ); }} resultComponent={ - loading ? ( - - ) : ( - - ) + } initialValues={initialValues} getGroups={getGroups} setInput={setInput} - compute={compute} - toolInfo={{ title: `What is a ${title}?`, description: longDescription }} + compute={debouncedCompute} /> ); } diff --git a/src/pages/tools/video/video-to-gif/service.ts b/src/pages/tools/video/video-to-gif/service.ts new file mode 100644 index 00000000..6af26f02 --- /dev/null +++ b/src/pages/tools/video/video-to-gif/service.ts @@ -0,0 +1,55 @@ +import { runFFmpegTask } from 'lib/ffmpeg'; +import { fetchFile } from '@ffmpeg/util'; +import { GIF_PRESETS, InitialValuesType } from './types'; + +export const videoToGif = async ( + input: File, + options: InitialValuesType +): Promise => { + return runFFmpegTask(async ({ ffmpeg, tempFile }) => { + const fileName = tempFile('.mp4'); + const outputName = tempFile('.gif'); + const paletteName = tempFile('.png'); + + const { start, end, quality } = options; + + const { fps, scale } = GIF_PRESETS[quality]; + + await ffmpeg.writeFile(fileName, await fetchFile(input)); + + await ffmpeg.exec([ + '-i', + fileName, + '-ss', + start.toString(), + '-to', + end.toString(), + '-vf', + `fps=${fps},scale=${scale},palettegen`, + paletteName + ]); + + await ffmpeg.exec([ + '-i', + fileName, + '-i', + paletteName, + '-ss', + start.toString(), + '-to', + end.toString(), + '-filter_complex', + `fps=${fps},scale=${scale}[x];[x][1:v]paletteuse`, + outputName + ]); + + const data = await ffmpeg.readFile(outputName); + + const blob = new Blob([new Uint8Array(data as Uint8Array)], { + type: 'image/gif' + }); + return new File([blob], `${input.name.replace(/\.[^/.]+$/, '')}.gif`, { + type: 'image/gif' + }); + }); +}; diff --git a/src/pages/tools/video/video-to-gif/types.ts b/src/pages/tools/video/video-to-gif/types.ts index 0bd16ffd..317d0585 100644 --- a/src/pages/tools/video/video-to-gif/types.ts +++ b/src/pages/tools/video/video-to-gif/types.ts @@ -1,7 +1,32 @@ +export type Quality = 'low' | 'mid' | 'high' | 'ultra'; + export type InitialValuesType = { - quality: 'mid' | 'high' | 'low' | 'ultra'; - fps: string; - scale: string; + quality: Quality; start: number; end: number; }; + +export const GIF_PRESETS: Record< + Quality, + { + fps: string; + scale: string; + } +> = { + low: { + fps: '5', + scale: '240:-1:flags=bilinear' + }, + mid: { + fps: '10', + scale: '320:-1:flags=bicubic' + }, + high: { + fps: '15', + scale: '480:-1:flags=lanczos' + }, + ultra: { + fps: '15', + scale: '640:-1:flags=lanczos' + } +};