Merge branch 'main' into crop-video

This commit is contained in:
Vladimir Kirill Bickov
2025-05-25 05:17:57 -07:00
committed by GitHub
23 changed files with 571 additions and 34 deletions

16
.idea/workspace.xml generated
View File

@@ -6,7 +6,8 @@
<component name="ChangeListManager">
<list default="true" id="b30e2810-c4c1-4aad-b134-794e52cc1c7d" name="Changes" comment="fix: misc">
<change beforePath="$PROJECT_DIR$/.idea/workspace.xml" beforeDir="false" afterPath="$PROJECT_DIR$/.idea/workspace.xml" afterDir="false" />
<change beforePath="$PROJECT_DIR$/src/pages/tools/pdf/split-pdf/index.tsx" beforeDir="false" afterPath="$PROJECT_DIR$/src/pages/tools/pdf/split-pdf/index.tsx" afterDir="false" />
<change beforePath="$PROJECT_DIR$/src/components/input/BaseFileInput.tsx" beforeDir="false" afterPath="$PROJECT_DIR$/src/components/input/BaseFileInput.tsx" afterDir="false" />
<change beforePath="$PROJECT_DIR$/src/pages/tools/pdf/protect-pdf/service.ts" beforeDir="false" afterPath="$PROJECT_DIR$/src/pages/tools/pdf/protect-pdf/service.ts" afterDir="false" />
</list>
<option name="SHOW_DIALOG" value="false" />
<option name="HIGHLIGHT_CONFLICTS" value="true" />
@@ -23,7 +24,7 @@
<option name="PUSH_AUTO_UPDATE" value="true" />
<option name="RECENT_BRANCH_BY_REPOSITORY">
<map>
<entry key="$PROJECT_DIR$" value="main" />
<entry key="$PROJECT_DIR$" value="fork/rohit267/feat/pdf-merge" />
</map>
</option>
<option name="RECENT_GIT_ROOT_PATH" value="$PROJECT_DIR$" />
@@ -134,6 +135,13 @@
"number": 102
},
"lastSeen": 1747171977348
},
{
"id": {
"id": "PR_kwDOMJIfts6XPua_",
"number": 117
},
"lastSeen": 1747929835864
}
]
}]]></component>
@@ -189,7 +197,7 @@
"Vitest.replaceText function (regexp mode).should return the original text when passed an invalid regexp.executor": "Run",
"Vitest.replaceText function.executor": "Run",
"Vitest.timeBetweenDates.executor": "Run",
"git-widget-placeholder": "#102 on fork/rohit267/feat/pdf-merge",
"git-widget-placeholder": "#117 on fork/nevolodia/flip-video",
"ignore.virus.scanning.warn.message": "true",
"kotlin-language-version-configured": "true",
"last_opened_file_path": "C:/Users/Ibrahima/IdeaProjects/omni-tools/src",
@@ -423,6 +431,8 @@
<workItem from="1745775228478" duration="1221000" />
<workItem from="1745835676024" duration="68000" />
<workItem from="1747171958176" duration="1105000" />
<workItem from="1747217211469" duration="4000" />
<workItem from="1747929815472" duration="843000" />
</task>
<task id="LOCAL-00147" summary="chore: update meta">
<option name="closed" value="true" />

View File

@@ -33,18 +33,15 @@ export default function BaseFileInput({
const { showSnackBar } = useContext(CustomSnackBarContext);
useEffect(() => {
try {
if (isArray(value)) {
const objectUrl = createObjectURL(value[0]);
if (value) {
try {
const objectUrl = createObjectURL(value);
setPreview(objectUrl);
return () => revokeObjectURL(objectUrl);
} else {
setPreview(null);
} catch (error) {
console.error('Error previewing file:', error);
}
} catch (error) {
console.error('Error previewing file:', error);
}
} else setPreview(null);
}, [value]);
const handleFileChange = (event: React.ChangeEvent<HTMLInputElement>) => {
@@ -70,11 +67,6 @@ export default function BaseFileInput({
}
};
function handleClear() {
// @ts-ignore
onChange(null);
}
const handleDrop = (event: React.DragEvent<HTMLDivElement>) => {
event.preventDefault();
event.stopPropagation();
@@ -216,11 +208,7 @@ export default function BaseFileInput({
</Box>
)}
</Box>
<InputFooter
handleCopy={handleCopy}
handleImport={handleImportClick}
handleClear={handleClear}
/>
<InputFooter handleCopy={handleCopy} handleImport={handleImportClick} />
<input
ref={fileInputRef}
style={{ display: 'none' }}

View File

@@ -2,7 +2,7 @@ import { defineTool } from '@tools/defineTool';
import { lazy } from 'react';
export const tool = defineTool('csv', {
name: 'Change csv separator',
name: 'Change CSV separator',
path: 'change-csv-separator',
icon: 'material-symbols:split-scene-rounded',
description:

View File

@@ -4,12 +4,12 @@ import { lazy } from 'react';
export const tool = defineTool('csv', {
name: 'Convert CSV Rows to Columns',
path: 'csv-rows-to-columns',
icon: 'carbon:transpose',
icon: 'fluent:text-arrow-down-right-column-24-filled',
description:
'This tool converts rows of a CSV (Comma Separated Values) file into columns. It extracts the horizontal lines from the input CSV one by one, rotates them 90 degrees, and outputs them as vertical columns one after another, separated by commas.',
longDescription:
'This tool converts rows of a CSV (Comma Separated Values) file into columns. For example, if the input CSV data has 6 rows, then the output will have 6 columns and the elements of the rows will be arranged from the top to bottom. In a well-formed CSV, the number of values in each row is the same. However, in cases when rows are missing fields, the program can fix them and you can choose from the available options: fill missing data with empty elements or replace missing data with custom elements, such as "missing", "?", or "x". During the conversion process, the tool also cleans the CSV file from unnecessary information, such as empty lines (these are lines without visible information) and comments. To help the tool correctly identify comments, in the options, you can specify the symbol at the beginning of a line that starts a comment. This symbol is typically a hash "#" or double slash "//". Csv-abulous!.',
shortDescription: 'Convert CSV data to JSON format',
shortDescription: 'Convert CSV rows to columns.',
keywords: ['csv', 'rows', 'columns', 'transpose'],
component: lazy(() => import('./index'))
});

View File

@@ -7,7 +7,7 @@ export const tool = defineTool('csv', {
icon: 'lets-icons:json-light',
description:
'Convert CSV files to JSON format with customizable options for delimiters, quotes, and output formatting. Support for headers, comments, and dynamic type conversion.',
shortDescription: 'Convert CSV data to JSON format',
shortDescription: 'Convert CSV data to JSON format.',
keywords: ['csv', 'json', 'convert', 'transform', 'parse'],
component: lazy(() => import('./index'))
});

View File

@@ -7,7 +7,7 @@ export const tool = defineTool('csv', {
icon: 'codicon:keyboard-tab',
description:
'Upload your CSV file in the form below and it will automatically get converted to a TSV file. In the tool options, you can customize the input CSV format specify the field delimiter, quotation character, and comment symbol, as well as skip empty CSV lines, and choose whether to preserve CSV column headers.',
shortDescription: 'Convert CSV data to TSV format',
shortDescription: 'Convert CSV data to TSV format.',
longDescription:
'This tool transforms Comma Separated Values (CSV) data to Tab Separated Values (TSV) data. Both CSV and TSV are popular file formats for storing tabular data but they use different delimiters to separate values CSV uses commas (","), while TSV uses tabs ("\t"). If we compare CSV files to TSV files, then CSV files are much harder to parse than TSV files because the values themselves may contain commas, so it is not always obvious where one field starts and ends without complicated parsing rules. TSV, on the other hand, uses just a tab symbol, which does not usually appear in data, so separating fields in TSV is as simple as splitting the input by the tab character. To convert CSV to TSV, simply input the CSV data in the input of this tool. In rare cases when a CSV file has a delimiter other than a comma, you can specify the current delimiter in the options of the tool. You can also specify the current quote character and the comment start character. Additionally, empty CSV lines can be skipped by activating the "Ignore Lines with No Data" option. If this option is off, then empty lines in the CSV are converted to empty TSV lines. The "Preserve Headers" option allows you to choose whether to process column headers of a CSV file. If the option is selected, then the resulting TSV file will include the first row of the input CSV file, which contains the column names. Alternatively, if the headers option is not selected, the first row will be skipped during the data conversion process. For the reverse conversion from TSV to CSV, you can use our Convert TSV to CSV tool. Csv-abulous!',
keywords: ['csv', 'tsv', 'convert', 'transform', 'parse'],

View File

@@ -6,7 +6,7 @@ export const tool = defineTool('csv', {
path: 'csv-to-xml',
icon: 'mdi-light:xml',
description: 'Convert CSV files to XML format with customizable options.',
shortDescription: 'Convert CSV data to XML format',
shortDescription: 'Convert CSV data to XML format.',
keywords: ['csv', 'xml', 'convert', 'transform', 'parse'],
component: lazy(() => import('./index'))
});

View File

@@ -2,7 +2,7 @@ import { defineTool } from '@tools/defineTool';
import { lazy } from 'react';
export const tool = defineTool('csv', {
name: 'Csv to yaml',
name: 'Convert CSV to YAML',
path: 'csv-to-yaml',
icon: 'nonicons:yaml-16',
description:

View File

@@ -2,7 +2,7 @@ import { defineTool } from '@tools/defineTool';
import { lazy } from 'react';
export const tool = defineTool('csv', {
name: 'Find incomplete csv records',
name: 'Find incomplete CSV records',
path: 'find-incomplete-csv-records',
icon: 'tdesign:search-error',
description:

View File

@@ -1,3 +1,4 @@
import { tool as transposeCsv } from './transpose-csv/meta';
import { tool as findIncompleteCsvRecords } from './find-incomplete-csv-records/meta';
import { tool as ChangeCsvDelimiter } from './change-csv-separator/meta';
import { tool as csvToYaml } from './csv-to-yaml/meta';
@@ -15,5 +16,6 @@ export const csvTools = [
swapCsvColumns,
csvToYaml,
ChangeCsvDelimiter,
findIncompleteCsvRecords
findIncompleteCsvRecords,
transposeCsv
];

View File

@@ -7,7 +7,7 @@ export const tool = defineTool('csv', {
icon: 'eva:swap-outline',
description:
'Just upload your CSV file in the form below, specify the columns to swap, and the tool will automatically change the positions of the specified columns in the output file. In the tool options, you can specify the column positions or names that you want to swap, as well as fix incomplete data and optionally remove empty records and records that have been commented out.',
shortDescription: 'Reorder CSV columns',
shortDescription: 'Reorder CSV columns.',
longDescription:
'This tool reorganizes CSV data by swapping the positions of its columns. Swapping columns can enhance the readability of a CSV file by placing frequently used data together or in the front for easier data comparison and editing. For example, you can swap the first column with the last or swap the second column with the third. To swap columns based on their positions, select the "Set Column Position" mode and enter the numbers of the "from" and "to" columns to be swapped in the first and second blocks of options. For example, if you have a CSV file with four columns "1, 2, 3, 4" and swap columns with positions "2" and "4", the output CSV will have columns in the order: "1, 4, 3, 2".As an alternative to positions, you can swap columns by specifying their headers (column names on the first row of data). If you enable this mode in the options, then you can enter the column names like "location" and "city", and the program will swap these two columns. If any of the specified columns have incomplete data (some fields are missing), you can choose to skip such data or fill the missing fields with empty values or custom values (specified in the options). Additionally, you can specify the symbol used for comments in the CSV data, such as "#" or "//". If you do not need the commented lines in the output, you can remove them by using the "Delete Comments" checkbox. You can also activate the checkbox "Delete Empty Lines" to get rid of empty lines that contain no visible information. Csv-abulous!',
keywords: ['csv', 'swap', 'columns'],

View File

@@ -0,0 +1,178 @@
import { Box } from '@mui/material';
import React, { useState } from 'react';
import ToolContent from '@components/ToolContent';
import { ToolComponentProps } from '@tools/defineTool';
import ToolTextInput from '@components/input/ToolTextInput';
import ToolTextResult from '@components/result/ToolTextResult';
import { GetGroupsType } from '@components/options/ToolOptions';
import { CardExampleType } from '@components/examples/ToolExamples';
import { transposeCSV } from './service';
import { InitialValuesType } from './types';
import TextFieldWithDesc from '@components/options/TextFieldWithDesc';
import SelectWithDesc from '@components/options/SelectWithDesc';
const initialValues: InitialValuesType = {
separator: ',',
commentCharacter: '#',
customFill: false,
customFillValue: 'x',
quoteChar: '"'
};
const exampleCards: CardExampleType<InitialValuesType>[] = [
{
title: 'Transpose a 2x3 CSV',
description:
'This example transposes a CSV with 2 rows and 3 columns. The tool splits the input data by the comma character, creating a 2 by 3 matrix. It then exchanges elements, turning columns into rows and vice versa. The output is a transposed CSV with flipped dimensions',
sampleText: `foo,bar,baz
val1,val2,val3`,
sampleResult: `foo,val1
bar,val2
baz,val3`,
sampleOptions: {
separator: ',',
commentCharacter: '#',
customFill: false,
customFillValue: 'x',
quoteChar: '"'
}
},
{
title: 'Transpose a Long CSV',
description:
'In this example, we flip a vertical single-column CSV file containing a list of our favorite fruits and their emojis. This single column is transformed into a single-row CSV file and the rows length matches the height of the original CSV.',
sampleText: `Tasty Fruit
🍑 peaches
🍒 cherries
🥝 kiwis
🍓 strawberries
🍎 apples
🍐 pears
🥭 mangos
🍍 pineapples
🍌 bananas
🍊 tangerines
🍉 watermelons
🍇 grapes`,
sampleResult: `fTasty Fruit,🍑 peaches,🍒 cherries,🥝 kiwis,🍓 strawberries,🍎 apples,🍐 pears,🥭 mangos,🍍 pineapples,🍌 bananas,🍊 tangerines,🍉 watermelons,🍇 grapes`,
sampleOptions: {
separator: ',',
commentCharacter: '#',
customFill: false,
customFillValue: 'x',
quoteChar: '"'
}
},
{
title: 'Clean and Transpose CSV Data',
description:
'In this example, we perform three tasks simultaneously: transpose a CSV file, remove comments and empty lines, and fix missing data. The transposition operation is the same as flipping a matrix across its diagonal and it is done automatically by the program. Additionally, the program automatically removes all empty lines as they cannot be transposed. The comments are removed by specifying the "#" symbol in the options. The program also fixes missing data using a custom bullet symbol "•", which is specified in the options.',
sampleText: `Fish Type,Color,Habitat
Goldfish,Gold,Freshwater
#Clownfish,Orange,Coral Reefs
Tuna,Silver,Saltwater
Shark,Grey,Saltwater
Salmon,Silver`,
sampleResult: `Fish Type,Goldfish,Tuna,Shark,Salmon
Color,Gold,Silver,Grey,Silver
Habitat,Freshwater,Saltwater,Saltwater,•`,
sampleOptions: {
separator: ',',
commentCharacter: '#',
customFill: true,
customFillValue: '•',
quoteChar: '"'
}
}
];
export default function TransposeCsv({
title,
longDescription
}: ToolComponentProps) {
const [input, setInput] = useState<string>('');
const [result, setResult] = useState<string>('');
const compute = (values: InitialValuesType, input: string) => {
setResult(transposeCSV(input, values));
};
const getGroups: GetGroupsType<InitialValuesType> | null = ({
values,
updateField
}) => [
{
title: 'Csv input Options',
component: (
<Box>
<TextFieldWithDesc
value={values.separator}
onOwnChange={(val) => updateField('separator', val)}
description={
'Enter the character used to delimit columns in the CSV input file.'
}
/>
<TextFieldWithDesc
value={values.quoteChar}
onOwnChange={(val) => updateField('quoteChar', val)}
description={
'Enter the quote character used to quote the CSV input fields.'
}
/>
<TextFieldWithDesc
value={values.commentCharacter}
onOwnChange={(val) => updateField('commentCharacter', val)}
description={
'Enter the character indicating the start of a comment line. Lines starting with this symbol will be skipped.'
}
/>
</Box>
)
},
{
title: 'Fixing CSV Options',
component: (
<Box>
<SelectWithDesc
selected={values.customFill}
options={[
{ label: 'Fill With Empty Values', value: false },
{ label: 'Fill with Custom Values', value: true }
]}
onChange={(value) => updateField('customFill', value)}
description={
'Insert empty fields or custom values where the CSV data is missing (not empty).'
}
/>
{values.customFill && (
<TextFieldWithDesc
value={values.customFillValue}
onOwnChange={(val) => updateField('customFillValue', val)}
description={
'Enter the character used to fill missing values in the CSV input file.'
}
/>
)}
</Box>
)
}
];
return (
<ToolContent
title={title}
input={input}
inputComponent={
<ToolTextInput title="Input CSV" value={input} onChange={setInput} />
}
resultComponent={<ToolTextResult title="Transposed CSV" value={result} />}
initialValues={initialValues}
exampleCards={exampleCards}
getGroups={getGroups}
setInput={setInput}
compute={compute}
toolInfo={{ title: `What is a ${title}?`, description: longDescription }}
/>
);
}

View File

@@ -0,0 +1,15 @@
import { defineTool } from '@tools/defineTool';
import { lazy } from 'react';
export const tool = defineTool('csv', {
name: 'Transpose CSV',
path: 'transpose-csv',
icon: 'carbon:transpose',
description:
'Just upload your CSV file in the form below, and this tool will automatically transpose your CSV. In the tool options, you can specify the character that starts the comment lines in the CSV to remove them. Additionally, if the CSV is incomplete (missing values), you can replace missing values with the empty character or a custom character.',
shortDescription: 'Quickly transpose a CSV file.',
keywords: ['transpose', 'csv'],
longDescription:
'This tool transposes Comma Separated Values (CSV). It treats the CSV as a matrix of data and flips all elements across the main diagonal. The output contains the same CSV data as the input, but now all the rows have become columns, and all the columns have become rows. After transposition, the CSV file will have opposite dimensions. For example, if the input file has 4 columns and 3 rows, the output file will have 3 columns and 4 rows. During conversion, the program also cleans the data from unnecessary lines and corrects incomplete data. Specifically, the tool automatically deletes all empty records and comments that begin with a specific character, which you can set in the option. Additionally, in cases where the CSV data is corrupted or lost, the utility completes the file with empty fields or custom fields that can be specified in the options. Csv-abulous!',
component: lazy(() => import('./index'))
});

View File

@@ -0,0 +1,27 @@
import { InitialValuesType } from './types';
import { transpose, normalizeAndFill } from '@utils/array';
import { splitCsv } from '@utils/csv';
export function transposeCSV(
input: string,
options: InitialValuesType
): string {
if (!input) return '';
const rows = splitCsv(
input,
true,
options.commentCharacter,
true,
options.separator,
options.quoteChar
);
const normalizeAndFillRows = options.customFill
? normalizeAndFill(rows, options.customFillValue)
: normalizeAndFill(rows, '');
return transpose(normalizeAndFillRows)
.map((row) => row.join(options.separator))
.join('\n');
}

View File

@@ -0,0 +1,89 @@
import { expect, describe, it } from 'vitest';
import { transposeCSV } from './service';
import { InitialValuesType } from './types';
describe('transposeCsv', () => {
it('should transpose a simple CSV', () => {
const options: InitialValuesType = {
separator: ',',
commentCharacter: '#',
customFill: false,
customFillValue: 'x',
quoteChar: '"'
};
const input = 'a,b,c\n1,2,3';
const expectedOutput = 'a,1\nb,2\nc,3';
const result = transposeCSV(input, options);
expect(result).toEqual(expectedOutput);
});
it('should handle an empty CSV', () => {
const options: InitialValuesType = {
separator: ',',
commentCharacter: '#',
customFill: false,
customFillValue: 'x',
quoteChar: '"'
};
const input = '';
const expectedOutput = '';
const result = transposeCSV(input, options);
expect(result).toEqual(expectedOutput);
});
it('should handle a single row CSV', () => {
const options: InitialValuesType = {
separator: ',',
commentCharacter: '#',
customFill: false,
customFillValue: 'x',
quoteChar: '"'
};
const input = 'a,b,c';
const expectedOutput = 'a\nb\nc';
const result = transposeCSV(input, options);
expect(result).toEqual(expectedOutput);
});
it('should handle a single column CSV', () => {
const options: InitialValuesType = {
separator: ',',
commentCharacter: '#',
customFill: false,
customFillValue: 'x',
quoteChar: '"'
};
const input = 'a\nb\nc';
const expectedOutput = 'a,b,c';
const result = transposeCSV(input, options);
expect(result).toEqual(expectedOutput);
});
it('should handle uneven rows in the CSV', () => {
const options: InitialValuesType = {
separator: ',',
commentCharacter: '#',
customFill: true,
customFillValue: 'x',
quoteChar: '"'
};
const input = 'a,b\n1,2,3';
const expectedOutput = 'a,1\nb,2\nx,3';
const result = transposeCSV(input, options);
expect(result).toEqual(expectedOutput);
});
it('should skip comment in the CSV', () => {
const options: InitialValuesType = {
separator: ',',
commentCharacter: '#',
customFill: true,
customFillValue: 'x',
quoteChar: '"'
};
const input = 'a,b\n1,2\n#c,3\nd,4';
const expectedOutput = 'a,1,d\nb,2,4';
const result = transposeCSV(input, options);
expect(result).toEqual(expectedOutput);
});
});

View File

@@ -0,0 +1,7 @@
export type InitialValuesType = {
separator: string;
commentCharacter: string;
customFill: boolean;
customFillValue: string;
quoteChar: string;
};

View File

@@ -37,7 +37,6 @@ export async function protectPdf(
password: options.password
};
const protectedFileUrl: string = await protectWithGhostScript(dataObject);
console.log('protected', protectedFileUrl);
return await loadPDFData(
protectedFileUrl,
pdfFile.name.replace('.pdf', '-protected.pdf')

View File

@@ -0,0 +1,169 @@
import { Box } from '@mui/material';
import React, { useState } from 'react';
import ToolContent from '@components/ToolContent';
import { ToolComponentProps } from '@tools/defineTool';
import { GetGroupsType } from '@components/options/ToolOptions';
import { InitialValuesType } from './types';
import ToolVideoInput from '@components/input/ToolVideoInput';
import ToolFileResult from '@components/result/ToolFileResult';
import TextFieldWithDesc from '@components/options/TextFieldWithDesc';
import { FFmpeg } from '@ffmpeg/ffmpeg';
import { fetchFile } from '@ffmpeg/util';
const initialValues: InitialValuesType = {
newSpeed: 2
};
export default function ChangeSpeed({
title,
longDescription
}: ToolComponentProps) {
const [input, setInput] = useState<File | null>(null);
const [result, setResult] = useState<File | null>(null);
const [loading, setLoading] = useState(false);
// FFmpeg only supports a tempo between 0.5 and 2.0, so we chain filters
const computeAudioFilter = (speed: number): string => {
if (speed <= 2 && speed >= 0.5) {
return `atempo=${speed}`;
}
// Break into supported chunks
const filters: string[] = [];
let remainingSpeed = speed;
while (remainingSpeed > 2.0) {
filters.push('atempo=2.0');
remainingSpeed /= 2.0;
}
while (remainingSpeed < 0.5) {
filters.push('atempo=0.5');
remainingSpeed /= 0.5;
}
filters.push(`atempo=${remainingSpeed.toFixed(2)}`);
return filters.join(',');
};
const compute = (optionsValues: InitialValuesType, input: File | null) => {
if (!input) return;
const { newSpeed } = optionsValues;
let ffmpeg: FFmpeg | null = null;
let ffmpegLoaded = false;
const processVideo = async (
file: File,
newSpeed: number
): Promise<void> => {
if (newSpeed === 0) return;
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;
}
// Write file to FFmpeg FS
const fileName = file.name;
const outputName = 'output.mp4';
try {
ffmpeg.writeFile(fileName, await fetchFile(file));
const videoFilter = `setpts=${1 / newSpeed}*PTS`;
const audioFilter = computeAudioFilter(newSpeed);
// Run FFmpeg command
await ffmpeg.exec([
'-i',
fileName,
'-vf',
videoFilter,
'-filter:a',
audioFilter,
'-c:v',
'libx264',
'-preset',
'ultrafast',
'-c:a',
'aac',
outputName
]);
const data = await ffmpeg.readFile(outputName);
// Create new file from processed data
const blob = new Blob([data], { type: 'video/mp4' });
const newFile = new File(
[blob],
file.name.replace('.mp4', `-${newSpeed}x.mp4`),
{ type: 'video/mp4' }
);
// Clean up to free memory
await ffmpeg.deleteFile(fileName);
await ffmpeg.deleteFile(outputName);
setResult(newFile);
} catch (err) {
console.error(`Failed to process video: ${err}`);
throw err;
} finally {
setLoading(false);
}
};
// Here we set the output video
processVideo(input, newSpeed);
};
const getGroups: GetGroupsType<InitialValuesType> | null = ({
values,
updateField
}) => [
{
title: 'New Video Speed',
component: (
<Box>
<TextFieldWithDesc
value={values.newSpeed.toString()}
onOwnChange={(val) => updateField('newSpeed', Number(val))}
description="Default multiplier: 2 means 2x faster"
type="number"
/>
</Box>
)
}
];
return (
<ToolContent
title={title}
input={input}
inputComponent={
<ToolVideoInput
value={input}
onChange={setInput}
title={'Input Video'}
/>
}
resultComponent={
loading ? (
<ToolFileResult title="Setting Speed" value={null} loading={true} />
) : (
<ToolFileResult title="Edited Video" value={result} extension="mp4" />
)
}
initialValues={initialValues}
getGroups={getGroups}
setInput={setInput}
compute={compute}
toolInfo={{ title: `What is a ${title}?`, description: longDescription }}
/>
);
}

View File

@@ -0,0 +1,13 @@
import { defineTool } from '@tools/defineTool';
import { lazy } from 'react';
export const tool = defineTool('video', {
name: 'Change speed',
path: 'change-speed',
icon: 'material-symbols-light:speed-outline',
description:
'This online utility lets you change the speed of a video. You can speed it up or slow it down.',
shortDescription: 'Quickly change video speed',
keywords: ['change', 'speed'],
component: lazy(() => import('./index'))
});

View File

@@ -0,0 +1,8 @@
import { InitialValuesType } from './types';
export function main(
input: File | null,
options: InitialValuesType
): File | null {
return input;
}

View File

@@ -0,0 +1,3 @@
export type InitialValuesType = {
newSpeed: number;
};

View File

@@ -1,3 +1,4 @@
import { tool as videoChangeSpeed } from './change-speed/meta';
import { tool as videoFlip } from './flip/meta';
import { rotate } from '../string/rotate/service';
import { gifTools } from './gif';
@@ -7,6 +8,7 @@ import { tool as compressVideo } from './compress/meta';
import { tool as loopVideo } from './loop/meta';
import { tool as flipVideo } from './flip/meta';
import { tool as cropVideo } from './crop-video/meta';
import { tool as changeSpeed } from './change-speed/meta';
export const videoTools = [
...gifTools,
@@ -15,5 +17,6 @@ export const videoTools = [
compressVideo,
loopVideo,
flipVideo,
cropVideo
cropVideo,
changeSpeed
];

26
src/utils/array.ts Normal file
View File

@@ -0,0 +1,26 @@
/**
* Transpose a 2D array (matrix).
* @param {any[][]} matrix - The 2D array to transpose.
* @returns {any[][]} - The transposed 2D array.
**/
export function transpose<T>(matrix: T[][]): any[][] {
return matrix[0].map((_, colIndex) => matrix.map((row) => row[colIndex]));
}
/**
* Normalize and fill a 2D array to ensure all rows have the same length.
* @param {any[][]} matrix - The 2D array to normalize and fill.
* @param {any} fillValue - The value to fill in for missing elements.
* @returns {any[][]} - The normalized and filled 2D array.
* **/
export function normalizeAndFill<T>(matrix: T[][], fillValue: T): T[][] {
const maxLength = Math.max(...matrix.map((row) => row.length));
return matrix.map((row) => {
const filledRow = [...row];
while (filledRow.length < maxLength) {
filledRow.push(fillValue);
}
return filledRow;
});
}