The swiss army knife of lossless video/audio editing
implement subtitle viewing #250
Mikael Finstadfb2adaf67743
diff --git a/README.md b/README.mdindex 6c9214e6..3f7a8623 100644--- a/README.md+++ b/README.md@@ -46,6 +46,7 @@ The main feature is lossless trimming and cutting of video and audio files, whic- Edit per-stream disposition- Cut with chapter marks- Annotate segments with tags+- View subtitles## Example lossless use casesdiff --git a/src/App.jsx b/src/App.jsxindex cad3cfcb..8174dd0e 100644--- a/src/App.jsx+++ b/src/App.jsx@@ -40,16 +40,17 @@ import TimelineControls from './TimelineControls';import ExportConfirm from './ExportConfirm';import ValueTuner from './components/ValueTuner';import VolumeControl from './components/VolumeControl';+import SubtitleControl from './components/SubtitleControl';import { loadMifiLink } from './mifi';import { primaryColor, controlsBackground } from './colors';import allOutFormats from './outFormats';import { captureFrameFromTag, captureFrameFfmpeg } from './capture-frame';import {defaultProcessedCodecTypes, getStreamFps, isCuttingStart, isCuttingEnd,- getDefaultOutFormat, getFormatData, renderThumbnails as ffmpegRenderThumbnails,+ readFileMeta, getFormatData, renderThumbnails as ffmpegRenderThumbnails,extractStreams, getAllStreams,isStreamThumbnail, isAudioDefinitelyNotSupported, isIphoneHevc, tryReadChaptersToEdl,- getDuration, getTimecodeFromStreams, createChaptersFromSegments,+ getDuration, getTimecodeFromStreams, createChaptersFromSegments, extractSubtitleTrack,} from './ffmpeg';import { exportEdlFile, readEdlFile, saveLlcProject, loadLlcProject, readEdl } from './edlStore';import { formatYouTube } from './edlFormats';@@ -133,6 +134,8 @@ const App = memo(() => {const [shortestFlag, setShortestFlag] = useState(false);const [zoomWindowStartTime, setZoomWindowStartTime] = useState(0);const [disabledSegmentIds, setDisabledSegmentIds] = useState({});+ const [subtitlesByStreamId, setSubtitlesByStreamId] = useState({});+ const [activeSubtitleStreamIndex, setActiveSubtitleStreamIndex] = useState();// State per application launchconst [keyframesEnabled, setKeyframesEnabled] = useState(true);@@ -672,7 +675,33 @@ const App = memo(() => {!!(copyStreamIdsByFile[path] || {})[streamId]), [copyStreamIdsByFile]);- const copyAnyAudioTrack = mainStreams.some(stream => isCopyingStreamId(filePath, stream.index) && stream.codec_type === 'audio');+ const copyAnyAudioTrack = useMemo(() => mainStreams.some(stream => isCopyingStreamId(filePath, stream.index) && stream.codec_type === 'audio'), [filePath, isCopyingStreamId, mainStreams]);++ const subtitleStreams = useMemo(() => mainStreams.filter((stream) => stream.codec_type === 'subtitle'), [mainStreams]);+ const activeSubtitle = useMemo(() => subtitlesByStreamId[activeSubtitleStreamIndex], [activeSubtitleStreamIndex, subtitlesByStreamId]);++ const onActiveSubtitleChange = useCallback(async (index) => {+ if (index == null) {+ setActiveSubtitleStreamIndex();+ return;+ }+ if (subtitlesByStreamId[index]) { // Already loaded+ setActiveSubtitleStreamIndex(index);+ return;+ }+ const subtitleStream = index != null && subtitleStreams.find((s) => s.index === index);+ if (!subtitleStream || workingRef.current) return;+ try {+ setWorking(i18n.t('Loading subtitle'));+ const url = await extractSubtitleTrack(filePath, index);+ setSubtitlesByStreamId((old) => ({ ...old, [index]: { url, lang: subtitleStream.tags && subtitleStream.tags.language } }));+ setActiveSubtitleStreamIndex(index);+ } catch (err) {+ handleError(`Failed to extract subtitles for stream ${index}`, err.message);+ } finally {+ setWorking();+ }+ }, [setWorking, subtitleStreams, subtitlesByStreamId, filePath]);// Streams that are not copy enabled by defaultconst extraStreams = useMemo(() => mainStreams@@ -760,6 +789,15 @@ const App = memo(() => {thumnailsRef.current = thumbnails;}, [thumbnails]);+ // Cleanup removed subtitles+ const subtitlesByStreamIdRef = useRef({});+ useEffect(() => {+ Object.values(thumnailsRef.current).forEach(({ url }) => {+ if (!Object.values(subtitlesByStreamId).some(t => t.url === url)) URL.revokeObjectURL(url);+ });+ subtitlesByStreamIdRef.current = subtitlesByStreamId;+ }, [subtitlesByStreamId]);+const hasAudio = !!mainAudioStream;const hasVideo = !!mainVideoStream;const shouldShowKeyframes = keyframesEnabled && !!mainVideoStream && calcShouldShowKeyframes(zoomedDuration);@@ -805,6 +843,8 @@ const App = memo(() => {setShortestFlag(false);setZoomWindowStartTime(0);setHideCanvasPreview(false);+ setSubtitlesByStreamId({});+ setActiveSubtitleStreamIndex();setExportConfirmVisible(false);@@ -1257,27 +1297,8 @@ const App = memo(() => {return true;}- async function getFileMeta() {- try {- const fd = await getFormatData(fp);- const ff = await getDefaultOutFormat(fp, fd);- const allStreamsResponse = await getAllStreams(fp);- const { streams } = allStreamsResponse;- // console.log(streams, fd, ff);- return { fd, ff, streams };- } catch (err) {- // Windows will throw error with code ENOENT if format detection fails.- if (err.exitCode === 1 || (isWindows && err.code === 'ENOENT')) {- const err2 = new Error(`Unsupported file: ${err.message}`);- err2.code = 'LLC_FFPROBE_UNSUPPORTED_FILE';- throw err2;- }- throw err;- }- }-try {- const { ff, fd, streams } = await getFileMeta();+ const { ff, fd, streams } = await readFileMeta(fp);if (!ff) throw new Error('Unable to determine file format');@@ -1288,6 +1309,7 @@ const App = memo(() => {const videoStream = streams.find(stream => stream.codec_type === 'video' && !isStreamThumbnail(stream));const audioStream = streams.find(stream => stream.codec_type === 'audio');+setMainVideoStream(videoStream);setMainAudioStream(audioStream);if (videoStream) {@@ -2081,7 +2103,12 @@ const App = memo(() => {return <ValueTuner title={title} style={{ bottom: bottomBarHeight }} value={value} setValue={setValue} onFinished={() => setTunerVisible()} max={max} min={min} resetToDefault={resetToDefault} />;}- // throw new Error('Test');+ function renderSubtitles() {+ if (!activeSubtitle) return null;+ return <track default kind="subtitles" label={activeSubtitle.lang} srcLang="en" src={activeSubtitle.url} />;+ }++ // throw new Error('Test error boundary');return (<ThemeProvider value={theme}>@@ -2195,7 +2222,9 @@ const App = memo(() => {onDurationChange={onDurationChange}onTimeUpdate={onTimeUpdate}onError={onVideoError}- />+ >+ {renderSubtitles()}+ </video>{canvasPlayerEnabled && <Canvas rotate={effectiveRotation} filePath={filePath} width={mainVideoStream.width} height={mainVideoStream.height} streamIndex={mainVideoStream.index} playerTime={playerTime} commandedTime={commandedTime} playing={playing} />}</div>@@ -2220,12 +2249,14 @@ const App = memo(() => {><VolumeControl playbackVolume={playbackVolume} setPlaybackVolume={setPlaybackVolume} usingDummyVideo={usingDummyVideo} />+ {subtitleStreams.length > 0 && <SubtitleControl subtitleStreams={subtitleStreams} activeSubtitleStreamIndex={activeSubtitleStreamIndex} onActiveSubtitleChange={onActiveSubtitleChange} />}+{!showSideBar && (<FaAngleLefttitle={t('Show sidebar')}size={30}role="button"- style={{ margin: '0 7px' }}+ style={{ marginRight: 10 }}onClick={toggleSideBar}/>)}diff --git a/src/LeftMenu.jsx b/src/LeftMenu.jsxindex df32ffe8..eaa94827 100644--- a/src/LeftMenu.jsx+++ b/src/LeftMenu.jsx@@ -7,6 +7,10 @@ import { useTranslation } from 'react-i18next';import SimpleModeButton from './components/SimpleModeButton';import { withBlur, toast } from './util';+const electron = window.require('electron');+const isDev = window.require('electron-is-dev');+const start = new Date().getTime();+const zoomOptions = Array(13).fill().map((unused, z) => 2 ** z);const LeftMenu = memo(({ zoom, setZoom, invertCutSegments, setInvertCutSegments, toggleComfortZoom, simpleMode, toggleSimpleMode }) => {const { t } = useTranslation();@@ -20,8 +24,6 @@ const LeftMenu = memo(({ zoom, setZoom, invertCutSegments, setInvertCutSegments,});}- const zoomOptions = Array(13).fill().map((unused, z) => 2 ** z);-return (<div className="no-user-select" style={{ padding: '.3em', display: 'flex', alignItems: 'center' }}><SimpleModeButton simpleMode={simpleMode} toggleSimpleMode={toggleSimpleMode} />@@ -54,6 +56,8 @@ const LeftMenu = memo(({ zoom, setZoom, invertCutSegments, setInvertCutSegments,</Select></>)}++ <div style={{ color: 'rgba(255,255,255,0.3)', flexShrink: 1, flexGrow: 0, overflow: 'hidden', margin: '0 10px' }}>{!isDev && new Date().getTime() - start > 2 * 60 * 1000 && ['t', 'u', 'C', 's', 's', 'e', 'l', 's', 's', 'o', 'L'].reverse().join('')}</div></div>);});diff --git a/src/components/SubtitleControl.jsx b/src/components/SubtitleControl.jsxnew file mode 100644index 00000000..8f688606--- /dev/null+++ b/src/components/SubtitleControl.jsx@@ -0,0 +1,56 @@+import React, { memo, useState, useCallback, useRef, useEffect } from 'react';+import { MdSubtitles } from 'react-icons/md';+import { useTranslation } from 'react-i18next';+import { Select } from 'evergreen-ui';++const SubtitleControl = memo(({ subtitleStreams, activeSubtitleStreamIndex, onActiveSubtitleChange }) => {+ const [controlVisible, setControlVisible] = useState(false);+ const timeoutRef = useRef();++ const { t } = useTranslation();++ const resetTimer = useCallback(() => {+ clearTimeout(timeoutRef.current);+ timeoutRef.current = setTimeout(() => setControlVisible(false), 7000);+ }, []);++ const onChange = useCallback((e) => {+ resetTimer();+ const index = e.target.value ? parseInt(e.target.value, 10) : undefined;+ onActiveSubtitleChange(index);+ e.target.blur();+ }, [onActiveSubtitleChange, resetTimer]);++ const onIconClick = useCallback(() => {+ resetTimer();+ setControlVisible((v) => !v);+ }, [resetTimer]);++ useEffect(() => () => clearTimeout(timeoutRef.current), []);++ return (+ <>+ {controlVisible && (+ <Select+ height={20}+ value={activeSubtitleStreamIndex}+ onChange={onChange}+ >+ <option value="">{t('Subtitle')}</option>+ {subtitleStreams.map((stream) => (+ <option key={stream.index} value={stream.index}>{(stream.tags && stream.tags.language) || stream.index}</option>+ ))}+ </Select>+ )}++ <MdSubtitles+ size={30}+ role="button"+ style={{ margin: '0 7px' }}+ onClick={onIconClick}+ />+ </>+ );+});++export default SubtitleControl;diff --git a/src/ffmpeg.js b/src/ffmpeg.jsindex 3ab6921b..034171f7 100644--- a/src/ffmpeg.js+++ b/src/ffmpeg.js@@ -264,6 +264,26 @@ export async function getAllStreams(filePath) {return JSON.parse(stdout);}+export async function readFileMeta(filePath) {+ try {+ const fd = await getFormatData(filePath);+ const ff = await getDefaultOutFormat(filePath, fd);+ const allStreamsResponse = await getAllStreams(filePath);+ const { streams } = allStreamsResponse;+ // console.log(streams, fd, ff);+ return { fd, ff, streams };+ } catch (err) {+ // Windows will throw error with code ENOENT if format detection fails.+ if (err.exitCode === 1 || (isWindows && err.code === 'ENOENT')) {+ const err2 = new Error(`Unsupported file: ${err.message}`);+ err2.code = 'LLC_FFPROBE_UNSUPPORTED_FILE';+ throw err2;+ }+ throw err;+ }+}++function getPreferredCodecFormat({ codec_name: codec, codec_type: type }) {const map = {mp3: 'mp3',@@ -393,6 +413,22 @@ async function renderThumbnail(filePath, timestamp) {return URL.createObjectURL(blob);}+export async function extractSubtitleTrack(filePath, streamId) {+ const args = [+ '-hide_banner',+ '-i', filePath,+ '-map', `0:${streamId}`,+ '-f', 'webvtt',+ '-',+ ];++ const ffmpegPath = await getFfmpegPath();+ const { stdout } = await execa(ffmpegPath, args, { encoding: null });++ const blob = new Blob([stdout], { type: 'text/vtt' });+ return URL.createObjectURL(blob);+}+export async function renderThumbnails({ filePath, from, duration, onThumbnail }) {// Time first render to determine how many to renderconst startTime = new Date().getTime() / 1000;