Skip to content

Commit bb2434c

Browse files
committed
Merge branch '4k-hdr' into 'main'
4K transcodes and HDR tone mapping See merge request techidiots-llc/mediariffle!8
2 parents d45ac15 + 25921ce commit bb2434c

11 files changed

Lines changed: 233 additions & 19 deletions

File tree

‎CHANGELOG.md‎

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,12 @@
1111
every 12 hours. An admin without one is walked through setting it up the first time they open Admin, ending with ten
1212
one-time recovery codes. Manage passkeys, the authenticator and recovery codes under Profile; another admin can reset
1313
someone's under Admin → Users. Signing in itself is unchanged. See docs/configuration.md.
14+
- **4K transcodes**: a 2160p level (H.264 at about 25 Mbit/s) for Auto and the quality menu, when the server allows it
15+
(`Transcoding:MaxHeight` 2160, `MaxVideoKbps` about 30000; best with a hardware encoder). For browsers that can't
16+
play a 4K file's HEVC as it is, and 4K Chromecasts. The quality menu now lists only the levels a file can have.
17+
- **HDR tone mapping**: HDR video (HDR10, HLG) converted to H.264 is tone-mapped to ordinary colours instead of
18+
looking washed out. Needs ffmpeg's zscale filter, which most builds have (the log says if not);
19+
`Transcoding:ToneMapHdr` turns it off. See docs/configuration.md.
1420

1521
### 🐞 Bug fixes
1622
- **A show's other series are told apart**: season folders named for another series of the show (`UK - Season 01`,

‎docs/configuration.md‎

Lines changed: 30 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -26,6 +26,7 @@ Put your settings in file 2. A complete example:
2626
"Encoder": "Libx264",
2727
"VaapiDevice": "/dev/dri/renderD128",
2828
"MaxHeight": 1080,
29+
"ToneMapHdr": true,
2930
"MaxVideoKbps": 8000,
3031
"MaxSessions": 4,
3132
"MaxSessionsPerUser": 2,
@@ -53,8 +54,9 @@ Put your settings in file 2. A complete example:
5354
| `AdminMfa.Hours` | How long a check lasts before Admin asks again. |
5455
| `Transcoding.FfmpegFolder` | Folder holding `ffmpeg` and `ffprobe`; empty to use `PATH`. |
5556
| `Transcoding.Encoder` | `Libx264` (CPU), `Nvenc` (NVIDIA), `Qsv` (Intel Quick Sync), `Vaapi` (Intel/AMD on Linux). |
56-
| `Transcoding.MaxHeight` | Transcodes are scaled down to this many lines. |
57-
| `Transcoding.MaxVideoKbps` | Peak video bitrate of a transcode. |
57+
| `Transcoding.MaxHeight` | Transcodes are scaled down to this many lines. `2160` allows 4K transcodes (see Quality below); 1080 by default. |
58+
| `Transcoding.MaxVideoKbps` | Peak video bitrate of a transcode. Raise it to about `30000` with `MaxHeight` 2160, or the 4K level is held to this. |
59+
| `Transcoding.ToneMapHdr` | HDR video (HDR10, HLG) that has to be converted is tone-mapped to ordinary colours, so it isn't washed out (see Quality below). `true` by default. |
5860
| `Transcoding.MaxSessions` | Remuxes and transcodes running at once, all users together. Direct play doesn't count. |
5961
| `Transcoding.MaxSessionsPerUser` | A user starting more stops their oldest. |
6062
| `Transcoding.SegmentSeconds` | Length of a stream segment. Shorter switches level and starts sooner; longer is a little more efficient. |
@@ -136,7 +138,9 @@ never touched) and everyone's place in it.
136138

137139
## Quality
138140

139-
The player has a quality menu: **Auto**, **Original**, and 1080p (8 Mbit/s), 720p (4), 480p (1.5), 360p (0.8).
141+
The player has a quality menu: **Auto**, **Original**, and 2160p (4K, 25 Mbit/s, when allowed), 1080p (8), 720p (4),
142+
480p (1.5), 360p (0.8). The menu lists only what a file can have here: nothing above the server's `MaxHeight`, the
143+
user's cap, or (by more than a step) the picture itself.
140144

141145
- **Auto** is an adaptive stream, as on streaming sites: a playlist offering every level (none above the picture's
142146
own size, the server's `MaxHeight` or the user's cap), from which the player picks a level segment by segment by
@@ -160,6 +164,29 @@ it's needed again. Seeking in a transcode never restarts the whole stream.
160164
Admins can cap a user's quality (**Admin → Users → Best quality**), e.g. 720p for someone streaming over a slow
161165
connection, so one viewer can't use all of the server's upload. A capped user doesn't get Original.
162166

167+
### 4K
168+
169+
A 4K file plays at 4K as it is (Original, or Auto with the connection to spare) on a device that decodes its video:
170+
HEVC on Safari and on Chrome/Edge with a hardware HEVC decoder, H.264 everywhere. A converted stream stops at 1080p
171+
unless the server allows 4K:
172+
173+
```json
174+
"Transcoding": { "Encoder": "Nvenc", "MaxHeight": 2160, "MaxVideoKbps": 30000 }
175+
```
176+
177+
That adds a 2160p level (H.264 at about 25 Mbit/s) to Auto and the menu, for browsers that can't decode HEVC
178+
(Firefox) and for 4K Chromecasts. Use a hardware encoder (`Nvenc`, `Qsv` or `Vaapi`): `Libx264` on the CPU can't
179+
make 4K in real time on most machines.
180+
181+
### HDR
182+
183+
HDR video (HDR10, HDR10+, HLG, and Dolby Vision's HDR10 base layer) sent as it is is the browser's to show, and
184+
browsers handle it themselves (on an HDR screen, or tone-mapped on an ordinary one). Converted to H.264, it's
185+
**tone-mapped** to ordinary (SDR, BT.709) colours first, so it isn't washed out and grey, as it would be with HDR's
186+
picture simply relabelled. That's done on the CPU with ffmpeg's `zscale` (libzimg) and `tonemap` filters, after
187+
scaling down, whatever the encoder; the log says at start if this ffmpeg lacks them (the builds linked from
188+
ffmpeg.org and most Linux packages have them). It takes CPU time, most at 4K; `"ToneMapHdr": false` turns it off.
189+
163190
## Library layout
164191

165192
```

‎src/MediaRiffle.Server/Api/LibraryEndpoints.cs‎

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -150,7 +150,7 @@ public static void MapLibraryEndpoints(this WebApplication app)
150150
});
151151
});
152152

153-
g.MapGet("/files/{id:int}", async (int id, ClaimsPrincipal me, UserManager<AppUser> users, AppDbContext db, LibraryFiles files) =>
153+
g.MapGet("/files/{id:int}", async (int id, ClaimsPrincipal me, UserManager<AppUser> users, AppDbContext db, LibraryFiles files, IOptions<MediaRiffleOptions> options) =>
154154
{
155155
var f = await db.MediaFiles.FirstOrDefaultAsync(x => x.Id == id);
156156
if (f is null) return Results.NotFound();
@@ -170,7 +170,8 @@ public static void MapLibraryEndpoints(this WebApplication app)
170170
bitrateKbps = probe.BitRateKbps,
171171
// The qualities this user may pick, best first; Original only without a cap
172172
qualities = (cap is null ? new[] { new { id = Quality.Original, label = "Original", kbps = probe.BitRateKbps } } : [])
173-
.Concat(Quality.Ladder.Where(l => cap is null || l.Height <= cap.Height)
173+
// The levels this file can have here: within the server's maximum and the user's cap, none (much) bigger than the picture
174+
.Concat(Quality.AdaptiveLevels(f.Height, options.Value.Transcoding.MaxHeight, cap?.Id)
174175
.Select(l => new { id = l.Id, label = $"{l.Label} ({l.TotalKbps / 1000.0:0.#} Mbit/s)", kbps = l.TotalKbps })),
175176
audio = probe.Audio.Select(a => new { a.Index, a.Label, a.IsDefault }),
176177
subtitles = probe.Subtitles.Select(s => new { id = $"s{s.Index}", s.Label, text = s.IsTextSubtitle })

‎src/MediaRiffle.Server/Api/PlaybackEndpoints.cs‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -106,6 +106,10 @@ public static void MapPlaybackEndpoints(this WebApplication app)
106106
};
107107
}
108108

109+
// HDR video that's converted is tone-mapped to ordinary colours (when this ffmpeg can)
110+
if (plan.Mode == PlaybackMode.Transcode && plan.Video is { IsHdr: true } && ffmpeg.CanToneMap)
111+
plan = plan with { ToneMap = true, Reason = plan.Reason + "; HDR tone-mapped" };
112+
109113
var start = req.Start;
110114
if (start is null)
111115
{

‎src/MediaRiffle.Server/Media/Ffmpeg.cs‎

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -140,6 +140,31 @@ public async Task<bool> CheckAsync()
140140
return false;
141141
}
142142
}
143+
await CheckToneMappingAsync();
143144
return true;
144145
}
146+
147+
/// <summary>
148+
/// This ffmpeg can tone-map HDR to SDR (it has zscale, from libzimg, and tonemap) and it's turned on
149+
/// (Transcoding:ToneMapHdr). Found out at start, by <see cref="CheckAsync"/>.
150+
/// </summary>
151+
public bool CanToneMap { get; private set; }
152+
153+
private async Task CheckToneMappingAsync()
154+
{
155+
if (!options.Value.Transcoding.ToneMapHdr) return;
156+
try
157+
{
158+
var filters = Encoding.UTF8.GetString(await RunAsync(FfmpegPath, ["-hide_banner", "-filters"], TimeSpan.FromSeconds(10)));
159+
CanToneMap = HasFilter(filters, "zscale") && HasFilter(filters, "tonemap");
160+
if (!CanToneMap)
161+
log.LogWarning("This ffmpeg has no zscale filter (libzimg), so HDR video converted for a browser will look washed out. " +
162+
"Builds from ffmpeg.org's links (BtbN, gyan.dev) and most Linux packages have it.");
163+
}
164+
catch (Exception ex) { log.LogWarning("Couldn't list ffmpeg's filters: {Error}", ex.Message); }
165+
}
166+
167+
/// <summary>Whether ffmpeg's <c>-filters</c> list has this filter (a line like " ..C zscale V->V Apply resizing…").</summary>
168+
public static bool HasFilter(string filterList, string name) =>
169+
filterList.Split('\n').Any(line => line.Split(' ', StringSplitOptions.RemoveEmptyEntries) is { Length: >= 2 } p && p[1] == name);
145170
}

‎src/MediaRiffle.Server/Media/PlaybackPlanner.cs‎

Lines changed: 41 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -31,10 +31,15 @@ public enum SegmentFormat
3131
/// Set for an adaptive transcode: the levels of its master playlist, best first, each a full-length playlist whose
3232
/// segments are made when asked for (see <see cref="PlaybackPlanner.SegmentArguments"/>). Null for a single stream.
3333
/// </param>
34+
/// <param name="ToneMap">
35+
/// Transcoded HDR video is tone-mapped to SDR (BT.709) first, so it isn't washed out; set when the video is HDR and
36+
/// the server's ffmpeg can (see <see cref="Ffmpeg.CanToneMap"/>).
37+
/// </param>
3438
public sealed record PlaybackPlan(
3539
PlaybackMode Mode, ProbeStream? Video, ProbeStream? Audio, ProbeStream? BurnSubtitle, string Reason,
3640
string Quality = Media.Quality.Original, int TargetHeight = 1080, int TargetVideoKbps = 8000, int AudioKbps = 192,
37-
SegmentFormat Segments = SegmentFormat.Ts, int StreamKbps = 0, IReadOnlyList<QualityLevel>? Levels = null)
41+
SegmentFormat Segments = SegmentFormat.Ts, int StreamKbps = 0, IReadOnlyList<QualityLevel>? Levels = null,
42+
bool ToneMap = false)
3843
{
3944
public bool IsAdaptive => Levels is { Count: > 0 };
4045
}
@@ -132,7 +137,7 @@ public static List<string> HlsArguments(PlaybackPlan plan, string input, double
132137
}
133138
else
134139
{
135-
a.AddRange(VideoTranscode(v, plan.BurnSubtitle, plan.TargetHeight, plan.TargetVideoKbps, o, fixedKeyframes: false));
140+
a.AddRange(VideoTranscode(v, plan.BurnSubtitle, plan.TargetHeight, plan.TargetVideoKbps, o, fixedKeyframes: false, plan.ToneMap));
136141
}
137142
}
138143

@@ -168,41 +173,66 @@ public static List<string> HlsArguments(PlaybackPlan plan, string input, double
168173
/// <paramref name="kbps"/>, with an image subtitle burned in when given. A keyframe at every segment boundary, so
169174
/// each segment starts cleanly (<paramref name="fixedKeyframes"/>: for an adaptive stream, where it must).
170175
/// </summary>
171-
private static List<string> VideoTranscode(ProbeStream v, ProbeStream? burn, int targetHeight, int kbps, TranscodingOptions o, bool fixedKeyframes)
176+
private static List<string> VideoTranscode(ProbeStream v, ProbeStream? burn, int targetHeight, int kbps, TranscodingOptions o,
177+
bool fixedKeyframes, bool toneMap = false)
172178
{
173179
var a = new List<string>();
174180
int height = Math.Min(targetHeight, o.MaxHeight);
175181
bool scale = v.Height > height;
182+
// HDR is scaled down first (less to tone-map), then tone-mapped on the CPU, whatever the encoder
183+
var hdr = toneMap && v.IsHdr ? (scale ? $"scale=-2:{height}," : "") + ToneMapFilter(v) + "," : null;
176184
var chain = o.Encoder switch
177185
{
178186
// VA-API scales on the GPU, after the frames are uploaded to it
179-
VideoEncoder.Vaapi => "format=nv12,hwupload" + (scale ? $",scale_vaapi=w=-2:h={height}" : ""),
180-
VideoEncoder.Qsv => (scale ? $"scale=-2:{height}," : "") + "format=nv12",
181-
_ => (scale ? $"scale=-2:{height}," : "") + "format=yuv420p",
187+
VideoEncoder.Vaapi => hdr is not null ? hdr + "format=nv12,hwupload"
188+
: "format=nv12,hwupload" + (scale ? $",scale_vaapi=w=-2:h={height}" : ""),
189+
VideoEncoder.Qsv => (hdr ?? (scale ? $"scale=-2:{height}," : "")) + "format=nv12",
190+
_ => (hdr ?? (scale ? $"scale=-2:{height}," : "")) + "format=yuv420p",
182191
};
183192
if (burn is { } s) a.AddRange(["-filter_complex", $"[0:{v.Index}][0:{s.Index}]overlay,{chain}[v]", "-map", "[v]"]);
184193
else a.AddRange(["-map", $"0:{v.Index}", "-vf", chain]);
185-
a.AddRange(EncoderArguments(o, Math.Min(kbps, o.MaxVideoKbps)));
194+
a.AddRange(EncoderArguments(o, Math.Min(kbps, o.MaxVideoKbps), Math.Min(height, v.Height > 0 ? v.Height : height)));
195+
// Tone-mapped (or ordinary) output is BT.709: say so, or players may take it for the source's BT.2020
196+
if (hdr is not null) a.AddRange(["-color_primaries", "bt709", "-color_trc", "bt709", "-colorspace", "bt709"]);
186197
// A player switching level starts a segment with no picture before it: NVENC's forced keyframes must be IDR
187198
if (fixedKeyframes && o.Encoder == VideoEncoder.Nvenc) a.AddRange(["-forced-idr", "1"]);
188199
// t counts from the first frame of this run, which starts on a segment boundary
189200
a.AddRange(["-force_key_frames", $"expr:gte(t,n_forced*{o.SegmentSeconds})"]);
190201
return a;
191202
}
192203

193-
private static IEnumerable<string> EncoderArguments(TranscodingOptions o, int kbps)
204+
private static IEnumerable<string> EncoderArguments(TranscodingOptions o, int kbps, int height)
194205
{
195206
var max = $"{kbps}k";
196207
var buf = $"{kbps * 2}k";
208+
var level = H264Level(height);
197209
return o.Encoder switch
198210
{
199211
VideoEncoder.Nvenc => ["-c:v", "h264_nvenc", "-preset", "p4", "-rc", "vbr", "-cq", "23", "-maxrate", max, "-bufsize", buf, "-profile:v", "high"],
200212
VideoEncoder.Qsv => ["-c:v", "h264_qsv", "-preset", "veryfast", "-global_quality", "23", "-maxrate", max, "-bufsize", buf, "-profile:v", "high"],
201213
VideoEncoder.Vaapi => ["-c:v", "h264_vaapi", "-rc_mode", "VBR", "-b:v", $"{kbps * 3 / 4}k", "-maxrate", max, "-bufsize", buf, "-profile:v", "high"],
202-
_ => ["-c:v", "libx264", "-preset", "veryfast", "-crf", "23", "-maxrate", max, "-bufsize", buf, "-profile:v", "high", "-level:v", "4.1"],
214+
_ => ["-c:v", "libx264", "-preset", "veryfast", "-crf", "23", "-maxrate", max, "-bufsize", buf, "-profile:v", "high", "-level:v", level],
203215
};
204216
}
205217

218+
/// <summary>The H.264 level a picture this tall needs: 4.1 up to 1080p, 5.1 for 4K.</summary>
219+
public static string H264Level(int height) => height > 1088 ? "5.1" : "4.1";
220+
221+
/// <summary>The CODECS of an H.264 High profile stream this tall (with AAC), for a master playlist.</summary>
222+
public static string HlsVideoCodec(int height) => height > 1088 ? "avc1.640033" : "avc1.640029";
223+
224+
/// <summary>
225+
/// HDR to SDR: into linear light (the source's transfer, PQ or HLG, and BT.2020 colours, taken from the probe as
226+
/// files don't always say so in the stream), tone-mapped with Hable, then BT.709 for an ordinary screen. zscale
227+
/// is libzimg's; <see cref="Ffmpeg.CanToneMap"/> checks this ffmpeg has it.
228+
/// </summary>
229+
public static string ToneMapFilter(ProbeStream v)
230+
{
231+
var transfer = v.ColorTransfer == "arib-std-b67" ? "arib-std-b67" : "smpte2084";
232+
return $"zscale=tin={transfer}:min=bt2020nc:pin=bt2020:rin=tv:t=linear:npl=100,format=gbrpf32le," +
233+
"zscale=p=bt709,tonemap=tonemap=hable:desat=0,zscale=t=bt709:m=bt709:r=tv";
234+
}
235+
206236
// ── Adaptive streams ──
207237
//
208238
// An adaptive transcode is a master playlist of levels, each a full-length VOD playlist of fixed segments:
@@ -230,7 +260,7 @@ public static string MasterPlaylist(PlaybackPlan plan, int first)
230260
var l = levels[i];
231261
var (w, h) = OutputSize(plan.Video, l.Height);
232262
int kbps = l.VideoKbps + (plan.Audio is null ? 0 : l.AudioKbps);
233-
var codecs = plan.Audio is null ? "avc1.640029" : "avc1.640029,mp4a.40.2";
263+
var codecs = plan.Audio is null ? HlsVideoCodec(h) : $"{HlsVideoCodec(h)},mp4a.40.2";
234264
sb.Append(CultureInfo.InvariantCulture,
235265
$"#EXT-X-STREAM-INF:BANDWIDTH={kbps * 1000},RESOLUTION={w}x{h},CODECS=\"{codecs}\",NAME=\"{l.Id}\"\n");
236266
sb.Append(CultureInfo.InvariantCulture, $"v{i}/index.m3u8\n");
@@ -269,7 +299,7 @@ public static List<string> SegmentArguments(PlaybackPlan plan, QualityLevel leve
269299
if (o.Encoder == VideoEncoder.Vaapi) a.AddRange(["-vaapi_device", o.VaapiDevice]);
270300
// -ss even at 0: the first frame of a run is then always the first one on or after the boundary
271301
a.AddRange(["-copyts", "-start_at_zero", "-ss", Seconds((double)startSegment * d), "-i", input]);
272-
if (plan.Video is { } v) a.AddRange(VideoTranscode(v, plan.BurnSubtitle, level.Height, level.VideoKbps, o, fixedKeyframes: true));
302+
if (plan.Video is { } v) a.AddRange(VideoTranscode(v, plan.BurnSubtitle, level.Height, level.VideoKbps, o, fixedKeyframes: true, plan.ToneMap));
273303
if (plan.Audio is { } au) a.AddRange(["-map", $"0:{au.Index}", "-c:a", "aac", "-b:a", $"{level.AudioKbps}k", "-ac", "2"]);
274304
a.AddRange([
275305
"-sn", "-dn", "-map_metadata", "-1", "-max_muxing_queue_size", "4096",

‎src/MediaRiffle.Server/Media/ProbeResult.cs‎

Lines changed: 10 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -8,8 +8,15 @@ public enum StreamType { Video, Audio, Subtitle, Other }
88
/// <summary>One stream of a file, from ffprobe.</summary>
99
public sealed record ProbeStream(
1010
int Index, StreamType Type, string Codec, string? Profile, string? PixelFormat,
11-
int Width, int Height, int Channels, string? Language, string? Title, bool IsDefault, bool IsForced)
11+
int Width, int Height, int Channels, string? Language, string? Title, bool IsDefault, bool IsForced,
12+
string? ColorTransfer = null, string? ColorPrimaries = null)
1213
{
14+
/// <summary>
15+
/// HDR video: HDR10 / HDR10+ / Dolby Vision's base layer (PQ, "smpte2084") or HLG ("arib-std-b67"). Converted to
16+
/// ordinary (SDR) H.264 it needs tone mapping, or it looks washed out.
17+
/// </summary>
18+
public bool IsHdr => Type == StreamType.Video && ColorTransfer is "smpte2084" or "arib-std-b67";
19+
1320
/// <summary>Text subtitles can be turned into WebVTT; image ones (PGS, DVD) can only be burned into the video.</summary>
1421
public bool IsTextSubtitle => Type == StreamType.Subtitle &&
1522
Codec is "subrip" or "srt" or "ass" or "ssa" or "mov_text" or "webvtt" or "text";
@@ -97,7 +104,8 @@ public static ProbeResult Parse(string json)
97104
Int(s, "index"), type, Str(s, "codec_name") ?? "unknown", Str(s, "profile"), Str(s, "pix_fmt"),
98105
Int(s, "width"), Int(s, "height"), Int(s, "channels"),
99106
Str(tags, "language"), Str(tags, "title"),
100-
Int(disposition, "default") == 1, Int(disposition, "forced") == 1));
107+
Int(disposition, "default") == 1, Int(disposition, "forced") == 1,
108+
Str(s, "color_transfer"), Str(s, "color_primaries")));
101109
}
102110
}
103111
return new ProbeResult

‎src/MediaRiffle.Server/Media/Quality.cs‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,9 @@ public static class Quality
1818

1919
public static readonly IReadOnlyList<QualityLevel> Ladder =
2020
[
21+
// 4K: only when the server allows it (Transcoding:MaxHeight 2160 and MaxVideoKbps to match), as it wants a fast
22+
// encoder (NVENC, Quick Sync, VA-API) and a fast connection
23+
new("2160", "2160p (4K)", 2160, 25000, 192),
2124
new("1080", "1080p", 1080, 8000, 192),
2225
new("720", "720p", 720, 4000, 160),
2326
new("480", "480p", 480, 1500, 128),

0 commit comments

Comments
 (0)