Skip to content

armgit / Filee

Public Imported from GitHub
0

Free, open-source file converter. Convert 263 formats offline by drag & drop — images, PDF, Word, Excel, PowerPoint, HWP/HWPX, video, audio, e-books and archives. No upload, no Office needed.

Rewrap video instead of re-encoding when the container takes the codecs

KnifeLemon00c6bbf106b5
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 0ae78118..f4f7e03c 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -19,6 +19,10 @@ find it, what it does and doesn't do.
a 5-second still video at the photo's own size, with its colours (Display P3 photos stay P3) and transparent areas
in black. Only photos over about 36 megapixels (48 MP phone cameras) are scaled down, to the largest picture H.264
and VP9 players decode. Animated GIF/WebP and PDF pages still become a moving video or a slideshow.
+- **MOV ↔ MP4 without quality loss.** When the new format can hold the video and sound as they are, like an iPhone
+ video (HEVC or H.264 with AAC) going from MOV to MP4, Filee now only rewraps them instead of re-encoding: nothing
+ is lost, HDR and 10-bit colour stay, and it takes seconds. The same goes for MKV, WebM and TS. Choosing a smaller
+ size (e.g. 720p), another audio bitrate or quality **Small** still re-encodes.
- **Save images as HEIC** (with FFmpeg). Any image Filee reads → HEIC, the format iPhones take photos in: about a
quarter of a JPG's size at the same quality, stored in 512-pixel tiles like a phone photo, upright, with the colour
profile and Exif kept. The **HEIC** preset is on the Presets page (quality 80); add it to a donut to use it.
diff --git a/docs/ENGINES.md b/docs/ENGINES.md
index 62f2a378..da0fca5f 100644
--- a/docs/ENGINES.md
+++ b/docs/ENGINES.md
@@ -509,6 +509,15 @@ Same-format edges exist too, so "MP4 720p" works on MP4 files and "MP3 128k" on
| MP3 · M4A/M4B · AAC · OGG · OPUS · WEBA · MKA · WMA · MP2 · AC3 · AMR | LAME VBR (V0/V2/V5) or CBR · AAC · AAC (ADTS) · Vorbis · Opus · Opus · Opus · WMA 2 · MP2 · AC-3 · AMR-NB 12.2k (8 kHz mono) |
| WAV · AIFF · AU · CAF · VOC · FLAC | 16-bit PCM (WAV: 8/16/24/32-bit or 32-bit float; RF64 over 4 GB) · FLAC |
+- **Rewrapping instead of re-encoding.** When the target container takes the source's codecs as they are
+ (`MediaEncoding.Remuxable`: H.264/HEVC + AAC, ALAC, AC-3, E-AC-3 or MP3 for MP4/M4V/MOV, also ProRes and PCM for
+ MOV; H.264/HEVC/VP9/AV1 with most audio for MKV; VP8/VP9/AV1 + Opus/Vorbis for WebM; H.264/HEVC for TS/M2TS),
+ the streams are copied (`-c copy`). An iPhone MOV becomes an MP4 in seconds, frame for frame, with 10-bit HDR
+ (HLG, Dolby Vision's HLG base), rotation and colour tags kept. HEVC gets the `hvc1` tag Apple players need. Video
+ is copied only in a pixel format players decode (4:2:0, 8 or 10 bits; ProRes as it is) and when no scaling down
+ is needed; audio only when no bitrate or other channel count is set. Quality *Small* always re-encodes (the user
+ asked for a smaller file); *High* and *Balanced* only set how a stream that has to be encoded is encoded. A
+ stream that can't be copied is encoded as below, the other one is still copied.
- Preset options (`MediaOptions`): *Quality* picks CRF 18/23/28 (x264), 24/32/38 (VP9), quantizer 2/4/7 (MPEG-4,
WMV, MPEG-2), Theora 8/6/4 and the audio bitrates (e.g. AAC 256/192/128 kbit/s per stereo pair); *MaxHeight*
scales down only, keeps the aspect ratio and even sizes; *AudioBitrateKbps* overrides the audio bitrate (snapped to
diff --git a/src/Filee.App/Assets/i18n/en.json b/src/Filee.App/Assets/i18n/en.json
index 369eb794..b43af1aa 100644
--- a/src/Filee.App/Assets/i18n/en.json
+++ b/src/Filee.App/Assets/i18n/en.json
@@ -312,6 +312,7 @@
"presets.target_folder": "Folder (extract archives)",
"presets.group.media": "Video & audio",
"presets.media_quality": "Quality",
+ "presets.media_quality_hint": "A video whose codecs the new format takes as they are (an iPhone MOV → MP4) is only rewrapped: no quality lost, HDR kept, done in seconds. Small always re-encodes to make the file smaller.",
"presets.media_quality.High": "High (larger files)",
"presets.media_quality.Balanced": "Balanced",
"presets.media_quality.Small": "Small (for sharing)",
diff --git a/src/Filee.App/Assets/i18n/ko.json b/src/Filee.App/Assets/i18n/ko.json
index 2d5214ba..b1978127 100644
--- a/src/Filee.App/Assets/i18n/ko.json
+++ b/src/Filee.App/Assets/i18n/ko.json
@@ -312,6 +312,7 @@
"presets.target_folder": "폴더 (압축 풀기)",
"presets.group.media": "동영상·오디오",
"presets.media_quality": "품질",
+ "presets.media_quality_hint": "새 형식이 코덱을 그대로 담을 수 있는 동영상(아이폰 MOV → MP4 등)은 다시 인코딩하지 않고 포장만 바꿔요. 화질 손실 없이 HDR도 유지되고 몇 초면 끝나요. '작게'는 용량을 줄이려고 항상 다시 인코딩해요.",
"presets.media_quality.High": "높음 (큰 파일)",
"presets.media_quality.Balanced": "균형",
"presets.media_quality.Small": "작게 (공유용)",
diff --git a/src/Filee.App/Assets/i18n/zh-CN.json b/src/Filee.App/Assets/i18n/zh-CN.json
index a75c78f3..35b5cabc 100644
--- a/src/Filee.App/Assets/i18n/zh-CN.json
+++ b/src/Filee.App/Assets/i18n/zh-CN.json
@@ -312,6 +312,7 @@
"presets.target_folder": "文件夹(解压缩)",
"presets.group.media": "视频和音频",
"presets.media_quality": "质量",
+ "presets.media_quality_hint": "新格式能直接容纳其编码的视频(如 iPhone MOV → MP4)只会重新封装:画质无损、保留 HDR,几秒即可完成。“小”总会重新编码以减小文件。",
"presets.media_quality.High": "高(文件较大)",
"presets.media_quality.Balanced": "均衡",
"presets.media_quality.Small": "小(便于分享)",
diff --git a/src/Filee.App/Views/PresetEditorView.axaml b/src/Filee.App/Views/PresetEditorView.axaml
index 646a5840..d71e3516 100644
--- a/src/Filee.App/Views/PresetEditorView.axaml
+++ b/src/Filee.App/Views/PresetEditorView.axaml
@@ -99,7 +99,8 @@
<Grid ColumnDefinitions="*,12,*" IsVisible="{Binding ShowMediaQuality}">
<StackPanel>
<TextBlock Classes="label" Text="{DynamicResource presets.media_quality}" />
- <ComboBox ItemsSource="{Binding MediaQualities}" SelectedItem="{Binding MediaQuality}" HorizontalAlignment="Stretch" />
+ <ComboBox ItemsSource="{Binding MediaQualities}" SelectedItem="{Binding MediaQuality}" HorizontalAlignment="Stretch"
+ ToolTip.Tip="{DynamicResource presets.media_quality_hint}" />
</StackPanel>
<StackPanel Grid.Column="2" IsVisible="{Binding ShowMaxHeight}">
<TextBlock Classes="label" Text="{DynamicResource presets.max_height}" />
diff --git a/src/Filee.Engines/Media/MediaEncoding.cs b/src/Filee.Engines/Media/MediaEncoding.cs
index cc879a5d..96260289 100644
--- a/src/Filee.Engines/Media/MediaEncoding.cs
+++ b/src/Filee.Engines/Media/MediaEncoding.cs
@@ -144,12 +144,24 @@ internal static class MediaEncoding
if (audio is not null)
args.AddRange(["-map", "0:a:0"]);
- var pal = IsPal(video.FrameRate);
- args.AddRange(["-vf", target is "vob" or "dv" ? DvdOrDvFilter(video, pal) : ScaleFilter(options.MaxHeight)]);
- args.AddRange(VideoCodecArguments(target, spec.VideoCodec!, options.Quality, video, pal));
+ if (CanCopyVideo(target, video, options))
+ {
+ args.AddRange(["-c:v", "copy"]);
+ // Apple plays HEVC in MP4/MOV only under the "hvc1" tag (FFmpeg keeps "hev1" from some sources).
+ if (video.Codec == "hevc" && target is "mp4" or "m4v" or "mov")
+ args.AddRange(["-tag:v", "hvc1"]);
+ }
+ else
+ {
+ var pal = IsPal(video.FrameRate);
+ args.AddRange(["-vf", target is "vob" or "dv" ? DvdOrDvFilter(video, pal) : ScaleFilter(options.MaxHeight)]);
+ args.AddRange(VideoCodecArguments(target, spec.VideoCodec!, options.Quality, video, pal));
+ }
if (audio is null)
args.Add("-an");
+ else if (CanCopyAudio(target, audio, options))
+ args.AddRange(["-c:a", "copy"]);
else
args.AddRange(AudioCodecArguments(target, spec.AudioCodec, options, audio, inVideo: true));
@@ -160,6 +172,46 @@ internal static class MediaEncoding
return args;
}
+ /// <summary>
+ /// Codecs a container takes as they are. A video whose streams are listed for the target is only rewrapped
+ /// (stream copy): no quality loss, HDR and 10-bit kept, seconds instead of minutes. iPhone videos (HEVC or H.264
+ /// with AAC in MOV) become MP4 this way. Only codecs the target's usual players handle are listed: MP4/MOV keep to
+ /// what Apple devices and browsers play, WebM to what the WebM specification allows.
+ /// </summary>
+ private static readonly Dictionary<string, (HashSet<string> Video, HashSet<string> Audio)> Remuxable = new()
+ {
+ ["mp4"] = (["h264", "hevc"], ["aac", "alac", "ac3", "eac3", "mp3"]),
+ ["m4v"] = (["h264", "hevc"], ["aac", "alac", "ac3", "eac3", "mp3"]),
+ ["mov"] = (["h264", "hevc", "prores"], ["aac", "alac", "ac3", "eac3", "mp3", "pcm_s16le", "pcm_s24le"]),
+ ["mkv"] = (["h264", "hevc", "vp9", "av1"], ["aac", "alac", "ac3", "eac3", "mp3", "opus", "vorbis", "flac"]),
+ ["webm"] = (["vp8", "vp9", "av1"], ["opus", "vorbis"]),
+ ["ts"] = (["h264", "hevc"], ["aac", "ac3", "eac3", "mp3"]),
+ ["m2ts"] = (["h264", "hevc"], ["aac", "ac3", "eac3"]),
+ };
+
+ /// <summary>Pixel formats players decode in hardware: 4:2:0 at 8 or 10 bits (phones record HDR video as 10-bit).</summary>
+ private static readonly HashSet<string> PlayablePixelFormats = ["yuv420p", "yuvj420p", "yuv420p10le"];
+
+ /// <summary>
+ /// True when the video stream can be copied: the target container takes its codec in a pixel format players
+ /// decode, it needs no scaling down, and the preset does not ask for a small file (Small always re-encodes; High
+ /// and Balanced only describe how a video that has to be encoded anyway is encoded).
+ /// </summary>
+ internal static bool CanCopyVideo(string target, VideoStreamInfo video, MediaOptions options) =>
+ options.Quality != MediaQuality.Small
+ && Remuxable.TryGetValue(target, out var codecs) && video.Codec is { } codec && codecs.Video.Contains(codec)
+ && (codec == "prores" || video.PixelFormat is { } format && PlayablePixelFormats.Contains(format))
+ && !(options.MaxHeight > 0 && video.DisplayHeight > Math.Max(16, options.MaxHeight));
+
+ /// <summary>
+ /// True when the audio stream can be copied: the container takes it, no bitrate is set and the channels stay
+ /// as they are.
+ /// </summary>
+ internal static bool CanCopyAudio(string target, AudioStreamInfo audio, MediaOptions options) =>
+ options.Quality != MediaQuality.Small && options.AudioBitrateKbps <= 0
+ && (options.AudioChannels is not (1 or 2) || options.AudioChannels == audio.Channels)
+ && Remuxable.TryGetValue(target, out var codecs) && audio.Codec is { } codec && codecs.Audio.Contains(codec);
+
/// <summary>
/// Scales down to <paramref name="maxHeight"/> (never up) keeping the aspect ratio, and makes both sides even,
/// which 4:2:0 encoders require (an odd-sized GIF or phone video would otherwise fail).
diff --git a/src/Filee.Engines/Media/MediaInfo.cs b/src/Filee.Engines/Media/MediaInfo.cs
index 6472d02b..b482b8bf 100644
--- a/src/Filee.Engines/Media/MediaInfo.cs
+++ b/src/Filee.Engines/Media/MediaInfo.cs
@@ -13,11 +13,17 @@ namespace Filee.Engines.Media;
/// <param name="SampleAspect">Pixel aspect ratio (1 for square pixels, 8/9 for NTSC DV 4:3, ...).</param>
/// <param name="Rotation">Display rotation in degrees from the display matrix (phones record portrait video this way).</param>
/// <param name="FrameRate">Average frames per second, 0 when unknown.</param>
-internal sealed record VideoStreamInfo(int Width, int Height, double SampleAspect, int Rotation, double FrameRate)
+/// <param name="Codec">FFmpeg's codec name (<c>h264</c>, <c>hevc</c>, …), null when unknown.</param>
+/// <param name="PixelFormat">FFmpeg's pixel format (<c>yuv420p</c>, <c>yuv420p10le</c>, …), null when unknown.</param>
+internal sealed record VideoStreamInfo(int Width, int Height, double SampleAspect, int Rotation, double FrameRate,
+ string? Codec = null, string? PixelFormat = null)
{
/// <summary>True when the picture is shown turned by 90° (FFmpeg rotates it upright while decoding).</summary>
public bool IsRotated => Math.Abs(Rotation % 180) == 90;
+ /// <summary>Height of the picture as it is displayed (the width for portrait phone videos).</summary>
+ public int DisplayHeight => IsRotated ? Width : Height;
+
/// <summary>Width ÷ height as the picture is displayed: pixel aspect and rotation applied.</summary>
public double DisplayAspect
{
@@ -32,7 +38,8 @@ internal sealed record VideoStreamInfo(int Width, int Height, double SampleAspec
}
/// <summary>The first audio stream of a file.</summary>
-internal sealed record AudioStreamInfo(int Channels, int SampleRate);
+/// <param name="Codec">FFmpeg's codec name (<c>aac</c>, <c>opus</c>, …), null when unknown.</param>
+internal sealed record AudioStreamInfo(int Channels, int SampleRate, string? Codec = null);
/// <summary>Summary of a media file.</summary>
/// <param name="Duration">Playing time, null when the container does not say (raw streams).</param>
@@ -85,10 +92,13 @@ internal sealed record MediaInfo(TimeSpan? Duration, VideoStreamInfo? Video, Aud
(int)Number(stream, "height"),
Ratio(Text(stream, "sample_aspect_ratio"), ':') is var sar and > 0 ? sar : 1,
RotationOf(stream),
- FrameRateOf(stream));
+ FrameRateOf(stream),
+ Text(stream, "codec_name"),
+ Text(stream, "pix_fmt"));
break;
case "audio" when audio is null:
- audio = new AudioStreamInfo((int)Number(stream, "channels"), (int)Number(stream, "sample_rate"));
+ audio = new AudioStreamInfo((int)Number(stream, "channels"), (int)Number(stream, "sample_rate"),
+ Text(stream, "codec_name"));
break;
}
}
diff --git a/tests/Filee.Engines.Tests/MediaTests.cs b/tests/Filee.Engines.Tests/MediaTests.cs
index 06fa6f0b..d836d40a 100644
--- a/tests/Filee.Engines.Tests/MediaTests.cs
+++ b/tests/Filee.Engines.Tests/MediaTests.cs
@@ -180,6 +180,38 @@ public class MediaTests(EngineFixture fx) : IClassFixture<EngineFixture>
Assert.All(amr.Where((_, i) => i > 0 && amr[i - 1] == "-ac"), channels => Assert.Equal("1", channels));
}
+ [Fact]
+ public void Streams_the_target_takes_as_they_are_are_copied()
+ {
+ var phone = new MediaInfo(TimeSpan.FromSeconds(10), new VideoStreamInfo(1920, 1080, 1, -90, 30, "hevc", "yuv420p10le"),
+ new AudioStreamInfo(2, 44100, "aac"), null);
+ var mp4 = Args("mp4", info: phone);
+ Assert.Equal("copy", After(mp4, "-c:v"));
+ Assert.Equal("hvc1", After(mp4, "-tag:v")); // Apple plays HEVC in MP4 only under this tag
+ Assert.Equal("copy", After(mp4, "-c:a"));
+ Assert.DoesNotContain("-vf", mp4);
+ Assert.Equal("+faststart", After(mp4, "-movflags"));
+
+ // WebM takes neither HEVC nor AAC.
+ var webm = Args("webm", info: phone);
+ Assert.Equal(("libvpx-vp9", "libopus"), (After(webm, "-c:v"), After(webm, "-c:a")));
+
+ // Re-encoded: scaled down (the portrait video is 1920 high as shown), a small file asked for, a pixel format
+ // players don't decode.
+ Assert.Equal("libx264", After(Args("mp4", new MediaOptions { MaxHeight = 1080 }, phone), "-c:v"));
+ Assert.Equal("copy", After(Args("mp4", new MediaOptions { MaxHeight = 2160 }, phone), "-c:v"));
+ Assert.Equal("libx264", After(Args("mp4", new MediaOptions { Quality = MediaQuality.Small }, phone), "-c:v"));
+ var yuv444 = phone with { Video = phone.Video! with { Codec = "h264", PixelFormat = "yuv444p" } };
+ Assert.Equal("libx264", After(Args("mp4", info: yuv444), "-c:v"));
+
+ // Audio alone is re-encoded when the container does not take it or the preset sets bitrate or channels.
+ var pcm = phone with { Audio = new AudioStreamInfo(2, 48000, "pcm_s16le") };
+ Assert.Equal(("copy", "aac"), (After(Args("mp4", info: pcm), "-c:v"), After(Args("mp4", info: pcm), "-c:a")));
+ Assert.Equal("aac", After(Args("mov", new MediaOptions { AudioBitrateKbps = 128 }, phone), "-c:a"));
+ Assert.Equal("aac", After(Args("mov", new MediaOptions { AudioChannels = 1 }, phone), "-c:a"));
+ Assert.Equal("copy", After(Args("mov", new MediaOptions { AudioChannels = 2 }, phone), "-c:a"));
+ }
+
[Fact]
public void Dvd_and_dv_frames_are_letterboxed_into_the_nearest_tv_shape()
{
@@ -289,9 +321,10 @@ public class MediaTests(EngineFixture fx) : IClassFixture<EngineFixture>
""";
var info = MediaInfo.Parse(json);
Assert.Equal(12.48, info.Duration!.Value.TotalSeconds, 3);
- Assert.Equal(new VideoStreamInfo(1920, 1080, 1, -90, 30000 / 1001.0), info.Video);
+ Assert.Equal(new VideoStreamInfo(1920, 1080, 1, -90, 30000 / 1001.0, "h264"), info.Video);
Assert.Equal(9 / 16.0, info.Video!.DisplayAspect, 3);
- Assert.Equal(new AudioStreamInfo(2, 48000), info.Audio);
+ Assert.Equal(1920, info.Video.DisplayHeight);
+ Assert.Equal(new AudioStreamInfo(2, 48000, "aac"), info.Audio);
Assert.Equal(2, info.CoverStreamIndex);
var raw = MediaInfo.Parse("""{ "streams": [ { "index": 0, "codec_type": "audio", "channels": 1, "sample_rate": "8000" } ], "format": {} }""");
@@ -448,6 +481,42 @@ public class MediaTests(EngineFixture fx) : IClassFixture<EngineFixture>
Assert.Empty(failures);
}
+ [Fact]
+ public async Task An_iphone_hdr_mov_is_rewrapped_into_mp4_without_re_encoding()
+ {
+ SkipUnlessInstalled();
+ var folder = fx.NewFolder();
+ // Like an iPhone video: HEVC Main 10 with HLG (BT.2020) in MOV, recorded sideways with a display matrix, AAC sound.
+ var hevc = await MakeClipAsync(folder, "hevc.mov", seconds: 2, size: "640x360",
+ extra: ["-c:v", "libx265", "-pix_fmt", "yuv420p10le",
+ "-x265-params", "colorprim=bt2020:transfer=arib-std-b67:colormatrix=bt2020nc:log-level=error", "-c:a", "aac"]);
+ var phone = Path.Combine(folder, "phone.mov");
+ await RunAsync(Tools!.Value.Ffmpeg, ["-hide_banner", "-nostdin", "-v", "error", "-y", "-display_rotation", "90", "-i", hevc, "-c", "copy", phone]);
+
+ var mp4 = await ConvertAsync(phone, "mp4");
+ var result = await ProcessRunner.RunAsync(Tools.Value.Ffprobe,
+ ["-v", "error", "-show_entries", "stream=codec_type,codec_name,codec_tag_string,pix_fmt,color_transfer,nb_frames:stream_side_data=rotation",
+ "-of", "json", mp4], TimeSpan.FromMinutes(1), CancellationToken.None);
+ using var json = JsonDocument.Parse(result.StandardOutput);
+ var video = json.RootElement.GetProperty("streams").EnumerateArray().Single(s => s.GetProperty("codec_type").GetString() == "video");
+ Assert.Equal("hevc", video.GetProperty("codec_name").GetString());
+ Assert.Equal("hvc1", video.GetProperty("codec_tag_string").GetString());
+ Assert.Equal("yuv420p10le", video.GetProperty("pix_fmt").GetString()); // 10-bit HDR kept
+ Assert.Equal("arib-std-b67", video.GetProperty("color_transfer").GetString());
+ Assert.Contains("rotation", video.GetProperty("side_data_list").ToString()); // still shown upright
+ Assert.Equal("50", video.GetProperty("nb_frames").GetString()); // every frame, none re-encoded or dropped
+
+ // The coded pictures are the source's, byte for byte.
+ async Task<string> Hash(string file)
+ {
+ var hash = await ProcessRunner.RunAsync(Tools.Value.Ffmpeg,
+ ["-hide_banner", "-v", "error", "-i", file, "-map", "0:v", "-c", "copy", "-f", "hash", "-hash", "md5", "-"],
+ TimeSpan.FromMinutes(1), CancellationToken.None);
+ return hash.StandardOutput.Trim();
+ }
+ Assert.Equal(await Hash(phone), await Hash(mp4));
+ }
+
[Fact]
public async Task Video_becomes_an_animated_gif_and_back()
{
@@ -705,7 +774,8 @@ public class MediaTests(EngineFixture fx) : IClassFixture<EngineFixture>
Assert.True(converter.GetStatus().IsAvailable);
var recorder = new Recorder();
- var outputs = await converter.ConvertAsync(Step(source, "mp4", "mkv", folder, new MediaOptions { Quality = MediaQuality.High }), recorder, CancellationToken.None);
+ // Small: H.264 + AAC in MKV would otherwise only be rewrapped, which takes too little time to report progress.
+ var outputs = await converter.ConvertAsync(Step(source, "mp4", "mkv", folder, new MediaOptions { Quality = MediaQuality.Small }), recorder, CancellationToken.None);
Assert.True(File.Exists(Assert.Single(outputs)));
var values = recorder.Values.ToList();