The swiss army knife of lossless video/audio editing
support more timecode formats in input field
Mikael Finstad1e34639db94a
diff --git a/src/App.jsx b/src/App.jsxindex 64a34bc3..ee330de2 100644--- a/src/App.jsx+++ b/src/App.jsx@@ -160,9 +160,6 @@ const App = memo(() => {const [batchFiles, setBatchFiles] = useState([]);const [selectedBatchFiles, setSelectedBatchFiles] = useState([]);- const [cutStartTimeManual, setCutStartTimeManual] = useState();- const [cutEndTimeManual, setCutEndTimeManual] = useState();-// Store "working" in a ref so we can avoid race conditionsconst workingRef = useRef(working);const setWorking = useCallback((val) => {@@ -656,8 +653,6 @@ const App = memo(() => {setDuration();cutSegmentsHistory.go(0);clearSegments();- setCutStartTimeManual();- setCutEndTimeManual();setFileFormat();setDetectedFileFormat();setRotation(360);@@ -2346,10 +2341,6 @@ const App = memo(() => {setCutStart={setCutStart}setCutEnd={setCutEnd}setCurrentSegIndex={setCurrentSegIndex}- cutStartTimeManual={cutStartTimeManual}- setCutStartTimeManual={setCutStartTimeManual}- cutEndTimeManual={cutEndTimeManual}- setCutEndTimeManual={setCutEndTimeManual}jumpCutEnd={jumpCutEnd}jumpCutStart={jumpCutStart}jumpTimelineStart={jumpTimelineStart}diff --git a/src/BottomBar.jsx b/src/BottomBar.jsxindex ff1eb736..205dbdeb 100644--- a/src/BottomBar.jsx+++ b/src/BottomBar.jsx@@ -1,4 +1,4 @@-import React, { memo, useCallback, useEffect, useMemo } from 'react';+import React, { memo, useCallback, useEffect, useMemo, useState } from 'react';import { Select } from 'evergreen-ui';import { motion } from 'framer-motion';import { MdRotate90DegreesCcw } from 'react-icons/md';@@ -19,19 +19,121 @@ import SimpleModeButton from './components/SimpleModeButton';import { withBlur, mirrorTransform, checkAppPath } from './util';import { toast } from './swal';import { getSegColor } from './util/colors';-import { formatDuration, parseDuration } from './util/duration';+import { formatDuration, parseDuration, isExactDurationMatch } from './util/duration';import useUserSettings from './hooks/useUserSettings';+const { clipboard } = window.require('electron');++const zoomOptions = Array(13).fill().map((unused, z) => 2 ** z);const leftRightWidth = 100;+const CutTimeInput = memo(({ cutTime, setCutTime, startTimeOffset, seekAbs, currentCutSeg, currentApparentCutSeg, isStart }) => {+ const { t } = useTranslation();++ const [cutTimeManual, setCutTimeManual] = useState();++ // Clear manual overrides if upstream cut time has changed+ useEffect(() => {+ setCutTimeManual();+ }, [setCutTimeManual, currentApparentCutSeg.start, currentApparentCutSeg.end]);++ const isCutTimeManualSet = () => cutTimeManual !== undefined;++ const border = `1px solid ${getSegColor(currentCutSeg).alpha(0.8).string()}`;++ const cutTimeInputStyle = {+ background: 'white', border, borderRadius: 5, color: 'rgba(0, 0, 0, 0.7)', fontSize: 13, textAlign: 'center', padding: '1px 5px', marginTop: 0, marginBottom: 0, marginLeft: isStart ? 0 : 5, marginRight: isStart ? 5 : 0, boxSizing: 'border-box', fontFamily: 'inherit', width: 90, outline: 'none',+ };++ const trySetTime = useCallback((timeWithOffset) => {+ const timeWithoutOffset = Math.max(timeWithOffset - startTimeOffset, 0);+ try {+ setCutTime(isStart ? 'start' : 'end', timeWithoutOffset);+ seekAbs(timeWithoutOffset);+ setCutTimeManual();+ } catch (err) {+ console.error('Cannot set cut time', err);+ // If we get an error from setCutTime, remain in the editing state (cutTimeManual)+ // https://github.com/mifi/lossless-cut/issues/988+ }+ }, [isStart, seekAbs, setCutTime, startTimeOffset]);++ const handleSubmit = useCallback((e) => {+ e.preventDefault();++ // Don't proceed if not a valid time value+ const timeWithOffset = parseDuration(cutTimeManual);+ if (timeWithOffset === undefined) return;++ trySetTime(timeWithOffset);+ }, [cutTimeManual, trySetTime]);++ const parseAndSetCutTime = useCallback((text) => {+ // Don't proceed if not a valid time value+ const timeWithOffset = parseDuration(text);+ if (timeWithOffset === undefined) return;++ trySetTime(timeWithOffset);+ }, [trySetTime]);++ function handleCutTimeInput(text) {+ setCutTimeManual(text);++ if (isExactDurationMatch(text)) parseAndSetCutTime(text);+ }++ const tryPaste = useCallback((clipboardText) => {+ try {+ setCutTimeManual(clipboardText);+ parseAndSetCutTime(clipboardText);+ } catch (err) {+ console.error(err);+ }+ }, [parseAndSetCutTime]);++ const handleCutTimePaste = useCallback((e) => {+ e.preventDefault();++ try {+ const clipboardData = e.clipboardData.getData('Text');+ setCutTimeManual(clipboardData);+ parseAndSetCutTime(clipboardData);+ } catch (err) {+ console.error(err);+ }+ }, [parseAndSetCutTime]);++ const handleContextMenu = useCallback(() => {+ const text = clipboard.readText();+ if (text) tryPaste(text);+ }, [tryPaste]);++ return (+ <form onSubmit={handleSubmit}>+ <input+ style={{ ...cutTimeInputStyle, color: isCutTimeManualSet() ? '#dc1d1d' : undefined }}+ type="text"+ title={isStart ? t('Manually input current segment\'s start time') : t('Manually input current segment\'s end time')}+ onChange={e => handleCutTimeInput(e.target.value)}+ onPaste={handleCutTimePaste}+ onBlur={() => setCutTimeManual()}+ onContextMenu={handleContextMenu}+ value={isCutTimeManualSet()+ ? cutTimeManual+ : formatDuration({ seconds: cutTime + startTimeOffset })}+ />+ </form>+ );+});+const BottomBar = memo(({zoom, setZoom, timelineToggleComfortZoom,isRotationSet, rotation, areWeCutting, increaseRotation, cleanupFilesDialog,captureSnapshot, onExportPress, segmentsToExport, hasVideo,seekAbs, currentSegIndexSafe, cutSegments, currentCutSeg, setCutStart, setCutEnd,- setCurrentSegIndex, cutStartTimeManual, setCutStartTimeManual, cutEndTimeManual, setCutEndTimeManual,+ setCurrentSegIndex,jumpTimelineStart, jumpTimelineEnd, jumpCutEnd, jumpCutStart, startTimeOffset, setCutTime, currentApparentCutSeg,playing, shortStep, togglePlay, toggleLoopSelectedSegments, toggleTimelineMode, hasAudio, timelineMode,keyframesEnabled, toggleKeyframesEnabled, seekClosestKeyframe, detectedFps, isFileOpened, selectedSegments,@@ -77,12 +179,6 @@ const BottomBar = memo(({const rotationStr = `${rotation}°`;- // Clear manual overrides if upstream cut time has changed- useEffect(() => {- setCutStartTimeManual();- setCutEndTimeManual();- }, [setCutStartTimeManual, setCutEndTimeManual, currentApparentCutSeg.start, currentApparentCutSeg.end]);-useEffect(() => {checkAppPath();}, []);@@ -111,74 +207,6 @@ const BottomBar = memo(({);}- function renderCutTimeInput(type) {- const isStart = type === 'start';-- const cutTimeManual = isStart ? cutStartTimeManual : cutEndTimeManual;- const cutTime = isStart ? currentApparentCutSeg.start : currentApparentCutSeg.end;- const setCutTimeManual = isStart ? setCutStartTimeManual : setCutEndTimeManual;-- const isCutTimeManualSet = () => cutTimeManual !== undefined;-- const border = `1px solid ${getSegColor(currentCutSeg).alpha(0.8).string()}`;-- const cutTimeInputStyle = {- background: 'white', border, borderRadius: 5, color: 'rgba(0, 0, 0, 0.7)', fontSize: 13, textAlign: 'center', padding: '1px 5px', marginTop: 0, marginBottom: 0, marginLeft: isStart ? 0 : 5, marginRight: isStart ? 5 : 0, boxSizing: 'border-box', fontFamily: 'inherit', width: 90, outline: 'none',- };-- function parseAndSetCutTime(text) {- setCutTimeManual(text);-- // Don't proceed if not a valid time value- const timeWithOffset = parseDuration(text);- if (timeWithOffset === undefined) return;-- const timeWithoutOffset = Math.max(timeWithOffset - startTimeOffset, 0);- try {- setCutTime(type, timeWithoutOffset);- seekAbs(timeWithoutOffset);- } catch (err) {- console.error('Cannot set cut time', err);- // If we get an error from setCutTime, remain in the editing state (cutTimeManual)- // https://github.com/mifi/lossless-cut/issues/988- }- }-- function handleCutTimeInput(text) {- // Allow the user to erase to reset- if (text.length === 0) {- setCutTimeManual();- return;- }-- parseAndSetCutTime(text);- }-- async function handleCutTimePaste(e) {- e.preventDefault();-- try {- const clipboardData = e.clipboardData.getData('Text');- parseAndSetCutTime(clipboardData);- } catch (err) {- console.error(err);- }- }-- return (- <input- style={{ ...cutTimeInputStyle, color: isCutTimeManualSet() ? '#dc1d1d' : undefined }}- type="text"- title={isStart ? t('Manually input current segment\'s start time') : t('Manually input current segment\'s end time')}- onChange={e => handleCutTimeInput(e.target.value)}- onPaste={handleCutTimePaste}- value={isCutTimeManualSet()- ? cutTimeManual- : formatDuration({ seconds: cutTime + startTimeOffset })}- />- );- }-const PlayPause = playing ? FaPause : FaPlay;return (@@ -239,7 +267,7 @@ const BottomBar = memo(({<SetCutpointButton currentCutSeg={currentCutSeg} side="start" onClick={setCutStart} title={t('Start current segment at current time')} style={{ marginRight: 5 }} />- {!simpleMode && renderCutTimeInput('start')}+ {!simpleMode && <CutTimeInput currentCutSeg={currentCutSeg} currentApparentCutSeg={currentApparentCutSeg} startTimeOffset={startTimeOffset} seekAbs={seekAbs} cutTime={currentApparentCutSeg.start} setCutTime={setCutTime} isStart />}<IoMdKeysize={25}@@ -290,7 +318,7 @@ const BottomBar = memo(({onClick={() => seekClosestKeyframe(1)}/>- {!simpleMode && renderCutTimeInput('end')}+ {!simpleMode && <CutTimeInput currentCutSeg={currentCutSeg} currentApparentCutSeg={currentApparentCutSeg} startTimeOffset={startTimeOffset} seekAbs={seekAbs} cutTime={currentApparentCutSeg.end} setCutTime={setCutTime} />}<SetCutpointButton currentCutSeg={currentCutSeg} side="end" onClick={setCutEnd} title={t('End current segment at current time')} style={{ marginLeft: 5 }} />diff --git a/src/util/duration.js b/src/util/duration.jsindex 9563a61c..70da9d2a 100644--- a/src/util/duration.js+++ b/src/util/duration.js@@ -32,18 +32,25 @@ export function formatDuration({ seconds: secondsIn, fileNameFriendly, showMs =return `${sign}${hoursPart}${minutesPadded}${delim}${secondsPadded}${msPart}`;}+export const isExactDurationMatch = (str) => /^-?\d{2}:\d{2}:\d{2}.\d{3}$/.test(str);++// See also parseYoutubeexport function parseDuration(str) {- if (!str) return undefined;- const match = str.trim().match(/^(-?)(\d{2}):(\d{2}):(\d{2})\.(\d{3})$/);+ const match = str.replace(/\s/g, '').match(/^(-?)(?:(?:(\d{1,}):)?(\d{1,2}):)?(\d{1,2}(?:[.,]\d{1,3})?)$/);+if (!match) return undefined;- const isNegatve = match[1] === '-';- const hours = parseInt(match[2], 10);- const minutes = parseInt(match[3], 10);- const seconds = parseInt(match[4], 10);- const ms = parseInt(match[5], 10);- if (hours > 59 || minutes > 59 || seconds > 59) return undefined;-- let ret = (((((hours * 60) + minutes) * 60) + seconds) + (ms / 1000));- if (isNegatve) ret *= -1;- return ret;++ const [, sign, hourStr, minStr, secStrRaw] = match;+ const secStr = secStrRaw.replace(',', '.');+ const hour = hourStr != null ? parseInt(hourStr, 10) : 0;+ const min = minStr != null ? parseInt(minStr, 10) : 0;+ const sec = parseFloat(secStr);++ if (min > 59 || sec >= 60) return undefined;++ let time = (((hour * 60) + min) * 60 + sec);++ if (sign === '-') time *= -1;++ return time;}diff --git a/src/util/duration.test.js b/src/util/duration.test.jsindex e8342c01..0909a593 100644--- a/src/util/duration.test.js+++ b/src/util/duration.test.js@@ -16,7 +16,8 @@ it('should format duration properly', () => {expect(formatDuration({ seconds: 101.5, showMs: false, shorten: true })).toBe('1:41');});-it('shoud format and parse duration with correct rounding', () => {+it('should format and parse duration with correct rounding', () => {+ // https://github.com/mifi/lossless-cut/issues/1217expect(formatDuration({ seconds: parseDuration('00:00:15.426') })).toBe('00:00:15.426');expect(formatDuration({ seconds: parseDuration('00:00:15.427') })).toBe('00:00:15.427');expect(formatDuration({ seconds: parseDuration('00:00:00.000') })).toBe('00:00:00.000');@@ -24,4 +25,18 @@ it('shoud format and parse duration with correct rounding', () => {expect(formatDuration({ seconds: parseDuration('00:00:01.000') })).toBe('00:00:01.000');expect(formatDuration({ seconds: parseDuration('00:00:01.001') })).toBe('00:00:01.001');expect(formatDuration({ seconds: parseDuration('24:59:59.999') })).toBe('24:59:59.999');+ expect(formatDuration({ seconds: parseDuration('01:02:03.45') })).toBe('01:02:03.450');+ expect(formatDuration({ seconds: parseDuration('01:02:03,45') })).toBe('01:02:03.450');+ expect(formatDuration({ seconds: parseDuration('01:02:03.4') })).toBe('01:02:03.400');+ expect(formatDuration({ seconds: parseDuration('01:02:03.456') })).toBe('01:02:03.456');+ expect(formatDuration({ seconds: parseDuration('-01:02:03.456') })).toBe('-01:02:03.456');+ expect(formatDuration({ seconds: parseDuration('01:02.345') })).toBe('00:01:02.345');+ expect(formatDuration({ seconds: parseDuration('01:02.003') })).toBe('00:01:02.003');+ expect(formatDuration({ seconds: parseDuration('01:01.2') })).toBe('00:01:01.200');+ expect(formatDuration({ seconds: parseDuration('1:1.2') })).toBe('00:01:01.200');+ expect(formatDuration({ seconds: parseDuration('01.234') })).toBe('00:00:01.234');+ expect(formatDuration({ seconds: parseDuration('1.234') })).toBe('00:00:01.234');+ expect(formatDuration({ seconds: parseDuration('1') })).toBe('00:00:01.000');+ expect(formatDuration({ seconds: parseDuration('-1') })).toBe('-00:00:01.000');+ expect(formatDuration({ seconds: parseDuration('01') })).toBe('00:00:01.000');});