Skip to content

The swiss army knife of lossless video/audio editing

chapters improvments #993

Mikael Finstad6d8981798dbd
diff --git a/src/App.jsx b/src/App.jsx
index 85cef533..e80269f9 100644
--- a/src/App.jsx
+++ b/src/App.jsx
@@ -72,7 +72,7 @@ import { adjustRate } from './util/rate-calculator';
import { askForOutDir, askForInputDir, askForImportChapters, createNumSegments as createNumSegmentsDialog, createFixedDurationSegments as createFixedDurationSegmentsDialog, promptTimeOffset, askForHtml5ifySpeed, askForFileOpenAction, confirmExtractAllStreamsDialog, showCleanupFilesDialog, showDiskFull, showCutFailedDialog, labelSegmentDialog, openYouTubeChaptersDialog, openAbout, showEditableJsonDialog, askForShiftSegments } from './dialogs';
import { openSendReportDialog } from './reporting';
import { fallbackLng } from './i18n';
-import { createSegment, getCleanCutSegments, getSegApparentStart, findSegmentsAtCursor, sortSegments, invertSegments, getSegmentTags } from './segments';
+import { createSegment, getCleanCutSegments, getSegApparentStart, findSegmentsAtCursor, sortSegments, invertSegments, getSegmentTags, convertSegmentsToChapters, hasAnySegmentOverlap } from './segments';
import { getOutSegError as getOutSegErrorRaw } from './util/outputNameTemplate';
@@ -369,12 +369,10 @@ const App = memo(() => {
const jumpTimelineStart = useCallback(() => seekAbs(0), [seekAbs]);
const jumpTimelineEnd = useCallback(() => seekAbs(durationSafe), [durationSafe, seekAbs]);
- const sortedCutSegments = useMemo(() => sortSegments(apparentCutSegments), [apparentCutSegments]);
-
const inverseCutSegments = useMemo(() => {
- const inverted = !haveInvalidSegs && isDurationValid(duration) ? invertSegments(sortedCutSegments, duration) : undefined;
+ const inverted = !haveInvalidSegs && isDurationValid(duration) ? invertSegments(sortSegments(apparentCutSegments), true, true, duration) : undefined;
return (inverted || []).map((seg) => ({ ...seg, segId: `${seg.start}-${seg.end}` }));
- }, [duration, haveInvalidSegs, sortedCutSegments]);
+ }, [apparentCutSegments, duration, haveInvalidSegs]);
const invertAllCutSegments = useCallback(() => {
// don't reset segIndex (which represent colors) when inverting
@@ -1149,8 +1147,8 @@ const App = memo(() => {
const filenamifyOrNot = useCallback((name) => (safeOutputFileName ? filenamify(name) : name).substr(0, maxLabelLength), [safeOutputFileName, maxLabelLength]);
const segmentsToExport = useMemo(() => {
- // This is a special mode where all segments will be simply written out as chapters to one file: https://github.com/mifi/lossless-cut/issues/993#issuecomment-1037927595
if (!segmentsToChaptersOnly) return enabledSegments;
+ // segmentsToChaptersOnly is a special mode where all segments will be simply written out as chapters to one file: https://github.com/mifi/lossless-cut/issues/993#issuecomment-1037927595
// Chapters export mode: Emulate a single segment with no cuts (full timeline)
return [{ start: 0, end: getSegApparentEnd({}) }];
}, [enabledSegments, getSegApparentEnd, segmentsToChaptersOnly]);
@@ -1223,7 +1221,15 @@ const App = memo(() => {
setWorking(i18n.t('Exporting'));
// Special segments-to-chapters mode:
- const chaptersToAdd = segmentsToChaptersOnly && sortBy(enabledSegments, 'start').map((segment) => ({ start: segment.start, end: segment.end, name: segment.name }));
+ let chaptersToAdd;
+ if (segmentsToChaptersOnly) {
+ const sortedSegments = sortSegments(enabledSegments);
+ if (hasAnySegmentOverlap(sortedSegments)) {
+ errorToast(i18n.t('Make sure you have no overlapping segments.'));
+ return;
+ }
+ chaptersToAdd = convertSegmentsToChapters(sortedSegments);
+ }
console.log('outSegTemplateOrDefault', outSegTemplateOrDefault);
diff --git a/src/__snapshots__/edlFormats.test.js.snap b/src/__snapshots__/edlFormats.test.js.snap
index 85fec0cf..742a7a16 100644
--- a/src/__snapshots__/edlFormats.test.js.snap
+++ b/src/__snapshots__/edlFormats.test.js.snap
@@ -1,5 +1,100 @@
// Jest Snapshot v1, https://goo.gl/fbAQLP
+exports[`parses pbf 1`] = `
+Array [
+ Object {
+ "end": 189.053,
+ "name": "label 1",
+ "start": 104.612,
+ },
+ Object {
+ "end": 476.194,
+ "name": "label 2",
+ "start": 300.448,
+ },
+ Object {
+ "end": 704.264,
+ "name": "label 3",
+ "start": 567.075,
+ },
+ Object {
+ "end": 855.455,
+ "name": "label 4",
+ "start": 704.264,
+ },
+]
+`;
+
+exports[`parses pbf 2`] = `
+Array [
+ Object {
+ "end": 189.053,
+ "name": "label 1",
+ "start": 104.612,
+ },
+ Object {
+ "end": 300.448,
+ "name": "label 2",
+ "start": 189.053,
+ },
+ Object {
+ "end": 476.194,
+ "name": "label 3",
+ "start": 300.448,
+ },
+ Object {
+ "end": 567.075,
+ "name": "label 4",
+ "start": 476.194,
+ },
+ Object {
+ "end": 704.264,
+ "name": "label 5",
+ "start": 567.075,
+ },
+ Object {
+ "end": 855.455,
+ "name": "label 6",
+ "start": 704.264,
+ },
+]
+`;
+
+exports[`parses pbf 3`] = `
+Array [
+ Object {
+ "end": 189.053,
+ "name": "A",
+ "start": 104.612,
+ },
+ Object {
+ "end": 476.194,
+ "name": "B",
+ "start": 300.448,
+ },
+ Object {
+ "end": 704.264,
+ "name": "C",
+ "start": 567.075,
+ },
+]
+`;
+
+exports[`parses pbf 4`] = `
+Array [
+ Object {
+ "end": 189.053,
+ "name": "A",
+ "start": 104.612,
+ },
+ Object {
+ "end": 476.194,
+ "name": "B",
+ "start": 300.448,
+ },
+]
+`;
+
exports[`parses xmeml 1 1`] = `
Array [
Object {
diff --git a/src/__snapshots__/segments.test.js.snap b/src/__snapshots__/segments.test.js.snap
new file mode 100644
index 00000000..7fa66dc2
--- /dev/null
+++ b/src/__snapshots__/segments.test.js.snap
@@ -0,0 +1,63 @@
+// Jest Snapshot v1, https://goo.gl/fbAQLP
+
+exports[`converts segments to chapters with gaps 1`] = `
+Array [
+ Object {
+ "end": 104.612,
+ "start": 0,
+ },
+ Object {
+ "end": 189.053,
+ "name": "label 1",
+ "start": 104.612,
+ },
+ Object {
+ "end": 300.448,
+ "start": 189.053,
+ },
+ Object {
+ "end": 476.194,
+ "name": "label 2",
+ "start": 300.448,
+ },
+ Object {
+ "end": 567.075,
+ "start": 476.194,
+ },
+ Object {
+ "end": 704.264,
+ "name": "label 3",
+ "start": 567.075,
+ },
+ Object {
+ "end": 855.455,
+ "name": "label 4",
+ "start": 704.264,
+ },
+]
+`;
+
+exports[`converts segments to chapters with no gaps 1`] = `
+Array [
+ Object {
+ "end": 2,
+ "name": "label 1",
+ "start": 0,
+ },
+ Object {
+ "end": 3,
+ "name": "label 2",
+ "start": 2,
+ },
+]
+`;
+
+exports[`converts segments to chapters with single long segment 1`] = `
+Array [
+ Object {
+ "end": 1,
+ "name": "label 1",
+ "start": 0,
+ },
+]
+`;
diff --git a/src/edlFormats.js b/src/edlFormats.js
index 7c6e6624..f8bb0f90 100644
--- a/src/edlFormats.js
+++ b/src/edlFormats.js
@@ -65,7 +65,7 @@ export async function parseMplayerEdl(text) {
const sceneMarkers = allRows.filter((row) => row.type === 2);
const commercialBreaks = allRows.filter((row) => row.type === 3);
- const inverted = cutAwaySegments.length > 0 ? invertSegments(sortSegments(cutAwaySegments)) : [];
+ const inverted = cutAwaySegments.length > 0 ? invertSegments(sortSegments(cutAwaySegments), true, true) : [];
const map = (segments, name, type) => segments.map(({ start, end }) => ({ start, end, name, tags: { mplayerEdlType: type } }));
@@ -104,7 +104,8 @@ export function parseCuesheet(cuesheet) {
}
// See https://github.com/mifi/lossless-cut/issues/993#issuecomment-1037090403
-export function parsePbf(text) {
+export function parsePbf(buf) {
+ const text = buf.toString('utf16le');
const bookmarks = text.split('\n').map((line) => {
const match = line.match(/^[0-9]+=([0-9]+)\*([^*]+)*([^*]+)?/);
if (match) return { time: parseInt(match[1], 10) / 1000, name: match[2] };
@@ -113,11 +114,18 @@ export function parsePbf(text) {
const out = [];
- for (let i = 0; i < bookmarks.length; i += 2) {
+ for (let i = 0; i < bookmarks.length;) {
const bookmark = bookmarks[i];
const nextBookmark = bookmarks[i + 1];
- out.push({ start: bookmark.time, end: nextBookmark && nextBookmark.time, name: bookmark.name });
+ if (!nextBookmark) {
+ out.push({ start: bookmark.time, end: undefined, name: bookmark.name });
+ i += 1;
+ } else {
+ out.push({ start: bookmark.time, end: nextBookmark && nextBookmark.time, name: bookmark.name });
+ i += nextBookmark.name === ' ' ? 2 : 1;
+ }
}
+
return out;
}
diff --git a/src/edlFormats.test.js b/src/edlFormats.test.js
index bf62b9d2..2b9e2d87 100644
--- a/src/edlFormats.test.js
+++ b/src/edlFormats.test.js
@@ -1,9 +1,9 @@
-import fs from 'fs';
+import fs from 'fs/promises';
import { join } from 'path';
-import { parseYouTube, formatYouTube, parseMplayerEdl, parseXmeml, parseCsv, getTimeFromFrameNum, formatCsvFrames, getFrameCountRaw } from './edlFormats';
+import { parseYouTube, formatYouTube, parseMplayerEdl, parseXmeml, parseCsv, getTimeFromFrameNum, formatCsvFrames, getFrameCountRaw, parsePbf } from './edlFormats';
-const readFixture = async (name, encoding = 'utf-8') => fs.promises.readFile(join(__dirname, 'fixtures', name), encoding);
+const readFixture = async (name, encoding = 'utf-8') => fs.readFile(join(__dirname, 'fixtures', name), encoding);
it('parseYoutube', () => {
const str = `
@@ -165,3 +165,10 @@ it('parses csv with frames', async () => {
});
expect(formatted).toEqual(csvFramesStr);
});
+
+it('parses pbf', async () => {
+ expect(parsePbf(await readFixture('test1.pbf', null))).toMatchSnapshot();
+ expect(parsePbf(await readFixture('test2.pbf', null))).toMatchSnapshot();
+ expect(parsePbf(await readFixture('test3.pbf', null))).toMatchSnapshot();
+ expect(parsePbf(await readFixture('potplayer bookmark format utf16le issue 867.pbf', null))).toMatchSnapshot();
+});
diff --git a/src/edlStore.js b/src/edlStore.js
index 203a0aaf..3e6f6416 100644
--- a/src/edlStore.js
+++ b/src/edlStore.js
@@ -24,7 +24,7 @@ export async function loadXmeml(path) {
}
export async function loadPbf(path) {
- return parsePbf(await fs.readFile(path, 'utf16le'));
+ return parsePbf(await fs.readFile(path));
}
export async function loadMplayerEdl(path) {
diff --git a/src/ffmpeg.js b/src/ffmpeg.js
index 81688b7b..ab2d0473 100644
--- a/src/ffmpeg.js
+++ b/src/ffmpeg.js
@@ -214,20 +214,19 @@ export async function getDuration(filePath) {
}
export async function createChaptersFromSegments({ segmentPaths, chapterNames }) {
- if (chapterNames) {
- try {
- const durations = await pMap(segmentPaths, (segmentPath) => getDuration(segmentPath), { concurrency: 3 });
- let timeAt = 0;
- return durations.map((duration, i) => {
- const ret = { start: timeAt, end: timeAt + duration, name: chapterNames[i] };
- timeAt += duration;
- return ret;
- });
- } catch (err) {
- console.error('Failed to create chapters from segments', err);
- }
+ if (!chapterNames) return undefined;
+ try {
+ const durations = await pMap(segmentPaths, (segmentPath) => getDuration(segmentPath), { concurrency: 3 });
+ let timeAt = 0;
+ return durations.map((duration, i) => {
+ const ret = { start: timeAt, end: timeAt + duration, name: chapterNames[i] };
+ timeAt += duration;
+ return ret;
+ });
+ } catch (err) {
+ console.error('Failed to create chapters from segments', err);
+ return undefined;
}
- return undefined;
}
/**
diff --git a/src/fixtures/potplayer bookmark format utf16le issue 867.pbf b/src/fixtures/potplayer bookmark format utf16le issue 867.pbf
new file mode 100644
index 00000000..bca08c5e
Binary files /dev/null and b/src/fixtures/potplayer bookmark format utf16le issue 867.pbf differ
diff --git a/src/fixtures/test1.csv b/src/fixtures/test1.csv
new file mode 100644
index 00000000..6b41b9c7
--- /dev/null
+++ b/src/fixtures/test1.csv
@@ -0,0 +1,4 @@
+104.612,189.053,label 1
+300.448,476.194,label 2
+567.075,704.264,label 3
+704.264,855.455,label 4
diff --git a/src/fixtures/test1.pbf b/src/fixtures/test1.pbf
new file mode 100644
index 00000000..b7f2f455
Binary files /dev/null and b/src/fixtures/test1.pbf differ
diff --git a/src/fixtures/test2.csv b/src/fixtures/test2.csv
new file mode 100644
index 00000000..be3a8a3b
--- /dev/null
+++ b/src/fixtures/test2.csv
@@ -0,0 +1,6 @@
+104.612,189.053,label 1
+189.053,300.448,label 2
+300.448,476.194,label 3
+476.194,567.075,label 4
+567.075,704.264,label 5
+704.264,855.455,label 6
diff --git a/src/fixtures/test2.pbf b/src/fixtures/test2.pbf
new file mode 100644
index 00000000..6504d46b
Binary files /dev/null and b/src/fixtures/test2.pbf differ
diff --git a/src/fixtures/test3.csv b/src/fixtures/test3.csv
new file mode 100644
index 00000000..aa590193
--- /dev/null
+++ b/src/fixtures/test3.csv
@@ -0,0 +1,3 @@
+104.612,189.053,A
+300.448,476.194,B
+567.075,704.264,C
diff --git a/src/fixtures/test3.pbf b/src/fixtures/test3.pbf
new file mode 100644
index 00000000..7a1ea87b
Binary files /dev/null and b/src/fixtures/test3.pbf differ
diff --git a/src/hooks/useFfmpegOperations.js b/src/hooks/useFfmpegOperations.js
index 0049188f..67846c66 100644
--- a/src/hooks/useFfmpegOperations.js
+++ b/src/hooks/useFfmpegOperations.js
@@ -18,10 +18,9 @@ async function writeChaptersFfmetadata(outDir, chapters) {
const path = join(outDir, `ffmetadata-${new Date().getTime()}.txt`);
- const ffmetadata = chapters.map(({ start, end, name }, i) => {
- const nameOut = name || `Chapter ${i + 1}`;
- return `[CHAPTER]\nTIMEBASE=1/1000\nSTART=${Math.floor(start * 1000)}\nEND=${Math.floor(end * 1000)}\ntitle=${nameOut}`;
- }).join('\n\n');
+ const ffmetadata = chapters.map(({ start, end, name }) => (
+ `[CHAPTER]\nTIMEBASE=1/1000\nSTART=${Math.floor(start * 1000)}\nEND=${Math.floor(end * 1000)}\ntitle=${name || ''}`
+ )).join('\n\n');
console.log('Writing chapters', ffmetadata);
await fs.writeFile(path, ffmetadata);
return path;
@@ -68,7 +67,11 @@ function useFfmpegOperations({ filePath, enableTransferTimestamps }) {
const durations = await pMap(paths, getDuration, { concurrency: 1 });
const totalDuration = sum(durations);
- const chaptersPath = await writeChaptersFfmetadata(outDir, chapters);
+ let chaptersPath;
+ if (chapters) {
+ const chaptersWithNames = chapters.map((chapter, i) => ({ ...chapter, name: chapter.name || `Chapter ${i + 1}` }));
+ chaptersPath = await writeChaptersFfmetadata(outDir, chaptersWithNames);
+ }
try {
let inputArgs = [];
diff --git a/src/reporting.jsx b/src/reporting.jsx
index bf1f9e41..fae37bfc 100644
--- a/src/reporting.jsx
+++ b/src/reporting.jsx
@@ -16,7 +16,7 @@ const ReactSwal = withReactContent(Swal);
// eslint-disable-next-line import/prefer-default-export
export function openSendReportDialog(err, state) {
const reportInstructions = isStoreBuild
- ? <p><Trans>Please send an email to <span style={{ fontWeight: 'bold', cursor: 'pointer' }} role="button" onClick={() => electron.shell.openExternal('mailto:[email protected]')}>[email protected]</span> where you describe what you were doing.</Trans></p>
+ ? <p><Trans>Please send an email to <span style={{ fontWeight: 'bold', cursor: 'pointer' }} role="button" onClick={() => electron.shell.openExternal('mailto:[email protected]')}>[email protected]</span> where you describe what you were doing.</Trans></p>
: <p><Trans>Please create an issue at <span style={{ fontWeight: 'bold', cursor: 'pointer' }} role="button" onClick={() => electron.shell.openExternal('https://github.com/mifi/lossless-cut/issues')}>https://github.com/mifi/lossless-cut/issues</span> where you describe what you were doing.</Trans></p>;
const platform = os.platform();
diff --git a/src/segments.js b/src/segments.js
index 44df0842..b34a1845 100644
--- a/src/segments.js
+++ b/src/segments.js
@@ -41,23 +41,29 @@ export const getSegmentTags = (segment) => (segment.tags || {});
export const sortSegments = (segments) => sortBy(segments, 'start');
-export function invertSegments(sortedCutSegments, duration) {
- if (sortedCutSegments.length < 1) return undefined;
+export function hasAnySegmentOverlap(sortedSegments) {
+ if (sortedSegments.length < 1) return false;
- const foundOverlap = sortedCutSegments.some((cutSegment, i) => {
+ return sortedSegments.some((cutSegment, i) => {
if (i === 0) return false;
- return sortedCutSegments[i - 1].end > cutSegment.start;
+ return sortedSegments[i - 1].end > cutSegment.start;
});
+}
+
+export function invertSegments(sortedCutSegments, includeFirstSegment, includeLastSegment, duration) {
+ if (sortedCutSegments.length < 1) return undefined;
- if (foundOverlap) return undefined;
+ if (hasAnySegmentOverlap(sortedCutSegments)) return undefined;
const ret = [];
- if (sortedCutSegments[0].start > 0) {
- ret.push({
- start: 0,
- end: sortedCutSegments[0].start,
- });
+ if (includeFirstSegment) {
+ if (sortedCutSegments[0].start > 0) {
+ ret.push({
+ start: 0,
+ end: sortedCutSegments[0].start,
+ });
+ }
}
sortedCutSegments.forEach((cutSegment, i) => {
@@ -68,15 +74,29 @@ export function invertSegments(sortedCutSegments, duration) {
});
});
- const last = sortedCutSegments[sortedCutSegments.length - 1];
- if (last.end < duration || duration == null) {
- ret.push({
- start: last.end,
- end: duration,
- });
+ if (includeLastSegment) {
+ const last = sortedCutSegments[sortedCutSegments.length - 1];
+ if (last.end < duration || duration == null) {
+ ret.push({
+ start: last.end,
+ end: duration,
+ });
+ }
}
// Filter out zero length resulting segments
// https://github.com/mifi/lossless-cut/issues/909
return ret.filter(({ start, end }) => end == null || start == null || end > start);
}
+
+// because chapters need to be contiguous, we need to insert gaps in-between
+export function convertSegmentsToChapters(sortedSegments) {
+ if (sortedSegments.length < 1) return [];
+ if (hasAnySegmentOverlap(sortedSegments)) throw new Error('Segments cannot overlap');
+
+ sortedSegments.map((segment) => ({ start: segment.start, end: segment.end, name: segment.name }));
+ const invertedSegments = invertSegments(sortedSegments, true, false);
+
+ // inverted segments will be "gap" segments. Merge together with normal segments
+ return sortSegments([...sortedSegments, ...invertedSegments]);
+}
diff --git a/src/segments.test.js b/src/segments.test.js
new file mode 100644
index 00000000..fa52de75
--- /dev/null
+++ b/src/segments.test.js
@@ -0,0 +1,51 @@
+import { convertSegmentsToChapters } from './segments';
+
+it('converts segments to chapters with gaps', () => {
+ expect(convertSegmentsToChapters([
+ {
+ start: 104.612,
+ end: 189.053,
+ name: 'label 1',
+ },
+ {
+ start: 300.448,
+ end: 476.194,
+ name: 'label 2',
+ },
+ {
+ start: 567.075,
+ end: 704.264,
+ name: 'label 3',
+ },
+ {
+ start: 704.264,
+ end: 855.455,
+ name: 'label 4',
+ },
+ ])).toMatchSnapshot();
+});
+
+it('converts segments to chapters with no gaps', () => {
+ expect(convertSegmentsToChapters([
+ {
+ start: 0,
+ end: 2,
+ name: 'label 1',
+ },
+ {
+ start: 2,
+ end: 3,
+ name: 'label 2',
+ },
+ ])).toMatchSnapshot();
+});
+
+it('converts segments to chapters with single long segment', () => {
+ expect(convertSegmentsToChapters([
+ {
+ start: 0,
+ end: 1,
+ name: 'label 1',
+ },
+ ])).toMatchSnapshot();
+});