Преглед на файлове

Offload HEVC transcode decode and scaling to VAAPI

The transcoder only moved the H.264 encode to the GPU; HEVC decoding,
scaling and the 10-bit to NV12 conversion still ran on the CPU, which
saturates low-end CPUs. VAAPI profiles now decode with -hwaccel vaapi,
keep frames on the GPU and scale with scale_vaapi, falling back to
software decode for sources the GPU cannot handle. Low-power (VDEnc)
variants are tried for drivers such as Debian's free iHD build that only
offer that entrypoint, and every DRM render node is probed.
Toby Chui преди 11 часа
родител
ревизия
ff5d5071dc

+ 3 - 0
src/mod/media/transcoder/hls.go

@@ -265,6 +265,9 @@ func buildHLSArgs(inputFile string, dir string, resolution TranscodeOutputResolu
 		// zero, which is what the growing playlist expects.
 		args = append(args, "-ss", fmt.Sprintf("%.3f", startTime))
 	}
+	if hw != nil {
+		args = append(args, hw.DecodeArgs...)
+	}
 	args = append(args, "-i", inputFile)
 
 	// Take the first video and, if present, the first audio track. Without this

+ 11 - 4
src/mod/media/transcoder/hwaccel.go

@@ -4,7 +4,8 @@ package transcoder
 	hwaccel.go
 
 	Detects and caches a working hardware H.264 encoder so TranscodeAndStream
-	can offload encoding from the CPU when the host supports it, falling back
+	can offload encoding (and, where the profile supports it, decoding and
+	scaling too) from the CPU when the host supports it, falling back
 	to the existing libx264 software path otherwise. Platform-specific profiles
 	(which encoder, which ffmpeg args) live in hwaccel_linux.go /
 	hwaccel_windows.go / hwaccel_darwin.go / hwaccel_other.go.
@@ -22,9 +23,15 @@ import (
 // hwEncoderProfile describes how to invoke a hardware-accelerated H.264
 // encoder as a drop-in replacement for the software libx264 path.
 type hwEncoderProfile struct {
-	Name        string                    // human-readable label for logging, e.g. "Intel/AMD VAAPI"
-	Codec       string                    // ffmpeg -vcodec value, e.g. "h264_vaapi"
-	PreInput    []string                  // extra global args inserted before -i (device init, etc.)
+	Name     string   // human-readable label for logging, e.g. "Intel/AMD VAAPI"
+	Codec    string   // ffmpeg -vcodec value, e.g. "h264_vaapi"
+	PreInput []string // extra global args inserted before -i (device init, etc.)
+	// DecodeArgs are input options, placed right before -i, that turn on
+	// hardware decoding and keep the decoded frames in GPU memory. They are
+	// left out of the probe encode, whose synthetic input has no hardware
+	// decoder to test. ffmpeg decodes a source the GPU cannot handle in
+	// software instead, so ScaleFilter must then accept both kinds of frame.
+	DecodeArgs  []string
 	ScaleFilter func(scale string) string // -vf value wrapping the given scale filter ("" = no scaling)
 	EncodeArgs  []string                  // encoder-specific args replacing "-preset superfast"
 	ProbeSize   string                    // WxH test frame size for the probe encode; "" uses defaultProbeSize

+ 11 - 17
src/mod/media/transcoder/hwaccel_linux.go

@@ -8,15 +8,16 @@ package transcoder
 
 	NVIDIA GPUs are tried first via NVENC (its own proprietary encode API,
 	needs the vendor driver but not VAAPI). Intel and AMD GPUs both expose
-	hardware H.264 encoding through VAAPI via their respective iHD/Mesa
-	drivers, so a single fallback profile covers both vendors, using the
-	default DRM render node. If a given encoder is unsupported or its driver
-	isn't present, testHWEncoder (hwaccel.go) will fail that profile's probe
-	and the next candidate (or software encoding) is used instead.
+	hardware decoding, scaling and H.264 encoding through VAAPI via their
+	respective iHD/Mesa drivers, so the VAAPI profiles (hwaccel_vaapi.go) cover
+	both vendors on every DRM render node present. If a given encoder is
+	unsupported or its driver isn't present, testHWEncoder (hwaccel.go) will
+	fail that profile's probe and the next candidate (or software encoding) is
+	used instead.
 */
 
 func candidateHWProfiles() []*hwEncoderProfile {
-	return []*hwEncoderProfile{
+	profiles := []*hwEncoderProfile{
 		{
 			Name:        "NVIDIA NVENC",
 			Codec:       "h264_nvenc",
@@ -26,16 +27,9 @@ func candidateHWProfiles() []*hwEncoderProfile {
 			// 250-frame GOP (~10s) and every seek has to wait for one.
 			EncodeArgs: []string{"-preset", "fast", "-forced-idr", "1"},
 		},
-		{
-			Name:     "Intel/AMD VAAPI",
-			Codec:    "h264_vaapi",
-			PreInput: []string{"-vaapi_device", "/dev/dri/renderD128"},
-			ScaleFilter: func(scale string) string {
-				if scale == "" {
-					return "format=nv12,hwupload"
-				}
-				return scale + ",format=nv12,hwupload"
-			},
-		},
 	}
+	for _, device := range vaapiRenderNodes() {
+		profiles = append(profiles, vaapiProfiles(device)...)
+	}
+	return profiles
 }

+ 127 - 0
src/mod/media/transcoder/hwaccel_vaapi.go

@@ -0,0 +1,127 @@
+package transcoder
+
+/*
+	hwaccel_vaapi.go
+
+	VAAPI profiles for Intel and AMD GPUs. Only Linux offers them (see
+	hwaccel_linux.go), but they are plain argument builders with no syscalls,
+	so they live in an untagged file and are tested on every platform.
+
+	Two pipelines are offered, best first:
+
+	  - Full hardware: the GPU decodes the source (-hwaccel vaapi), scales it and
+	    converts 10-bit to 8-bit (scale_vaapi), then encodes it. Frames never
+	    leave GPU memory, so a 1080p or 4K HEVC source costs the CPU little more
+	    than demuxing and the audio track. Before this existed, only the encode
+	    was offloaded: an HEVC source was still decoded, scaled and converted to
+	    NV12 by the CPU, which a low-end dual-core cannot keep up with.
+	  - Encode only: the CPU decodes and scales, the GPU encodes. Kept for
+	    drivers without the video processing (VPP) entrypoint scale_vaapi needs.
+
+	Each comes in two flavours. Intel's media driver exposes H.264 encoding
+	either through the full encode entrypoint or the low-power (VDEnc) one,
+	and the free build Debian and Ubuntu ship as intel-media-va-driver has only
+	the low-power one on most generations, since the other needs the non-free
+	shader kernels. ffmpeg's h264_vaapi asks for the full entrypoint unless
+	told -low_power 1 and does not try the other on its own, so without the
+	low-power variant such a host would fall back to libx264 entirely.
+*/
+
+import (
+	"path/filepath"
+	"sort"
+	"strings"
+)
+
+// vaapiRenderNodeGlob matches the DRM render nodes VAAPI devices are opened
+// through (renderD128, renderD129, ... one per GPU).
+const vaapiRenderNodeGlob = "/dev/dri/renderD*"
+
+// vaapiDefaultRenderNode is tried when no render node can be listed, which
+// keeps the behaviour of the single hardcoded node used before.
+const vaapiDefaultRenderNode = "/dev/dri/renderD128"
+
+// vaapiRenderNodes lists the render nodes to probe, in name order. A machine
+// with an NVIDIA card next to the Intel iGPU has the iGPU on renderD129, which
+// the single default node used to miss.
+func vaapiRenderNodes() []string {
+	nodes, err := filepath.Glob(vaapiRenderNodeGlob)
+	if err != nil || len(nodes) == 0 {
+		return []string{vaapiDefaultRenderNode}
+	}
+	sort.Strings(nodes)
+	return nodes
+}
+
+// vaapiProfiles returns the VAAPI candidates for one render node, best first.
+func vaapiProfiles(device string) []*hwEncoderProfile {
+	preInput := []string{"-vaapi_device", device}
+	lowPower := []string{"-low_power", "1"}
+	// -hwaccel_output_format vaapi keeps decoded frames on the GPU. A source
+	// the GPU cannot decode (an unsupported profile, or a codec such as MPEG-4
+	// Part 2 that VAAPI never had) is decoded in software by ffmpeg instead
+	// of failing, and vaapiHWFilter uploads those frames.
+	decode := []string{"-hwaccel", "vaapi", "-hwaccel_output_format", "vaapi"}
+	name := filepath.Base(device)
+
+	return []*hwEncoderProfile{
+		{
+			Name:        "Intel/AMD VAAPI, hardware decode and encode (" + name + ")",
+			Codec:       "h264_vaapi",
+			PreInput:    preInput,
+			DecodeArgs:  decode,
+			ScaleFilter: vaapiHWFilter,
+		},
+		{
+			Name:        "Intel/AMD VAAPI low-power, hardware decode and encode (" + name + ")",
+			Codec:       "h264_vaapi",
+			PreInput:    preInput,
+			DecodeArgs:  decode,
+			ScaleFilter: vaapiHWFilter,
+			EncodeArgs:  lowPower,
+		},
+		{
+			Name:        "Intel/AMD VAAPI, encode only (" + name + ")",
+			Codec:       "h264_vaapi",
+			PreInput:    preInput,
+			ScaleFilter: vaapiUploadFilter,
+		},
+		{
+			Name:        "Intel/AMD VAAPI low-power, encode only (" + name + ")",
+			Codec:       "h264_vaapi",
+			PreInput:    preInput,
+			ScaleFilter: vaapiUploadFilter,
+			EncodeArgs:  lowPower,
+		},
+	}
+}
+
+// vaapiHWFilter is the -vf chain of the full hardware pipeline.
+//
+// format=nv12|vaapi lets GPU-decoded frames through untouched and converts
+// software-decoded ones to NV12; hwupload then uploads the latter and passes
+// the former through. scale_vaapi resizes on the GPU and, with format=nv12,
+// also turns 10-bit (P010) frames into the 8-bit NV12 that h264_vaapi and the
+// browsers need - so it stays in the chain even when nothing is resized.
+func vaapiHWFilter(scale string) string {
+	return "format=nv12|vaapi,hwupload," + vaapiScaleFilter(scale)
+}
+
+// vaapiScaleFilter turns a software scale filter from resolutionScaleFilter
+// into its scale_vaapi equivalent; the w/h expressions are the same, since
+// scale_vaapi evaluates them like scale does.
+func vaapiScaleFilter(scale string) string {
+	if scale == "" {
+		return "scale_vaapi=format=nv12"
+	}
+	return "scale_vaapi=" + strings.TrimPrefix(scale, "scale=") + ":format=nv12"
+}
+
+// vaapiUploadFilter is the -vf chain of the encode-only pipeline: scale and
+// convert in software, then upload for the encoder.
+func vaapiUploadFilter(scale string) string {
+	if scale == "" {
+		return "format=nv12,hwupload"
+	}
+	return scale + ",format=nv12,hwupload"
+}

+ 202 - 0
src/mod/media/transcoder/hwaccel_vaapi_test.go

@@ -0,0 +1,202 @@
+package transcoder
+
+import (
+	"strings"
+	"testing"
+)
+
+// TestVAAPIScaleFilter verifies the software scale filter is carried over to
+// scale_vaapi with its expressions intact, and that the NV12 conversion is
+// always present (it is what turns 10-bit frames into 8-bit ones).
+func TestVAAPIScaleFilter(t *testing.T) {
+	scale720, err := resolutionScaleFilter(TranscodeResolution_720p)
+	if err != nil {
+		t.Fatalf("resolutionScaleFilter(720p) returned error: %v", err)
+	}
+	cases := []struct {
+		name  string
+		scale string
+		want  string
+	}{
+		{"no resize", "", "scale_vaapi=format=nv12"},
+		{"plain resize", "scale=w=640:h=360", "scale_vaapi=w=640:h=360:format=nv12"},
+		{"preset resize", scale720, "scale_vaapi=" + strings.TrimPrefix(scale720, "scale=") + ":format=nv12"},
+	}
+	for _, tc := range cases {
+		t.Run(tc.name, func(t *testing.T) {
+			if got := vaapiScaleFilter(tc.scale); got != tc.want {
+				t.Errorf("vaapiScaleFilter(%q) = %q, want %q", tc.scale, got, tc.want)
+			}
+		})
+	}
+}
+
+// TestResolutionScaleFilterPrefix guards the assumption vaapiScaleFilter makes:
+// every preset's software filter is a single scale= filter.
+func TestResolutionScaleFilterPrefix(t *testing.T) {
+	for resolution := range qualityPresets {
+		scale, err := resolutionScaleFilter(resolution)
+		if err != nil {
+			t.Fatalf("resolutionScaleFilter(%q) returned error: %v", resolution, err)
+		}
+		// Commas inside the quoted min() expressions are fine; one between
+		// filters would sit right after a closing quote.
+		if !strings.HasPrefix(scale, "scale=") || strings.Contains(scale, "',") {
+			t.Errorf("resolutionScaleFilter(%q) = %q, want a single scale= filter", resolution, scale)
+		}
+	}
+}
+
+// TestVAAPIFilters verifies both pipelines' -vf chains.
+func TestVAAPIFilters(t *testing.T) {
+	cases := []struct {
+		name   string
+		filter func(string) string
+		scale  string
+		want   string
+	}{
+		{"hardware, no resize", vaapiHWFilter, "", "format=nv12|vaapi,hwupload,scale_vaapi=format=nv12"},
+		{"hardware, resize", vaapiHWFilter, "scale=w=640:h=360", "format=nv12|vaapi,hwupload,scale_vaapi=w=640:h=360:format=nv12"},
+		{"upload, no resize", vaapiUploadFilter, "", "format=nv12,hwupload"},
+		{"upload, resize", vaapiUploadFilter, "scale=w=640:h=360", "scale=w=640:h=360,format=nv12,hwupload"},
+	}
+	for _, tc := range cases {
+		t.Run(tc.name, func(t *testing.T) {
+			if got := tc.filter(tc.scale); got != tc.want {
+				t.Errorf("filter(%q) = %q, want %q", tc.scale, got, tc.want)
+			}
+		})
+	}
+}
+
+// TestVAAPIProfiles verifies the candidate order (full hardware before encode
+// only, each normal before low-power) and that every profile opens the given
+// render node.
+func TestVAAPIProfiles(t *testing.T) {
+	const device = "/dev/dri/renderD129"
+	profiles := vaapiProfiles(device)
+	want := []struct {
+		hwDecode bool
+		lowPower bool
+	}{
+		{true, false},
+		{true, true},
+		{false, false},
+		{false, true},
+	}
+	if len(profiles) != len(want) {
+		t.Fatalf("vaapiProfiles() returned %d profiles, want %d", len(profiles), len(want))
+	}
+	for i, p := range profiles {
+		if p.Codec != "h264_vaapi" {
+			t.Errorf("profile %d Codec = %q, want h264_vaapi", i, p.Codec)
+		}
+		if strings.Join(p.PreInput, " ") != "-vaapi_device "+device {
+			t.Errorf("profile %d PreInput = %v, want -vaapi_device %s", i, p.PreInput, device)
+		}
+		if !strings.Contains(p.Name, "renderD129") {
+			t.Errorf("profile %d Name = %q, want it to name the render node", i, p.Name)
+		}
+		hwDecode := strings.Join(p.DecodeArgs, " ") == "-hwaccel vaapi -hwaccel_output_format vaapi"
+		if hwDecode != want[i].hwDecode {
+			t.Errorf("profile %d (%s) DecodeArgs = %v, want hardware decode %v", i, p.Name, p.DecodeArgs, want[i].hwDecode)
+		}
+		if hwDecode != strings.Contains(p.ScaleFilter(""), "scale_vaapi") {
+			t.Errorf("profile %d (%s) hardware decode %v does not match filter %q", i, p.Name, hwDecode, p.ScaleFilter(""))
+		}
+		lowPower := strings.Join(p.EncodeArgs, " ") == "-low_power 1"
+		if lowPower != want[i].lowPower {
+			t.Errorf("profile %d (%s) EncodeArgs = %v, want low power %v", i, p.Name, p.EncodeArgs, want[i].lowPower)
+		}
+	}
+}
+
+// TestVAAPIRenderNodes verifies a node is always offered, even on hosts with
+// no /dev/dri (such as the Windows and macOS machines tests also run on).
+func TestVAAPIRenderNodes(t *testing.T) {
+	nodes := vaapiRenderNodes()
+	if len(nodes) == 0 {
+		t.Fatal("vaapiRenderNodes() returned no node")
+	}
+	for _, node := range nodes {
+		if !strings.Contains(node, "renderD") {
+			t.Errorf("vaapiRenderNodes() returned %q, want a render node", node)
+		}
+	}
+}
+
+// TestProbeArgsOmitDecodeArgs verifies the probe never asks for hardware
+// decoding: its input is a synthetic lavfi source with no hardware decoder.
+func TestProbeArgsOmitDecodeArgs(t *testing.T) {
+	profile := vaapiProfiles(vaapiDefaultRenderNode)[0]
+	args := probeArgs(profile)
+	if indexOf(args, "-hwaccel") != -1 || indexOf(args, "-hwaccel_output_format") != -1 {
+		t.Errorf("probeArgs() = %v, want no hardware decode options", args)
+	}
+	if vf := indexOf(args, "-vf"); vf == -1 || args[vf+1] != vaapiHWFilter("") {
+		t.Errorf("probeArgs() = %v, want the full hardware filter chain", args)
+	}
+}
+
+// TestDecodeArgsPlacement verifies the MP4 and HLS command lines put the
+// hardware decode options after the device and seek and before -i, which is
+// where ffmpeg reads input options from.
+func TestDecodeArgsPlacement(t *testing.T) {
+	hw := vaapiProfiles(vaapiDefaultRenderNode)[0]
+	builders := map[string]func() ([]string, error){
+		"mp4": func() ([]string, error) {
+			return buildMP4Args("in.mkv", TranscodeResolution_720p, 30, hw)
+		},
+		"hls": func() ([]string, error) {
+			return buildHLSArgs("in.mkv", t.TempDir(), TranscodeResolution_720p, 30, "/seg/", hw)
+		},
+	}
+	for name, build := range builders {
+		t.Run(name, func(t *testing.T) {
+			args, err := build()
+			if err != nil {
+				t.Fatalf("build returned error: %v", err)
+			}
+			device := indexOf(args, "-vaapi_device")
+			seek := indexOf(args, "-ss")
+			hwaccel := indexOf(args, "-hwaccel")
+			input := indexOf(args, "-i")
+			if device == -1 || seek == -1 || hwaccel == -1 || input == -1 {
+				t.Fatalf("missing -vaapi_device, -ss, -hwaccel or -i in %v", args)
+			}
+			if !(device < seek && seek < hwaccel && hwaccel < input) {
+				t.Errorf("want -vaapi_device < -ss < -hwaccel < -i, got %d, %d, %d, %d\nargs: %v",
+					device, seek, hwaccel, input, args)
+			}
+			vf := indexOf(args, "-vf")
+			if vf == -1 || !strings.HasPrefix(args[vf+1], "format=nv12|vaapi,hwupload,scale_vaapi=") {
+				t.Errorf("want the GPU scale chain after -vf, got %v", args)
+			}
+			if indexOf(args, "h264_vaapi") == -1 || indexOf(args, "libx264") != -1 {
+				t.Errorf("want h264_vaapi and no libx264, got %v", args)
+			}
+		})
+	}
+}
+
+// TestBuildMP4ArgsSoftware verifies the software path keeps libx264 with an
+// 8-bit pixel format and asks for no hardware decoding.
+func TestBuildMP4ArgsSoftware(t *testing.T) {
+	args, err := buildMP4Args("in.mkv", TranscodeResolution_original, 0, nil)
+	if err != nil {
+		t.Fatalf("buildMP4Args returned error: %v", err)
+	}
+	joined := strings.Join(args, " ")
+	if !strings.Contains(joined, "-vcodec libx264") || !strings.Contains(joined, "-pix_fmt yuv420p") {
+		t.Errorf("want libx264 with yuv420p, got %v", args)
+	}
+	if indexOf(args, "-hwaccel") != -1 || indexOf(args, "-ss") != -1 || indexOf(args, "-vf") != -1 {
+		t.Errorf("want no -hwaccel, -ss or -vf, got %v", args)
+	}
+	if args[len(args)-1] != "pipe:1" {
+		t.Errorf("want output on pipe:1, got %v", args)
+	}
+	if _, err := buildMP4Args("in.mkv", "banana", 0, nil); err == nil {
+		t.Error("buildMP4Args accepted an invalid resolution, want error")
+	}
+}

+ 53 - 41
src/mod/media/transcoder/transcoder.go

@@ -36,53 +36,16 @@ const (
 // Sync / AMF on Linux and Windows, VideoToolbox on macOS - it is used in place
 // of libx264 to keep CPU load down (probed once and cached by
 // getHWEncoderProfile); otherwise this falls back to the original software path.
+// With VAAPI the source is decoded and scaled on the GPU as well, which is what
+// keeps an HEVC source from saturating a low-end CPU.
 func TranscodeAndStream(w http.ResponseWriter, r *http.Request, inputFile string, resolution TranscodeOutputResolution, startTime float64) {
 	// Build the FFmpeg command based on the resolution parameter
-	var cmd *exec.Cmd
-
-	scale, err := resolutionScaleFilter(resolution)
+	args, err := buildMP4Args(inputFile, resolution, startTime, getHWEncoderProfile())
 	if err != nil {
 		http.Error(w, "Invalid resolution parameter", http.StatusBadRequest)
 		return
 	}
-
-	var preInputArgs []string
-	if startTime > 0.001 {
-		preInputArgs = append(preInputArgs, "-ss", fmt.Sprintf("%.3f", startTime))
-	}
-
-	var videoCodecArgs []string
-	var vf string
-	if hw := getHWEncoderProfile(); hw != nil {
-		preInputArgs = append(append([]string{}, hw.PreInput...), preInputArgs...)
-		vf = hw.ScaleFilter(scale)
-		videoCodecArgs = append([]string{"-vcodec", hw.Codec}, hw.EncodeArgs...)
-		videoCodecArgs = append(videoCodecArgs, rateControlArgs(resolution, true)...)
-	} else {
-		vf = scale
-		// -pix_fmt yuv420p is not optional. libx264 otherwise matches the source
-		// bit depth, so a 10-bit input (routine in anime releases) produces a
-		// High 10 stream that Chrome and Firefox cannot decode — the transcode
-		// would appear to succeed and then fail to play, which is the whole
-		// problem transcoding exists to avoid.
-		videoCodecArgs = []string{"-vcodec", "libx264", "-preset", "superfast", "-pix_fmt", "yuv420p"}
-		videoCodecArgs = append(videoCodecArgs, rateControlArgs(resolution, false)...)
-	}
-
-	middleArgs := []string{"-i", inputFile}
-	if vf != "" {
-		middleArgs = append(middleArgs, "-vf", vf)
-	}
-
-	transcodeFormatArgs := []string{"-f", "mp4"}
-	transcodeFormatArgs = append(transcodeFormatArgs, videoCodecArgs...)
-	transcodeFormatArgs = append(transcodeFormatArgs, "-g", "60", "-movflags", "frag_keyframe+empty_moov+faststart", "pipe:1")
-
-	var args []string
-	args = append(args, preInputArgs...)
-	args = append(args, middleArgs...)
-	args = append(args, transcodeFormatArgs...)
-	cmd = exec.Command("ffmpeg", args...)
+	cmd := exec.Command("ffmpeg", args...)
 
 	// Set response headers for streaming MP4 video
 	w.Header().Set("Content-Type", "video/mp4")
@@ -153,6 +116,55 @@ func TranscodeAndStream(w http.ResponseWriter, r *http.Request, inputFile string
 	logger.PrintAndLog("Transcoder", "[Media Server] Transcode client disconnected", nil)
 }
 
+// buildMP4Args assembles the ffmpeg command line of TranscodeAndStream: the
+// hardware profile when one is given, libx264 otherwise, muxed into a
+// fragmented MP4 on stdout. buildHLSArgs is its HLS counterpart.
+func buildMP4Args(inputFile string, resolution TranscodeOutputResolution, startTime float64, hw *hwEncoderProfile) ([]string, error) {
+	scale, err := resolutionScaleFilter(resolution)
+	if err != nil {
+		return nil, err
+	}
+
+	var preInputArgs []string
+	if startTime > 0.001 {
+		preInputArgs = append(preInputArgs, "-ss", fmt.Sprintf("%.3f", startTime))
+	}
+
+	var videoCodecArgs []string
+	var vf string
+	if hw != nil {
+		preInputArgs = append(append([]string{}, hw.PreInput...), preInputArgs...)
+		preInputArgs = append(preInputArgs, hw.DecodeArgs...)
+		vf = hw.ScaleFilter(scale)
+		videoCodecArgs = append([]string{"-vcodec", hw.Codec}, hw.EncodeArgs...)
+		videoCodecArgs = append(videoCodecArgs, rateControlArgs(resolution, true)...)
+	} else {
+		vf = scale
+		// -pix_fmt yuv420p is not optional. libx264 otherwise matches the source
+		// bit depth, so a 10-bit input (routine in anime releases) produces a
+		// High 10 stream that Chrome and Firefox cannot decode — the transcode
+		// would appear to succeed and then fail to play, which is the whole
+		// problem transcoding exists to avoid.
+		videoCodecArgs = []string{"-vcodec", "libx264", "-preset", "superfast", "-pix_fmt", "yuv420p"}
+		videoCodecArgs = append(videoCodecArgs, rateControlArgs(resolution, false)...)
+	}
+
+	middleArgs := []string{"-i", inputFile}
+	if vf != "" {
+		middleArgs = append(middleArgs, "-vf", vf)
+	}
+
+	transcodeFormatArgs := []string{"-f", "mp4"}
+	transcodeFormatArgs = append(transcodeFormatArgs, videoCodecArgs...)
+	transcodeFormatArgs = append(transcodeFormatArgs, "-g", "60", "-movflags", "frag_keyframe+empty_moov+faststart", "pipe:1")
+
+	var args []string
+	args = append(args, preInputArgs...)
+	args = append(args, middleArgs...)
+	args = append(args, transcodeFormatArgs...)
+	return args, nil
+}
+
 type TranscodeAudioSampleRate int
 
 const (