Skip to content

The swiss army knife of lossless video/audio editing

Fix wrong duration when cutting a file with cover art

Claudebd9ef59049e6
diff --git a/src/renderer/src/hooks/useFfmpegOperations.ts b/src/renderer/src/hooks/useFfmpegOperations.ts
index aab3f149..ea075026 100644
--- a/src/renderer/src/hooks/useFfmpegOperations.ts
+++ b/src/renderer/src/hooks/useFfmpegOperations.ts
@@ -6,7 +6,7 @@ import i18n from 'i18next';
import { getSuffixedOutPath, transferTimestamps, getOutFileExtension, getOutDir, getHtml5ifiedPath, unlinkWithRetry, getFrameDuration, isMac, html5ifiedPrefix, html5dummySuffix, assertFileExists } from '../util';
import { isCuttingStart, isCuttingEnd, runFfmpegWithProgress, getFfCommandLine, getDuration, createChaptersFromSegments, readFileFfprobeMeta, getExperimentalArgs, getVideoTimescaleArgs, logStdoutStderr, runFfmpegConcat, RefuseOverwriteError, runFfmpeg } from '../ffmpeg';
-import { getMapStreamsArgs, getStreamIdsToCopy } from '../util/streams';
+import { getEffectiveAvoidNegativeTs, getMapStreamsArgs, getStreamIdsToCopy } from '../util/streams';
import { needsSmartCut, getCodecParams } from '../smartcut';
import { getGuaranteedSegments, isDurationValid } from '../segments';
import type { FFprobeStream } from '../../../common/ffprobe';
@@ -297,7 +297,10 @@ function useFfmpegOperations({ filePath, treatInputFileModifiedTimeAsStart, trea
const copyFileStreamsFiltered = copyFileStreams.filter(({ streamIds }) => streamIds.length > 0);
// remove -avoid_negative_ts make_zero when not cutting start (no -ss), or else some videos get blank first frame in QuickLook
- const avoidNegativeTsArgs = cuttingStart && avoidNegativeTs && ssBeforeInput ? ['-avoid_negative_ts', String(avoidNegativeTs)] : [];
+ // note: `make_zero`/`make_non_negative` get downgraded to `auto` when copying a cover art stream, or else the
+ // output gets the segment's end time as its duration, see https://github.com/mifi/lossless-cut/issues/3009
+ const effectiveAvoidNegativeTs = getEffectiveAvoidNegativeTs({ avoidNegativeTs, allFilesMeta, copyFileStreams: copyFileStreamsFiltered });
+ const avoidNegativeTsArgs = cuttingStart && effectiveAvoidNegativeTs && ssBeforeInput ? ['-avoid_negative_ts', String(effectiveAvoidNegativeTs)] : [];
// If cutting multiple files, `-ss` must be before `-i`, regardless of `ssBeforeInput` choice
// and it seems that `-t` must be after `-i` #896
diff --git a/src/renderer/src/util/streams.test.ts b/src/renderer/src/util/streams.test.ts
index 4b7476b3..8ff92c76 100644
--- a/src/renderer/src/util/streams.test.ts
+++ b/src/renderer/src/util/streams.test.ts
@@ -1,6 +1,6 @@
import { test, expect } from 'vitest';
-import { getMapStreamsArgs, getStreamIdsToCopy } from './streams';
+import { getEffectiveAvoidNegativeTs, getMapStreamsArgs, getStreamIdsToCopy } from './streams';
import type { FFprobeStreamDisposition } from '../../../common/ffprobe';
import type { LiteFFprobeStream } from '../types';
@@ -164,3 +164,41 @@ test('ass output', () => {
'-map', '0:0', '-c:0', 'ass',
]);
});
+
+// stream 0 of `streams1` is an attached_pic (cover art) mjpeg stream
+// https://github.com/mifi/lossless-cut/issues/3009
+test('getEffectiveAvoidNegativeTs, downgrades to auto when copying cover art', () => {
+ expect(getEffectiveAvoidNegativeTs({
+ avoidNegativeTs: 'make_zero',
+ allFilesMeta,
+ copyFileStreams: [{ path, streamIds: [0, 1] }],
+ })).toBe('auto');
+
+ expect(getEffectiveAvoidNegativeTs({
+ avoidNegativeTs: 'make_non_negative',
+ allFilesMeta,
+ copyFileStreams: [{ path, streamIds: [0, 1] }],
+ })).toBe('auto');
+});
+
+test('getEffectiveAvoidNegativeTs, passes through when not copying cover art', () => {
+ expect(getEffectiveAvoidNegativeTs({
+ avoidNegativeTs: 'make_zero',
+ allFilesMeta,
+ copyFileStreams: [{ path, streamIds: [1, 2] }],
+ })).toBe('make_zero');
+
+ expect(getEffectiveAvoidNegativeTs({
+ avoidNegativeTs: 'make_non_negative',
+ allFilesMeta,
+ copyFileStreams: [{ path, streamIds: [1, 2] }],
+ })).toBe('make_non_negative');
+});
+
+test('getEffectiveAvoidNegativeTs, leaves other values alone', () => {
+ const copyFileStreams = [{ path, streamIds: [0, 1] }];
+
+ expect(getEffectiveAvoidNegativeTs({ avoidNegativeTs: 'auto', allFilesMeta, copyFileStreams })).toBe('auto');
+ expect(getEffectiveAvoidNegativeTs({ avoidNegativeTs: 'disabled', allFilesMeta, copyFileStreams })).toBe('disabled');
+ expect(getEffectiveAvoidNegativeTs({ avoidNegativeTs: undefined, allFilesMeta, copyFileStreams })).toBe(undefined);
+});
diff --git a/src/renderer/src/util/streams.ts b/src/renderer/src/util/streams.ts
index 8bdfae30..250e1d93 100644
--- a/src/renderer/src/util/streams.ts
+++ b/src/renderer/src/util/streams.ts
@@ -1,5 +1,6 @@
import invariant from 'tiny-invariant';
import type { FFprobeStream, FFprobeStreamDisposition } from '../../../common/ffprobe';
+import type { AvoidNegativeTs } from '../../../common/types';
import type { AllFilesMeta, ChromiumHTMLAudioElement, ChromiumHTMLVideoElement, CopyfileStreams, LiteFFprobeStream } from '../types';
import type { FileStream } from '../ffmpeg';
@@ -262,6 +263,37 @@ export function isStreamThumbnail(stream: Pick<FFprobeStream, 'codec_type' | 'di
return stream && stream.codec_type === 'video' && stream.disposition?.[attachedPicDisposition] === 1;
}
+function isCopyingThumbnailStream({ allFilesMeta, copyFileStreams }: {
+ allFilesMeta: AllFilesStreamMeta,
+ copyFileStreams: CopyfileStreams,
+}) {
+ return copyFileStreams.some(({ path, streamIds }) => streamIds.some((streamId) => {
+ const stream = getStreamById({ allFilesMeta, streamId, path });
+ return stream != null && isStreamThumbnail(stream);
+ }));
+}
+
+/**
+ * An attached_pic (cover art) packet has no position on the timeline - the demuxer emits it at
+ * pts 0. When seeking before the input (`-ss` before `-i`), ffmpeg applies the seek offset to it
+ * anyway, dragging it to -(cut from), and it reaches the muxer first. `make_zero` and
+ * `make_non_negative` then derive their file-wide correction from that packet and shift every
+ * other stream back by +(cut from), undoing the rebase to zero that the audio/video already got.
+ * The mov muxer records that as an empty edit, so the muxed duration ends up being the segment's
+ * end time in the source instead of its length (ffprobe hides this, but e.g. VLC reports it).
+ * `auto` doesn't use the attached pic as its reference, so it cuts correctly and keeps the cover art.
+ * See https://github.com/mifi/lossless-cut/issues/3009
+ */
+export function getEffectiveAvoidNegativeTs({ avoidNegativeTs, allFilesMeta, copyFileStreams }: {
+ avoidNegativeTs: AvoidNegativeTs | undefined,
+ allFilesMeta: AllFilesStreamMeta,
+ copyFileStreams: CopyfileStreams,
+}) {
+ if (avoidNegativeTs !== 'make_zero' && avoidNegativeTs !== 'make_non_negative') return avoidNegativeTs;
+ if (!isCopyingThumbnailStream({ allFilesMeta, copyFileStreams })) return avoidNegativeTs;
+ return 'auto';
+}
+
export const getAudioStreams = <T extends Pick<FFprobeStream, 'codec_type'>>(streams: T[]) => streams.filter((stream) => stream.codec_type === 'audio');
export const getRealVideoStreams = <T extends Pick<FFprobeStream, 'codec_type' | 'disposition'>>(streams: T[]) => streams.filter((stream) => stream.codec_type === 'video' && !isStreamThumbnail(stream));
export const getSubtitleStreams = <T extends Pick<FFprobeStream, 'codec_type'>>(streams: T[]) => streams.filter((stream) => stream.codec_type === 'subtitle');