فهرست منبع

Merge branch 'v3.0.5' of https://github.com/tobychui/arozos into v3.0.5

Toby Chui 3 هفته پیش
والد
کامیت
2110d52595

+ 2 - 10
src/mod/media/mediaserver/hls.go

@@ -12,7 +12,7 @@ package mediaserver
 	(web/script/hlsmse.js) because the segments are fragmented MP4.
 
 	Two endpoints make up the format:
-	  /media/hls/          ?file=<vpath>[&res=][&start=]  -> the .m3u8 playlist
+	  /media/hls/          ?file=<vpath>[&res=360p|480p|720p|1080p][&start=]  -> the .m3u8 playlist
 	  /media/hls/segment   ?sid=<session>&name=<segment>  -> one fMP4 segment, or the init segment
 
 	The playlist request creates (or joins) a transcode session; every segment
@@ -45,15 +45,7 @@ func transcodeResolutionFromRequest(r *http.Request) transcoder.TranscodeOutputR
 	if err != nil {
 		return transcoder.TranscodeResolution_original
 	}
-	switch resolution {
-	case "1080p":
-		return transcoder.TranscodeResolution_1080p
-	case "720p":
-		return transcoder.TranscodeResolution_720p
-	case "360p":
-		return transcoder.TranscodeResolution_360p
-	}
-	return transcoder.TranscodeResolution_original
+	return transcoder.ParseTranscodeResolution(resolution)
 }
 
 // clientIDFromRequest reads the optional "client" parameter identifying the

+ 5 - 21
src/mod/media/transcoder/hls.go

@@ -239,7 +239,7 @@ func hlsSessionKey(owner string, inputFile string, resolution TranscodeOutputRes
 // segments be fetched from an HTTP endpoint rather than sitting next to the
 // playlist on disk.
 func buildHLSArgs(inputFile string, dir string, resolution TranscodeOutputResolution, startTime float64, segmentBaseURL string, hw *hwEncoderProfile) ([]string, error) {
-	height, err := resolutionHeight(resolution)
+	scale, err := resolutionScaleFilter(resolution)
 	if err != nil {
 		return nil, err
 	}
@@ -249,15 +249,15 @@ func buildHLSArgs(inputFile string, dir string, resolution TranscodeOutputResolu
 	var videoCodecArgs []string
 	if hw != nil {
 		args = append(args, hw.PreInput...)
-		vf = hw.ScaleFilter(height)
+		vf = hw.ScaleFilter(scale)
 		videoCodecArgs = append([]string{"-vcodec", hw.Codec}, hw.EncodeArgs...)
+		videoCodecArgs = append(videoCodecArgs, rateControlArgs(resolution, true)...)
 	} else {
-		if height != "" {
-			vf = "scale=-1:" + height
-		}
+		vf = scale
 		// See TranscodeAndStream: without this a 10-bit source yields a High 10
 		// stream that most browsers cannot decode.
 		videoCodecArgs = []string{"-vcodec", "libx264", "-preset", "superfast", "-pix_fmt", "yuv420p"}
+		videoCodecArgs = append(videoCodecArgs, rateControlArgs(resolution, false)...)
 	}
 
 	if startTime > 0.001 {
@@ -317,22 +317,6 @@ func hlsOutputPath(dir string, name string) string {
 	return filepath.ToSlash(filepath.Join(dir, name))
 }
 
-// resolutionHeight maps a requested output resolution to an ffmpeg scale
-// height, returning an error for anything unrecognised.
-func resolutionHeight(resolution TranscodeOutputResolution) (string, error) {
-	switch resolution {
-	case "360p":
-		return "360", nil
-	case "720p":
-		return "720", nil
-	case "1080p":
-		return "1080", nil
-	case "":
-		return "", nil
-	}
-	return "", errors.New("invalid resolution parameter")
-}
-
 // HLSManager owns every live HLS session and the temp directory they live in.
 type HLSManager struct {
 	root            string // parent directory for all session directories

+ 2 - 36
src/mod/media/transcoder/hls_test.go

@@ -156,41 +156,6 @@ func TestHLSSessionKey(t *testing.T) {
 	}
 }
 
-// TestResolutionHeight covers the shared mapping used by both the MP4 and the
-// HLS path, including the rejection that guards the endpoint.
-func TestResolutionHeight(t *testing.T) {
-	cases := []struct {
-		resolution TranscodeOutputResolution
-		want       string
-		wantErr    bool
-	}{
-		{TranscodeResolution_original, "", false},
-		{"360p", "360", false},
-		{"720p", "720", false},
-		{"1080p", "1080", false},
-		{"banana", "", true},
-		{"480p", "", true},
-	}
-
-	for _, tc := range cases {
-		t.Run(string(tc.resolution), func(t *testing.T) {
-			got, err := resolutionHeight(tc.resolution)
-			if tc.wantErr {
-				if err == nil {
-					t.Fatalf("resolutionHeight(%q) returned no error, want one", tc.resolution)
-				}
-				return
-			}
-			if err != nil {
-				t.Fatalf("resolutionHeight(%q) returned error: %v", tc.resolution, err)
-			}
-			if got != tc.want {
-				t.Errorf("resolutionHeight(%q) = %q, want %q", tc.resolution, got, tc.want)
-			}
-		})
-	}
-}
-
 // TestBuildHLSArgs checks the generated command line for the properties that
 // make the output playable: correct muxer settings, the whole playlist kept,
 // the segment URL prefix, and the encoder chosen the same way the MP4 path
@@ -212,7 +177,8 @@ func TestBuildHLSArgs(t *testing.T) {
 			"-hls_playlist_type event",
 			"-hls_base_url " + baseURL,
 			"-vcodec libx264",
-			"-vf scale=-1:360",
+			"-vf scale=w=",
+			"-maxrate 800k",
 			"-c:a aac",
 			"-map 0:v:0",
 		} {

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

@@ -22,12 +22,12 @@ 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.)
-	ScaleFilter func(height string) string // -vf value for the given target height ("" height = no scaling)
-	EncodeArgs  []string                   // encoder-specific args replacing "-preset superfast"
-	ProbeSize   string                     // WxH test frame size for the probe encode; "" uses defaultProbeSize
+	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.)
+	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
 }
 
 // defaultProbeSize is the test frame size used by testHWEncoder when a profile
@@ -41,16 +41,16 @@ var (
 	hwProfile     *hwEncoderProfile // nil if no usable hardware encoder was found
 )
 
-// nv12ScaleFilter returns a -vf filter chain that performs the requested
-// resize (if any) and converts to NV12. This is what the hardware encoders
+// nv12ScaleFilter returns a -vf filter chain that applies the given scale
+// filter (if any, see resolutionScaleFilter) and converts to NV12. This is what the hardware encoders
 // that accept plain system-memory frames (NVENC, QSV, AMF) expect as input -
 // unlike VAAPI, they upload to the GPU internally so no explicit hwupload
 // step is needed.
-func nv12ScaleFilter(height string) string {
-	if height == "" {
+func nv12ScaleFilter(scale string) string {
+	if scale == "" {
 		return "format=nv12"
 	}
-	return "scale=-1:" + height + ",format=nv12"
+	return scale + ",format=nv12"
 }
 
 // getHWEncoderProfile probes the host once for a working Intel/AMD hardware

+ 3 - 3
src/mod/media/transcoder/hwaccel_linux.go

@@ -30,11 +30,11 @@ func candidateHWProfiles() []*hwEncoderProfile {
 			Name:     "Intel/AMD VAAPI",
 			Codec:    "h264_vaapi",
 			PreInput: []string{"-vaapi_device", "/dev/dri/renderD128"},
-			ScaleFilter: func(height string) string {
-				if height == "" {
+			ScaleFilter: func(scale string) string {
+				if scale == "" {
 					return "format=nv12,hwupload"
 				}
-				return "scale=-1:" + height + ",format=nv12,hwupload"
+				return scale + ",format=nv12,hwupload"
 			},
 		},
 	}

+ 10 - 10
src/mod/media/transcoder/hwaccel_test.go

@@ -10,20 +10,19 @@ import (
 // the hardware encoders that accept plain system-memory frames.
 func TestNV12ScaleFilter(t *testing.T) {
 	cases := []struct {
-		name   string
-		height string
-		want   string
+		name  string
+		scale string
+		want  string
 	}{
 		{"no resize", "", "format=nv12"},
-		{"resize to 360", "360", "scale=-1:360,format=nv12"},
-		{"resize to 720", "720", "scale=-1:720,format=nv12"},
+		{"resize", "scale=w=640:h=360", "scale=w=640:h=360,format=nv12"},
 	}
 
 	for _, tc := range cases {
 		t.Run(tc.name, func(t *testing.T) {
-			got := nv12ScaleFilter(tc.height)
+			got := nv12ScaleFilter(tc.scale)
 			if got != tc.want {
-				t.Errorf("nv12ScaleFilter(%q) = %q, want %q", tc.height, got, tc.want)
+				t.Errorf("nv12ScaleFilter(%q) = %q, want %q", tc.scale, got, tc.want)
 			}
 		})
 	}
@@ -43,9 +42,10 @@ func TestCandidateHWProfiles(t *testing.T) {
 		if profile.ScaleFilter == nil {
 			t.Fatalf("profile %q has nil ScaleFilter", profile.Name)
 		}
-		for _, height := range []string{"", "360", "720", "1080"} {
-			if vf := profile.ScaleFilter(height); vf == "" {
-				t.Errorf("profile %q ScaleFilter(%q) returned empty string", profile.Name, height)
+		for _, resolution := range []TranscodeOutputResolution{TranscodeResolution_original, TranscodeResolution_360p, TranscodeResolution_1080p} {
+			scale, _ := resolutionScaleFilter(resolution)
+			if vf := profile.ScaleFilter(scale); vf == "" {
+				t.Errorf("profile %q ScaleFilter(%q) returned empty string", profile.Name, scale)
 			}
 		}
 		if profile.ProbeSize != "" && !regexp.MustCompile(`^\d+x\d+$`).MatchString(profile.ProbeSize) {

+ 13 - 0
src/mod/media/transcoder/probe.go

@@ -18,6 +18,7 @@ import (
 	"errors"
 	"fmt"
 	"os/exec"
+	"strconv"
 	"strings"
 	"time"
 )
@@ -32,6 +33,10 @@ type MediaCodecInfo struct {
 	AudioCodec   string `json:"audioCodec"`   // aac, opus, ac3, …
 	Width        int    `json:"width"`
 	Height       int    `json:"height"`
+	// BitRate is the whole file's average bitrate in bits per second, 0 when
+	// the container does not say. The player's Auto quality uses it to judge
+	// whether the connection can carry the file as it is.
+	BitRate int64 `json:"bitRate"`
 
 	// DirectPlay is the server's verdict on whether a mainstream browser can
 	// decode this without transcoding. The client still has the final say via
@@ -76,6 +81,7 @@ func ProbeMediaCodecs(inputFile string) (*MediaCodecInfo, error) {
 		"-v", "quiet",
 		"-print_format", "json",
 		"-show_streams",
+		"-show_format",
 		inputFile,
 	)
 	output, err := cmd.Output()
@@ -103,12 +109,19 @@ func parseMediaCodecs(probeJSON []byte) (*MediaCodecInfo, error) {
 			// disposition is what tells it apart from the real picture.
 			Disposition map[string]int `json:"disposition"`
 		} `json:"streams"`
+		Format struct {
+			BitRate string `json:"bit_rate"`
+		} `json:"format"`
 	}
 	if err := json.Unmarshal(probeJSON, &parsed); err != nil {
 		return nil, fmt.Errorf("could not parse ffprobe output: %w", err)
 	}
 
 	info := &MediaCodecInfo{}
+	//ffprobe reports the bitrate as a decimal string, or "N/A"
+	if bitRate, err := strconv.ParseInt(parsed.Format.BitRate, 10, 64); err == nil && bitRate > 0 {
+		info.BitRate = bitRate
+	}
 	haveVideo := false
 	haveAudio := false
 

+ 28 - 0
src/mod/media/transcoder/probe_test.go

@@ -185,3 +185,31 @@ func TestIsHighBitDepth(t *testing.T) {
 		})
 	}
 }
+
+// TestParseMediaCodecs_BitRate covers the container bitrate the player's Auto
+// quality reads, including the "N/A" ffprobe prints when it does not know.
+func TestParseMediaCodecs_BitRate(t *testing.T) {
+	cases := []struct {
+		name  string
+		probe string
+		want  int64
+	}{
+		{"reported", `{"streams":[{"codec_type":"video","codec_name":"h264","pix_fmt":"yuv420p"}],
+			"format":{"bit_rate":"4512345"}}`, 4512345},
+		{"not available", `{"streams":[{"codec_type":"video","codec_name":"h264","pix_fmt":"yuv420p"}],
+			"format":{"bit_rate":"N/A"}}`, 0},
+		{"no format section", `{"streams":[{"codec_type":"video","codec_name":"h264","pix_fmt":"yuv420p"}]}`, 0},
+	}
+
+	for _, tc := range cases {
+		t.Run(tc.name, func(t *testing.T) {
+			info, err := parseMediaCodecs([]byte(tc.probe))
+			if err != nil {
+				t.Fatalf("unexpected error: %v", err)
+			}
+			if info.BitRate != tc.want {
+				t.Errorf("BitRate = %d, want %d", info.BitRate, tc.want)
+			}
+		})
+	}
+}

+ 84 - 0
src/mod/media/transcoder/quality.go

@@ -0,0 +1,84 @@
+package transcoder
+
+/*
+	quality.go
+
+	Output quality presets for the video transcoder.
+
+	The player offers the familiar 360p to 1080p ladder. Each step is a bounding
+	box the picture is fitted into plus a bitrate ceiling, so choosing a lower
+	quality really does cost less bandwidth rather than only fewer pixels. The
+	source resolution (an empty resolution) keeps the encoder's own defaults,
+	which is how every transcode behaved before the ladder existed.
+*/
+
+import (
+	"errors"
+	"fmt"
+	"strings"
+)
+
+type qualityPreset struct {
+	long    int // long side of the bounding box, in pixels
+	short   int // short side of the bounding box, in pixels
+	maxRate int // peak video bitrate, in kbit/s
+}
+
+var qualityPresets = map[TranscodeOutputResolution]qualityPreset{
+	TranscodeResolution_360p:  {long: 640, short: 360, maxRate: 800},
+	TranscodeResolution_480p:  {long: 854, short: 480, maxRate: 1400},
+	TranscodeResolution_720p:  {long: 1280, short: 720, maxRate: 2800},
+	TranscodeResolution_1080p: {long: 1920, short: 1080, maxRate: 5000},
+}
+
+// ParseTranscodeResolution maps a request parameter onto a known resolution.
+// Anything unrecognised means the source resolution, matching the behaviour the
+// transcode endpoints have always had for an unknown value.
+func ParseTranscodeResolution(value string) TranscodeOutputResolution {
+	resolution := TranscodeOutputResolution(strings.ToLower(strings.TrimSpace(value)))
+	if _, ok := qualityPresets[resolution]; ok {
+		return resolution
+	}
+	return TranscodeResolution_original
+}
+
+// resolutionScaleFilter returns the ffmpeg scale filter for a resolution, or ""
+// for the source resolution.
+//
+// The picture is fitted into the preset's box turned to match the source, so a
+// portrait clip at 720p comes out 720 wide rather than 720 tall, and a 2.4:1
+// film at 1080p keeps its full 1920 width. It is never enlarged, and both sides
+// are rounded down to even numbers, which yuv420p requires (libx264 rejects an
+// odd width outright). This is spelt out as expressions rather than with
+// force_original_aspect_ratio / force_divisible_by because the latter needs
+// ffmpeg 4.3, newer than several distributions still ship.
+func resolutionScaleFilter(resolution TranscodeOutputResolution) (string, error) {
+	if resolution == TranscodeResolution_original {
+		return "", nil
+	}
+	preset, ok := qualityPresets[resolution]
+	if !ok {
+		return "", errors.New("invalid resolution parameter")
+	}
+	factor := fmt.Sprintf("min(1,min(%d/max(iw,ih),%d/min(iw,ih)))", preset.long, preset.short)
+	return fmt.Sprintf("scale=w='trunc(%s*iw/2)*2':h='trunc(%s*ih/2)*2'", factor, factor), nil
+}
+
+// rateControlArgs caps the video bitrate of a resized transcode; the source
+// resolution gets none and keeps the encoder defaults.
+//
+// libx264 stays on constant quality and only falls back to the ceiling where a
+// scene needs more than it allows. Hardware encoders share no common quality
+// mode, so they get a target bitrate under the same ceiling instead.
+func rateControlArgs(resolution TranscodeOutputResolution, hardware bool) []string {
+	preset, ok := qualityPresets[resolution]
+	if !ok {
+		return nil
+	}
+	maxRate := fmt.Sprintf("%dk", preset.maxRate)
+	bufSize := fmt.Sprintf("%dk", preset.maxRate*2)
+	if hardware {
+		return []string{"-b:v", fmt.Sprintf("%dk", preset.maxRate*3/4), "-maxrate", maxRate, "-bufsize", bufSize}
+	}
+	return []string{"-crf", "23", "-maxrate", maxRate, "-bufsize", bufSize}
+}

+ 150 - 0
src/mod/media/transcoder/quality_test.go

@@ -0,0 +1,150 @@
+package transcoder
+
+import (
+	"os/exec"
+	"path/filepath"
+	"strings"
+	"testing"
+)
+
+// TestParseTranscodeResolution covers the request parameter mapping, including
+// the fall back to the source resolution for anything unknown.
+func TestParseTranscodeResolution(t *testing.T) {
+	cases := []struct {
+		value string
+		want  TranscodeOutputResolution
+	}{
+		{"360p", TranscodeResolution_360p},
+		{"480p", TranscodeResolution_480p},
+		{"720p", TranscodeResolution_720p},
+		{"1080p", TranscodeResolution_1080p},
+		{" 720P ", TranscodeResolution_720p},
+		{"", TranscodeResolution_original},
+		{"original", TranscodeResolution_original},
+		{"1280p", TranscodeResolution_original},
+		{"240p", TranscodeResolution_original},
+		{"banana", TranscodeResolution_original},
+	}
+
+	for _, tc := range cases {
+		t.Run(tc.value, func(t *testing.T) {
+			if got := ParseTranscodeResolution(tc.value); got != tc.want {
+				t.Errorf("ParseTranscodeResolution(%q) = %q, want %q", tc.value, got, tc.want)
+			}
+		})
+	}
+}
+
+// TestResolutionScaleFilter covers the shared filter used by both the MP4 and
+// the HLS path, including the rejection that guards the endpoint.
+func TestResolutionScaleFilter(t *testing.T) {
+	cases := []struct {
+		resolution TranscodeOutputResolution
+		want       string
+		wantErr    bool
+	}{
+		{TranscodeResolution_original, "", false},
+		{TranscodeResolution_360p, "min(1,min(640/max(iw,ih),360/min(iw,ih)))", false},
+		{TranscodeResolution_1080p, "min(1,min(1920/max(iw,ih),1080/min(iw,ih)))", false},
+		{"banana", "", true},
+	}
+
+	for _, tc := range cases {
+		t.Run(string(tc.resolution), func(t *testing.T) {
+			got, err := resolutionScaleFilter(tc.resolution)
+			if tc.wantErr {
+				if err == nil {
+					t.Fatalf("resolutionScaleFilter(%q) returned no error, want one", tc.resolution)
+				}
+				return
+			}
+			if err != nil {
+				t.Fatalf("resolutionScaleFilter(%q) returned error: %v", tc.resolution, err)
+			}
+			if tc.want == "" {
+				if got != "" {
+					t.Errorf("resolutionScaleFilter(%q) = %q, want no filter", tc.resolution, got)
+				}
+				return
+			}
+			if !strings.HasPrefix(got, "scale=") || !strings.Contains(got, tc.want) {
+				t.Errorf("resolutionScaleFilter(%q) = %q, want a scale filter using %q", tc.resolution, got, tc.want)
+			}
+		})
+	}
+}
+
+// TestResolutionScaleFilterOutput runs the filter through ffmpeg to check the
+// sizes it produces: fitted to the box, turned for portrait sources, never
+// enlarged and always even. Skipped where ffmpeg is not installed.
+func TestResolutionScaleFilterOutput(t *testing.T) {
+	if _, err := exec.LookPath("ffmpeg"); err != nil {
+		t.Skip("ffmpeg not installed")
+	}
+	if _, err := exec.LookPath("ffprobe"); err != nil {
+		t.Skip("ffprobe not installed")
+	}
+
+	cases := []struct {
+		name       string
+		source     string
+		resolution TranscodeOutputResolution
+		want       string
+	}{
+		{"widescreen down", "1920x1080", TranscodeResolution_720p, "1280,720"},
+		{"scope film keeps width", "1920x800", TranscodeResolution_1080p, "1920,800"},
+		{"scope film down", "1920x800", TranscodeResolution_720p, "1280,532"},
+		{"portrait", "1080x1920", TranscodeResolution_720p, "720,1280"},
+		{"four by three", "1440x1080", TranscodeResolution_480p, "640,480"},
+		{"never upscales", "720x480", TranscodeResolution_1080p, "720,480"},
+		{"odd width made even", "853x480", TranscodeResolution_480p, "852,480"},
+	}
+
+	for _, tc := range cases {
+		t.Run(tc.name, func(t *testing.T) {
+			scale, err := resolutionScaleFilter(tc.resolution)
+			if err != nil {
+				t.Fatalf("resolutionScaleFilter(%q) returned error: %v", tc.resolution, err)
+			}
+			out := filepath.Join(t.TempDir(), "out.mp4")
+			encode := exec.Command("ffmpeg", "-v", "error",
+				"-f", "lavfi", "-i", "color=c=black:s="+tc.source+":d=0.1",
+				"-vf", scale, "-frames:v", "1", "-vcodec", "libx264", "-pix_fmt", "yuv420p", "-y", out)
+			if output, err := encode.CombinedOutput(); err != nil {
+				t.Fatalf("ffmpeg failed: %v\n%s", err, output)
+			}
+			probe, err := exec.Command("ffprobe", "-v", "quiet", "-select_streams", "v:0",
+				"-show_entries", "stream=width,height", "-of", "csv=p=0", out).Output()
+			if err != nil {
+				t.Fatalf("ffprobe failed: %v", err)
+			}
+			if got := strings.TrimSpace(string(probe)); got != tc.want {
+				t.Errorf("%s at %s = %s, want %s", tc.source, tc.resolution, got, tc.want)
+			}
+		})
+	}
+}
+
+// TestRateControlArgs checks the bitrate ceiling each path gets.
+func TestRateControlArgs(t *testing.T) {
+	cases := []struct {
+		name       string
+		resolution TranscodeOutputResolution
+		hardware   bool
+		want       string
+	}{
+		{"original software", TranscodeResolution_original, false, ""},
+		{"original hardware", TranscodeResolution_original, true, ""},
+		{"480p software", TranscodeResolution_480p, false, "-crf 23 -maxrate 1400k -bufsize 2800k"},
+		{"720p hardware", TranscodeResolution_720p, true, "-b:v 2100k -maxrate 2800k -bufsize 5600k"},
+	}
+
+	for _, tc := range cases {
+		t.Run(tc.name, func(t *testing.T) {
+			got := strings.Join(rateControlArgs(tc.resolution, tc.hardware), " ")
+			if got != tc.want {
+				t.Errorf("rateControlArgs(%q, %v) = %q, want %q", tc.resolution, tc.hardware, got, tc.want)
+			}
+		})
+	}
+}

+ 8 - 6
src/mod/media/transcoder/transcoder.go

@@ -21,10 +21,12 @@ import (
 
 type TranscodeOutputResolution string
 
+// Output resolutions offered by the player; see quality.go for what each means.
 const (
 	TranscodeResolution_360p     TranscodeOutputResolution = "360p"
+	TranscodeResolution_480p     TranscodeOutputResolution = "480p"
 	TranscodeResolution_720p     TranscodeOutputResolution = "720p"
-	TranscodeResolution_1080p    TranscodeOutputResolution = "1280p"
+	TranscodeResolution_1080p    TranscodeOutputResolution = "1080p"
 	TranscodeResolution_original TranscodeOutputResolution = ""
 )
 
@@ -38,7 +40,7 @@ func TranscodeAndStream(w http.ResponseWriter, r *http.Request, inputFile string
 	// Build the FFmpeg command based on the resolution parameter
 	var cmd *exec.Cmd
 
-	height, err := resolutionHeight(resolution)
+	scale, err := resolutionScaleFilter(resolution)
 	if err != nil {
 		http.Error(w, "Invalid resolution parameter", http.StatusBadRequest)
 		return
@@ -53,18 +55,18 @@ func TranscodeAndStream(w http.ResponseWriter, r *http.Request, inputFile string
 	var vf string
 	if hw := getHWEncoderProfile(); hw != nil {
 		preInputArgs = append(append([]string{}, hw.PreInput...), preInputArgs...)
-		vf = hw.ScaleFilter(height)
+		vf = hw.ScaleFilter(scale)
 		videoCodecArgs = append([]string{"-vcodec", hw.Codec}, hw.EncodeArgs...)
+		videoCodecArgs = append(videoCodecArgs, rateControlArgs(resolution, true)...)
 	} else {
-		if height != "" {
-			vf = "scale=-1:" + height
-		}
+		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}

+ 7 - 6
src/mod/media/transcoder/transcoder_test.go

@@ -32,12 +32,12 @@ func TestTranscodeOutputResolution_Constants(t *testing.T) {
 	}
 }
 
-// TestTranscodeResolution_1080pConstant verifies the 1080p constant value.
-// (The source defines it as "1280p" – we test the actual defined value.)
+// TestTranscodeResolution_1080pConstant verifies the 1080p constant value. It
+// once read "1280p", which resolutionScaleFilter rejected, so a 1080p request
+// failed with 400.
 func TestTranscodeResolution_1080pConstant(t *testing.T) {
-	// The constant is intentionally defined as "1280p" in the source file.
-	if string(TranscodeResolution_1080p) != "1280p" {
-		t.Errorf("expected '1280p', got '%s'", TranscodeResolution_1080p)
+	if string(TranscodeResolution_1080p) != "1080p" {
+		t.Errorf("expected '1080p', got '%s'", TranscodeResolution_1080p)
 	}
 }
 
@@ -83,8 +83,9 @@ func TestTranscodeAndStream_ResolutionSwitch(t *testing.T) {
 		res  TranscodeOutputResolution
 	}{
 		{"360p", TranscodeResolution_360p},
+		{"480p", TranscodeResolution_480p},
 		{"720p", TranscodeResolution_720p},
-		{"1080p", "1080p"}, // use literal since the constant has wrong value "1280p"
+		{"1080p", TranscodeResolution_1080p},
 		{"original", TranscodeResolution_original},
 	}
 

+ 423 - 20
src/web/Movie/backend/common.js

@@ -97,6 +97,371 @@ function usingHLS() {
     return isWebKitClient();
 }
 
+// ── Streaming quality ────────────────────────────────────────────────────────
+// The resolution a transcode is scaled to, on the familiar 360p–1080p ladder.
+// Each step also caps the bitrate on the server (kbps below mirrors the
+// ceilings in mod/media/transcoder/quality.go), so a lower step is what to pick
+// on a slow link. "original" keeps the source resolution and plays the file
+// directly whenever the browser can; any other step always transcodes. "auto"
+// moves between those on its own, see AutoQualityController below.
+//
+// Steps are boxes (long × short side) rather than heights so that a portrait
+// clip or a 2.4:1 film is judged the way the server will scale it. A step
+// larger than the source is not offered: the server never enlarges, so it
+// would only cost a transcode for the same picture.
+var STREAM_QUALITY_KEY = "movie_stream_quality";
+var STREAM_QUALITIES = [
+    { id: "auto",     label: "Auto" },
+    { id: "original", label: "Original" },
+    { id: "1080p", label: "1080p", long: 1920, short: 1080, kbps: 5000 },
+    { id: "720p",  label: "720p",  long: 1280, short: 720,  kbps: 2800 },
+    { id: "480p",  label: "480p",  long: 854,  short: 480,  kbps: 1400 },
+    { id: "360p",  label: "360p",  long: 640,  short: 360,  kbps: 800 }
+];
+
+function streamQualityStep(id) {
+    for (var i = 0; i < STREAM_QUALITIES.length; i++) {
+        if (STREAM_QUALITIES[i].id === id) { return STREAM_QUALITIES[i]; }
+    }
+    return null;
+}
+
+function getStreamQuality() {
+    var quality = localStorage.getItem(STREAM_QUALITY_KEY);
+    return streamQualityStep(quality) ? quality : "original";
+}
+
+function setStreamQuality(quality) {
+    if (!streamQualityStep(quality)) { quality = "original"; }
+    localStorage.setItem(STREAM_QUALITY_KEY, quality);
+}
+
+// Whether a step is worth offering for a source described by a probe result.
+// Without one (no ffmpeg, a remote file system, probe still running) every step
+// is offered; the server will not enlarge the picture whichever is chosen.
+function streamQualityAvailable(id, info) {
+    var step = streamQualityStep(id);
+    if (!step) { return false; }
+    if (!step.long || !info || !(info.width > 0) || !(info.height > 0)) { return true; }
+    var long  = Math.max(info.width, info.height);
+    var short = Math.min(info.width, info.height);
+    return long >= step.long || short >= step.short;
+}
+
+// The step a given file actually plays at: the viewer's choice, the step Auto
+// is on, or the source resolution when the choice is larger than the file.
+function effectiveStreamQuality(filepath) {
+    var quality = getStreamQuality();
+    if (quality === "auto") { return autoQualityStep(filepath); }
+    if (!streamQualityAvailable(quality, cachedMediaInfo(filepath))) { return "original"; }
+    return quality;
+}
+
+// The &res= parameter for a transcode of this file, or "" at source resolution.
+function streamQualityParam(filepath) {
+    var quality = effectiveStreamQuality(filepath);
+    return quality === "original" ? "" : "&res=" + quality;
+}
+
+// ── Auto quality ─────────────────────────────────────────────────────────────
+// Auto judges the connection from the video buffer alone; nothing is
+// downloaded just to measure it. While the browser is still filling its buffer
+// it is downloading as fast as it can, so how many seconds of video arrive per
+// second of wall time (the fill rate) says how much faster than real time the
+// current step can be delivered. Multiplied by that step's bitrate it gives an
+// estimate of what the link carries. That covers a slow server too: an HLS
+// transcode that cannot keep up fills slowly, and a smaller step is also
+// cheaper to encode.
+//
+// It only holds while the browser really is downloading. Playing a file
+// directly, Chrome keeps a fixed number of bytes ahead and rests in between,
+// which it announces with a 'suspend' event, so any measurement spanning a rest
+// is thrown away and a resting browser is never taken for one running dry. (The
+// Media Source player never rests below 30 seconds ahead, and the element does
+// not report suspends for it.)
+//
+// Once the buffer is full the browser only tops it up, so there is nothing
+// left to measure and an old estimate says nothing about a link that has since
+// got faster. A buffer that stays full is then the evidence instead: after a
+// long stall-free stretch Auto tries the next step up, and the fresh stream's
+// own fill rate shows straight away whether it holds.
+//
+// Every change of step restarts the stream, so Auto is deliberately slow to
+// move: down at once on real rebuffering or a buffer running dry, up only one
+// step at a time, and a step that did not hold is left alone twice as long as
+// the last time before it is tried again. Bitrates are the server's ceilings,
+// so estimates are comparative rather than an exact measure of the line.
+var AUTO_QUALITY_ESTIMATE_KEY = "movie_auto_quality_kbps";
+var AUTO_QUALITY_LADDER  = ["original", "1080p", "720p", "480p", "360p"];   // best first
+var AUTO_TICK_MS         = 1000;
+var AUTO_FILL_CEILING    = 15;     // seconds ahead below which every browser keeps downloading
+var AUTO_SAMPLE_SECONDS  = 8;      // window a fill rate is measured over: two HLS segments, which arrive whole
+var AUTO_LOW_BUFFER      = 6;      // seconds ahead that count as running dry
+var AUTO_STALL_MS        = 2000;   // a rebuffer at least this long steps down
+var AUTO_SEEK_GRACE_MS   = 3000;   // waiting right after a seek is the seek, not the link
+var AUTO_SETTLE_MS       = 8000;   // start-up of a fresh stream is not judged
+var AUTO_COOLDOWN_MS     = 10000;  // least time between two changes
+var AUTO_UP_HOLD_MS      = 45000;  // stall-free time before trying a better step
+var AUTO_PROBE_MS        = 60000;  // a step up undone within this did not hold
+var AUTO_RETRY_MAX_MS    = 600000; // longest a step that did not hold is left alone
+var AUTO_ESTIMATE_FRESH_MS = 60000; // an estimate older than this no longer vetoes a step up
+var AUTO_UP_MARGIN       = 1.5;    // headroom wanted over the next step's bitrate
+var AUTO_START_MARGIN    = 1.3;    // headroom wanted when choosing where a file starts
+var AUTO_DOWN_MARGIN     = 0.8;    // share of the estimate a lower step may use
+
+var _autoQuality = { filepath: null, step: "original" };
+
+function autoQualityEstimate() {
+    var kbps = parseFloat(localStorage.getItem(AUTO_QUALITY_ESTIMATE_KEY));
+    return kbps > 0 ? kbps : 0;
+}
+
+// Steps Auto may use for a file, best first.
+function autoQualityLadder(info) {
+    return AUTO_QUALITY_LADDER.filter(function (id) { return streamQualityAvailable(id, info); });
+}
+
+// Bitrate of a step in kbit/s. The scaled steps have the server's ceiling; the
+// source resolution costs what the file does when played as it is, and has no
+// ceiling at all when transcoded, where superfast x264 runs above the scaled
+// step of the same size.
+function streamStepKbps(id, info, transcoded) {
+    var step = streamQualityStep(id);
+    if (step && step.kbps) { return step.kbps; }
+    if (!transcoded && info && info.bitRate > 0) { return info.bitRate / 1000; }
+    var ladder = autoQualityLadder(info);
+    var sameSize = ladder.length > 1 ? streamQualityStep(ladder[1]) : null;
+    return sameSize ? sameSize.kbps * 1.5 : 8000;
+}
+
+// The step Auto plays a file at. A new file starts at the best step the last
+// estimate can carry, or at Original when there is no estimate yet. The choice
+// is only fixed once the file's probe is in, since the steps depend on its size.
+function autoQualityStep(filepath) {
+    if (_autoQuality.filepath === filepath) { return _autoQuality.step; }
+    var info   = cachedMediaInfo(filepath);
+    var ladder = autoQualityLadder(info);
+    var estimate = autoQualityEstimate();
+    var step = ladder[0];
+    if (estimate > 0) {
+        var transcoded = !(info && info.directPlay);
+        step = ladder[ladder.length - 1];
+        for (var i = 0; i < ladder.length; i++) {
+            if (streamStepKbps(ladder[i], info, transcoded) * AUTO_START_MARGIN <= estimate) {
+                step = ladder[i];
+                break;
+            }
+        }
+    }
+    if (mediaInfoProbed(filepath)) { _autoQuality = { filepath: filepath, step: step }; }
+    return step;
+}
+
+function setAutoQualityStep(filepath, step) {
+    _autoQuality = { filepath: filepath, step: step };
+}
+
+// Watches one <video> element and moves Auto between steps. hooks:
+//   filepath()     the file playing, or null when Auto should keep still
+//                  (nothing playing, or the picture is on a cast receiver)
+//   isTranscoded() whether the element is playing a transcode
+//   onSwitch(step) re-open the current file at the step just chosen
+function AutoQualityController(videoEl, hooks) {
+    this.video = videoEl;
+    this.hooks = hooks;
+    this.window = null;          // fill-rate measurement in progress
+    this.rate = null;            // fill rate of the current stream, averaged
+    this.estimateAt = 0;         // when this player last measured the link
+    this.streamStartedAt = Date.now();
+    this.lastSwitchAt = 0;
+    this.lastSeekAt = 0;
+    this.lastStallAt = 0;
+    this.stallStart = 0;
+    this.hasPlayed = false;
+    this.lastProgressAt = 0;
+    this.lastSuspendAt = 0;
+    this.file = null;
+    this.probe = null;           // the last step up, while it has yet to hold
+    this.blocked = {};           // step -> { until, hold } for steps that did not hold
+
+    var self = this;
+    videoEl.addEventListener("loadstart", function () {
+        // A new stream: a seek-by-reload, a new episode or a change of step
+        self.streamStartedAt = Date.now();
+        self.window = null;
+        self.rate = null;
+        self.stallStart = 0;
+        self.hasPlayed = false;
+    });
+    videoEl.addEventListener("progress", function () { self.lastProgressAt = Date.now(); });
+    videoEl.addEventListener("suspend", function () { self.lastSuspendAt = Date.now(); });
+    videoEl.addEventListener("seeking", function () {
+        self.lastSeekAt = Date.now();
+        self.window = null;
+    });
+    videoEl.addEventListener("waiting", function () {
+        if (!self.hasPlayed || videoEl.paused) { return; }
+        if (Date.now() - self.lastSeekAt < AUTO_SEEK_GRACE_MS) { return; }
+        if (!self.stallStart) { self.stallStart = Date.now(); }
+    });
+    videoEl.addEventListener("playing", function () {
+        self.hasPlayed = true;
+        if (self.stallStart && Date.now() - self.stallStart >= AUTO_STALL_MS) {
+            self.lastStallAt = Date.now();
+        }
+        self.stallStart = 0;
+    });
+    this.timer = setInterval(function () { self.tick(); }, AUTO_TICK_MS);
+}
+
+// End of the buffered range under the playhead, and how far ahead it reaches.
+AutoQualityController.prototype._bufferAhead = function () {
+    var buffered = this.video.buffered;
+    var time = this.video.currentTime;
+    for (var i = 0; i < buffered.length; i++) {
+        if (buffered.start(i) <= time + 0.25 && time < buffered.end(i)) {
+            return { end: buffered.end(i), ahead: buffered.end(i) - time };
+        }
+    }
+    return { end: time, ahead: 0 };
+};
+
+AutoQualityController.prototype._currentKbps = function (filepath) {
+    return streamStepKbps(autoQualityStep(filepath), cachedMediaInfo(filepath), this.hooks.isTranscoded());
+};
+
+AutoQualityController.prototype._recordRate = function (rate, filepath) {
+    rate = Math.max(0, Math.min(rate, 50));
+    // Averaged within a stream: a window still catches one segment more or
+    // less than the link really delivered
+    this.rate = this.rate === null ? rate : (this.rate + rate) / 2;
+    this.estimateAt = Date.now();
+    var sample = this.rate * this._currentKbps(filepath);
+    var previous = autoQualityEstimate();
+    var estimate = previous > 0 ? previous * 0.7 + sample * 0.3 : sample;
+    try { localStorage.setItem(AUTO_QUALITY_ESTIMATE_KEY, String(Math.round(estimate))); } catch (e) {}
+};
+
+// Whether the browser has stopped downloading because it has enough. It fires
+// 'progress' and then 'suspend' at the end of each burst, hence the >=.
+AutoQualityController.prototype._resting = function () {
+    return this.lastSuspendAt > 0 && this.lastSuspendAt >= this.lastProgressAt;
+};
+
+// Measure the fill rate, but only while the browser is certainly downloading:
+// the buffer is short and it has not rested since the window opened. A window
+// spanning a rest would read as a slow link.
+AutoQualityController.prototype._sampleFill = function (now, buffer, filepath) {
+    var w = this.window;
+    if (w && this.lastSuspendAt >= w.t) {
+        w = this.window = null;
+    }
+    if (buffer.ahead >= AUTO_FILL_CEILING) {
+        // The browser may rest from here on. A window cut short by getting
+        // here is not used either: over a second or two, whether the last
+        // segment happened to land inside it decides the reading. A link that
+        // fills this fast is not what holds Auto back anyway.
+        this.window = null;
+        return;
+    }
+    if (!w || buffer.end < w.end - 0.5) {
+        this.window = this._resting() ? null : { t: now, end: buffer.end };
+        return;
+    }
+    var seconds = (now - w.t) / 1000;
+    if (seconds >= AUTO_SAMPLE_SECONDS) {
+        this._recordRate((buffer.end - w.end) / seconds, filepath);
+        this.window = { t: now, end: buffer.end };
+    }
+};
+
+AutoQualityController.prototype._switch = function (filepath, step, now) {
+    var up = AUTO_QUALITY_LADDER.indexOf(step) < AUTO_QUALITY_LADDER.indexOf(autoQualityStep(filepath));
+    if (!up && this.probe && now - this.probe.at < AUTO_PROBE_MS) {
+        // The last step up did not hold: leave it alone twice as long as before
+        var last = this.blocked[this.probe.step];
+        var hold = last ? Math.min(last.hold * 2, AUTO_RETRY_MAX_MS) : 2 * AUTO_UP_HOLD_MS;
+        this.blocked[this.probe.step] = { until: now + hold, hold: hold };
+    }
+    this.probe = up ? { step: step, from: autoQualityStep(filepath), at: now } : null;
+    this.lastSwitchAt = now;
+    setAutoQualityStep(filepath, step);
+    if (typeof this.hooks.onSwitch === "function") { this.hooks.onSwitch(step); }
+};
+
+AutoQualityController.prototype.tick = function () {
+    var video = this.video;
+    var filepath = this.hooks.filepath();
+    if (getStreamQuality() !== "auto" || !filepath || !mediaInfoProbed(filepath)) {
+        this.window = null;
+        return;
+    }
+    // A paused element may stop downloading, which says nothing about the link
+    if (video.paused || video.seeking || video.ended) {
+        this.window = null;
+        return;
+    }
+
+    // What a step costs depends on the file, so what failed on the last one
+    // says nothing about this one
+    if (this.file !== filepath) {
+        this.file = filepath;
+        this.probe = null;
+        this.blocked = {};
+    }
+
+    var now = Date.now();
+    var buffer = this._bufferAhead();
+    this._sampleFill(now, buffer, filepath);
+    if (now - this.streamStartedAt < AUTO_SETTLE_MS || now - this.lastSwitchAt < AUTO_COOLDOWN_MS) { return; }
+
+    var info    = cachedMediaInfo(filepath);
+    var ladder  = autoQualityLadder(info);
+    var current = Math.max(0, ladder.indexOf(autoQualityStep(filepath)));
+
+    var stalled  = this.stallStart && now - this.stallStart >= AUTO_STALL_MS;
+    // Running dry: little left, a recent reading below real time, and the
+    // browser still trying rather than resting on what it has
+    var draining = buffer.ahead < AUTO_LOW_BUFFER && this.rate !== null && this.rate < 0.9 &&
+        now - this.estimateAt < 2 * AUTO_SAMPLE_SECONDS * 1000 && !this._resting();
+    if ((stalled || draining) && current < ladder.length - 1) {
+        // A step up that did not hold goes back to where it came from, as long
+        // as the link has not dropped below that too. Otherwise, with a rate
+        // measured on this stream, go straight to a step it can carry; without
+        // one, a single step is the safe guess.
+        var throughput = this.rate !== null ? this.rate * this._currentKbps(filepath) : null;
+        var from = this.probe && now - this.probe.at < AUTO_PROBE_MS ? ladder.indexOf(this.probe.from) : -1;
+        var target = current + 1;
+        if (from > current && (throughput === null || throughput >= streamStepKbps(ladder[from], info, true))) {
+            target = from;
+        } else if (throughput !== null) {
+            var budget = throughput * AUTO_DOWN_MARGIN;
+            while (target < ladder.length - 1 && streamStepKbps(ladder[target], info, true) > budget) { target++; }
+        }
+        if (stalled) { this.lastStallAt = now; }
+        this.stallStart = 0;
+        this._switch(filepath, ladder[target], now);
+        return;
+    }
+
+    if (current > 0 && !this.stallStart &&
+            now - Math.max(this.lastStallAt, this.lastSwitchAt, this.streamStartedAt) >= AUTO_UP_HOLD_MS &&
+            buffer.ahead >= AUTO_FILL_CEILING) {
+        // A full buffer kept full shows headroom. A recent measurement of this
+        // stream says whether it is enough for the next step; without one, try
+        // it. Original played as it is costs the file's own bitrate, otherwise
+        // it is another transcode.
+        var next = ladder[current - 1];
+        var retry = this.blocked[next];
+        if (retry && now < retry.until) { return; }
+        var nextKbps = streamStepKbps(next, info, !(info && info.directPlay));
+        var fresh = this.rate !== null && now - this.estimateAt < AUTO_ESTIMATE_FRESH_MS;
+        if (!fresh || this.rate * this._currentKbps(filepath) >= nextKbps * AUTO_UP_MARGIN) {
+            this._switch(filepath, next, now);
+        }
+    }
+};
+
 // WebKit plays HLS natively. Everywhere else it is played through Media Source
 // Extensions: hls.js if someone has vendored it into web/script/, otherwise the
 // built-in MSE player in web/script/hlsmse.js, which is enough because the
@@ -123,35 +488,71 @@ function hlsPlaybackSupported(videoEl) {
 // a bare decode error (NS_ERROR_DOM_MEDIA_METADATA_ERR on Firefox) instead of
 // being transcoded. So the server is asked what the file really contains.
 var WEB_PLAYABLE_EXTENSIONS = ["mp4", "webm", "ogg", "m4v"];
-var _codecProbeCache = {};
+var _mediaInfoCache = {};
 
 function isWebPlayableExtension(ext) {
     return WEB_PLAYABLE_EXTENSIONS.indexOf(String(ext || "").toLowerCase()) !== -1;
 }
 
-// Decide whether a file can be handed to the browser as-is. Calls back with
-// true for direct play, false to transcode.
-//
-// Only web-native containers are probed: anything else is transcoded regardless,
-// so there is nothing to learn. Results are cached per file, making repeat plays
-// and episode changes free.
-function resolveDirectPlay(filepath, ext, callback) {
-    if (!isWebPlayableExtension(ext)) { callback(false); return; }
-    if (Object.prototype.hasOwnProperty.call(_codecProbeCache, filepath)) {
-        callback(_codecProbeCache[filepath]);
+// Ask the server what a file contains (codecs, picture size). Calls back with
+// the probe result, or null when there is none to be had (no ffmpeg, a remote
+// file system). Answers are cached per file, making repeat plays and episode
+// changes free.
+function probeMediaInfo(filepath, callback) {
+    if (mediaInfoProbed(filepath)) {
+        callback(_mediaInfoCache[filepath]);
         return;
     }
 
-    fetch(PROBE_API + "?file=" + encodeURIComponent(filepath), { credentials: "same-origin" })
-        .then(function (r) { return r.json(); })
+    // Without ffmpeg the probe route does not exist and the request falls
+    // through to the plain media endpoint, which would start sending the whole
+    // film. Anything that is not JSON is cut off at the headers.
+    var controller = window.AbortController ? new AbortController() : null;
+    fetch(PROBE_API + "?file=" + encodeURIComponent(filepath),
+          { credentials: "same-origin", signal: controller ? controller.signal : undefined })
+        .then(function (r) {
+            if ((r.headers.get("Content-Type") || "").indexOf("json") === -1) {
+                if (controller) { controller.abort(); }
+                return null;
+            }
+            return r.json();
+        })
         .then(function (info) {
-            // A probe error (no ffmpeg, remote file system) leaves the old
-            // extension-based behaviour in place rather than blocking playback.
-            var direct = (info && !info.error) ? !!info.directPlay : true;
-            _codecProbeCache[filepath] = direct;
-            callback(direct);
+            info = (info && !info.error) ? info : null;
+            _mediaInfoCache[filepath] = info;
+            callback(info);
         })
-        .catch(function () { callback(true); });
+        .catch(function () {
+            // Settled as "nothing known", like a probe error, so Auto can fix
+            // the file's starting step instead of re-deciding it on every call.
+            _mediaInfoCache[filepath] = null;
+            callback(null);
+        });
+}
+
+function cachedMediaInfo(filepath) {
+    return _mediaInfoCache[filepath] || null;
+}
+
+// Whether the probe for a file has answered (with a result or with nothing).
+function mediaInfoProbed(filepath) {
+    return Object.prototype.hasOwnProperty.call(_mediaInfoCache, filepath);
+}
+
+// Decide whether a file can be handed to the browser as-is. Calls back with
+// true for direct play, false to transcode.
+//
+// Every file is probed, not only web-native containers: the picture size is
+// what decides which quality steps apply, and a step below the source always
+// means a transcode, however playable the file is.
+function resolveDirectPlay(filepath, ext, callback) {
+    probeMediaInfo(filepath, function (info) {
+        if (effectiveStreamQuality(filepath) !== "original") { callback(false); return; }
+        if (!isWebPlayableExtension(ext)) { callback(false); return; }
+        // A probe error (no ffmpeg, remote file system) leaves the old
+        // extension-based behaviour in place rather than blocking playback.
+        callback(info ? !!info.directPlay : true);
+    });
 }
 
 // Safety net for direct playback: the probe can still be wrong for a browser
@@ -178,7 +579,8 @@ function clearDirectPlaybackWatch(videoEl) {
     }
 }
 
-// Build the streaming URL for a transcoded file, honouring the current mode.
+// Build the streaming URL for a transcoded file, honouring the current mode
+// and quality.
 // startSeconds restarts the transcode at an offset; the resulting stream always
 // begins at zero, so callers track the offset separately.
 function transcodeStreamURL(filepath, startSeconds) {
@@ -188,6 +590,7 @@ function transcodeStreamURL(filepath, startSeconds) {
     if (startSeconds && startSeconds > 0.001) {
         url += "&start=" + startSeconds.toFixed(3);
     }
+    url += streamQualityParam(filepath);
     // Only HLS needs it, and the MP4 response is cacheable — a per-load
     // parameter would defeat that cache for nothing.
     if (hls) { url += "&client=" + MOVIE_CLIENT_ID; }

+ 116 - 1
src/web/Movie/embedded.html

@@ -504,6 +504,8 @@
         }
         .speed-btn:hover  { color: var(--text); }
         .speed-btn.active { background: var(--accent); color: #fff; font-weight: 600; }
+        .quality-grid { display: grid; grid-template-columns: repeat(3, 1fr); gap: 4px; }
+        .set-head-note { margin-left: auto; text-transform: none; letter-spacing: 0; font-weight: 500; }
 
         .set-link {
             display: flex; align-items: center; gap: 9px;
@@ -671,6 +673,17 @@
                 <button class="set-seg-btn"        data-stream="hls">HLS</button>
             </div>
         </div>
+        <div class="set-section">
+            <div class="set-head"><img src="img/icons/quality_white.svg" alt="">Quality<span class="set-head-note" id="set-quality-note"></span></div>
+            <div class="quality-grid" id="set-quality-grid">
+                <button class="speed-btn" data-quality="auto">Auto</button>
+                <button class="speed-btn active" data-quality="original">Original</button>
+                <button class="speed-btn" data-quality="1080p">1080p</button>
+                <button class="speed-btn" data-quality="720p">720p</button>
+                <button class="speed-btn" data-quality="480p">480p</button>
+                <button class="speed-btn" data-quality="360p">360p</button>
+            </div>
+        </div>
         <div class="set-section" style="padding-left:0;padding-right:0;padding-bottom:2px;">
             <div class="set-link" id="set-video-props">
                 <img src="img/icons/menu_white.svg" alt="">Video properties
@@ -838,6 +851,7 @@ if (files && files.length > 0) {
     // The extension only says the container might be playable; the codec inside
     // decides. An .mp4 holding HEVC or 10-bit H.264 has to be transcoded.
     resolveDirectPlay(currentFile.filepath, currentFile.ext, function (directPlay) {
+        renderStreamQuality();   // the probe now knows which steps this file allows
         beginFileStream(directPlay);
     });
 }
@@ -1566,16 +1580,105 @@ function applyStreamMode(mode, reloadCurrent) {
     // avoids starting a transcode from the beginning only to abandon it.
     var resumeAt = effectivePlaybackTime();
     var startAt  = resumeAt > 1 ? resumeAt : 0;
+    var resume   = !vid.paused;
     transcodeSeekOffset = startAt;
     if (!attachTranscodeStream(vid, transcodeStreamURL(currentFile.filepath, startAt),
             function (reason) { showToast(reason); },
-            function () { playVideo(vid); })) {
+            function () { settlePlayState(resume); })) {
         showToast('This browser cannot play the HLS stream.');
     }
 }
 
 function playerVideoElement() { return vid; }
 
+// Show the quality steps the current file allows, with the one it plays at
+// highlighted. That is the viewer's choice unless the file is smaller than it;
+// under Auto the header says which step Auto is on.
+function renderStreamQuality() {
+    var info   = currentFile ? cachedMediaInfo(currentFile.filepath) : null;
+    var chosen = getStreamQuality();
+    var active = (chosen === 'auto' || !currentFile) ? chosen : effectiveStreamQuality(currentFile.filepath);
+    $('#set-quality-grid .speed-btn').each(function () {
+        var id = String($(this).data('quality'));
+        $(this).toggle(streamQualityAvailable(id, info))
+               .toggleClass('active', id === active);
+    });
+    var note = (chosen === 'auto' && currentFile) ? streamQualityStep(effectiveStreamQuality(currentFile.filepath)) : null;
+    $('#set-quality-note').text(note ? note.label : '');
+}
+
+// Apply a quality step. Changing it mid-playback re-opens the file at the new
+// step, resuming where the viewer was.
+function applyStreamQuality(quality, reloadCurrent) {
+    var previous = currentFile ? effectiveStreamQuality(currentFile.filepath) : getStreamQuality();
+    // Auto starts from whatever is playing now rather than reloading straight away
+    if (quality === 'auto' && currentFile) { setAutoQualityStep(currentFile.filepath, previous); }
+    setStreamQuality(quality);
+    renderStreamQuality();
+
+    if (!reloadCurrent || !currentFile || previous === effectiveStreamQuality(currentFile.filepath)) { return; }
+    reopenCurrentStream(!vid.paused);
+}
+
+// Finish re-opening a stream in the state the viewer left it. The pause()
+// matters even on a paused element: it stops the newly set source from
+// starting by itself, which the element's autoplay would otherwise do.
+function settlePlayState(resume) {
+    if (resume) { playVideo(vid); } else { vid.pause(); }
+}
+
+// Re-open the file at the current position after a quality change, playing
+// again only when `resume` says it was playing. Unlike a streaming-mode change
+// this can cross between direct playback and a transcode: dropping below the
+// source size always transcodes, and returning to Original plays the file
+// as-is again when the browser can.
+function reopenCurrentStream(resume) {
+    var file     = currentFile;
+    var resumeAt = effectivePlaybackTime();
+    var startAt  = resumeAt > 1 ? resumeAt : 0;
+    // A direct stream knows its own length; a transcode is told it separately
+    var knownDuration = isTranscodedVideo ? transcodeDuration : vid.duration;
+
+    showSeekFreeze();
+    setSubtitleSeekFloor(startAt);
+    resolveDirectPlay(file.filepath, file.ext, function (directPlay) {
+        if (currentFile !== file) { return; }
+        clearDirectPlaybackWatch(vid);
+        detachTranscodeStream(vid);
+        $(vid).off('loadedmetadata.quality');   // from a switch made just before
+        isTranscodedVideo = !directPlay;
+
+        if (directPlay) {
+            transcodeSeekOffset = 0;
+            vid.src = MEDIA_API + '?file=' + encodeURIComponent(file.filepath);
+            $(vid).one('loadedmetadata.quality', function () { vid.currentTime = startAt; });
+            onDirectPlaybackFailure(vid, function () {
+                showToast('This browser cannot decode that file — switching to a transcode');
+                beginFileStream(false);
+            });
+            settlePlayState(resume);
+            return;
+        }
+
+        transcodeSeekOffset = startAt;
+        if (knownDuration > 0 && isFinite(knownDuration)) {
+            transcodeDuration = knownDuration;
+        } else {
+            fetch(ao_root + 'media/duration/?file=' + encodeURIComponent(file.filepath))
+                .then(function (r) { return r.json(); })
+                .then(function (data) {
+                    if (data.duration > 0 && currentFile === file) { transcodeDuration = data.duration; }
+                }).catch(function () {});
+        }
+        if (!attachTranscodeStream(vid, transcodeStreamURL(file.filepath, startAt),
+                function (reason) { hideSeekFreeze(); showToast(reason); },
+                function () { settlePlayState(resume); })) {
+            hideSeekFreeze();
+            showToast('This browser cannot play the transcoded stream. Switch streaming mode to MP4 in settings.');
+        }
+    });
+}
+
 // Surface the two streaming modes that cannot work on a given browser. Anything
 // that is simply working says nothing at all.
 function warnIfStreamModeUnplayable() {
@@ -1605,6 +1708,7 @@ function openSettingsPopup() {
     setPlaybackSpeed(playbackSpeed);
     setAlwaysShowVolumeBar(alwaysShowVolumeBar);
     applyStreamMode(getStreamMode(), false);
+    renderStreamQuality();
     $('#player-ctx').hide();
     closeSubtitlePopup();
     $('#settings-popup').addClass('active');
@@ -1686,6 +1790,9 @@ function initSettingsPopup() {
     $('#set-stream-seg').on('click', '.set-seg-btn', function () {
         applyStreamMode(String($(this).data('stream')), true);
     });
+    $('#set-quality-grid').on('click', '.speed-btn', function () {
+        applyStreamQuality(String($(this).data('quality')), true);
+    });
 
     $('#set-video-props').on('click', function () { closeSettingsPopup(); openVideoInfo('props'); });
 
@@ -1694,6 +1801,14 @@ function initSettingsPopup() {
     setPlaybackSpeed(playbackSpeed);
     setAlwaysShowVolumeBar(alwaysShowVolumeBar);
     applyStreamMode(getStreamMode(), false);
+    renderStreamQuality();
+
+    // Auto quality only ever moves while playing, so it always resumes
+    new AutoQualityController(vid, {
+        filepath: function () { return currentFile ? currentFile.filepath : null; },
+        isTranscoded: function () { return isTranscodedVideo; },
+        onSwitch: function () { renderStreamQuality(); reopenCurrentStream(true); }
+    });
 
     // A transcode seek replaces the media source, which resets playbackRate —
     // reapply the chosen speed every time new media is loaded.

+ 1 - 0
src/web/Movie/img/icons/quality_white.svg

@@ -0,0 +1 @@
+<svg xmlns="http://www.w3.org/2000/svg" height="24px" viewBox="0 0 24 24" width="24px" fill="#F3F3F3"><rect x="3" y="5" width="18" height="2" rx="1"/><rect x="3" y="11" width="18" height="2" rx="1"/><rect x="3" y="17" width="18" height="2" rx="1"/><rect x="13" y="3" width="3" height="6" rx="1"/><rect x="6" y="9" width="3" height="6" rx="1"/><rect x="15" y="15" width="3" height="6" rx="1"/></svg>

+ 133 - 2
src/web/Movie/index.html

@@ -1212,6 +1212,8 @@ body.always-show-volume #volume-slider { display: block; }
 }
 .speed-btn:hover  { color: var(--text); }
 .speed-btn.active { background: var(--accent); color: #fff; font-weight: 600; }
+.quality-grid { display: grid; grid-template-columns: repeat(3, 1fr); gap: 4px; }
+.set-head-note { margin-left: auto; text-transform: none; letter-spacing: 0; font-weight: 500; }
 
 .set-link {
     display: flex; align-items: center; gap: 9px;
@@ -1867,6 +1869,17 @@ img.ctx-icon { height: 16px; opacity: 0.85; display: block; }
                         <button class="set-seg-btn"        data-stream="hls">HLS</button>
                     </div>
                 </div>
+                <div class="set-section">
+                    <div class="set-head"><img src="img/icons/quality_white.svg" alt="">Quality<span class="set-head-note" id="set-quality-note"></span></div>
+                    <div class="quality-grid" id="set-quality-grid">
+                        <button class="speed-btn" data-quality="auto">Auto</button>
+                        <button class="speed-btn active" data-quality="original">Original</button>
+                        <button class="speed-btn" data-quality="1080p">1080p</button>
+                        <button class="speed-btn" data-quality="720p">720p</button>
+                        <button class="speed-btn" data-quality="480p">480p</button>
+                        <button class="speed-btn" data-quality="360p">360p</button>
+                    </div>
+                </div>
                 <div class="set-section" style="padding-left:0;padding-right:0;padding-bottom:2px;">
                     <div class="set-link" id="set-video-props">
                         <img src="img/icons/menu_white.svg" alt="">Video properties
@@ -3566,6 +3579,7 @@ function startPlayback(index) {
     // so it is routed through the same verdict.
     resolveDirectPlay(ep.filepath, ext, function (directPlay) {
         if (playingIndex !== index) { return; }   // episode changed while probing
+        renderStreamQuality();   // the probe now knows which steps this file allows
 
         if (castMode && _castConnected()) {
             // Don't load locally — avoids transcoding the same file twice.
@@ -3576,7 +3590,8 @@ function startPlayback(index) {
             _castSend('media.load', {
                 filepath: ep.filepath, name: ep.name, type: 'video',
                 src: directPlay ? MEDIA_API + '?file=' + encodeURIComponent(ep.filepath)
-                                : TRANSCODE_API + '?file=' + encodeURIComponent(ep.filepath),
+                                : TRANSCODE_API + '?file=' + encodeURIComponent(ep.filepath)
+                                  + streamQualityParam(ep.filepath),
                 startTime: 0
             });
             // Volume after load, before play — guarantees device volume overrides
@@ -4184,16 +4199,118 @@ function applyStreamMode(mode, reloadCurrent) {
     var resumeAt = effectivePlaybackTime();
     var startAt  = resumeAt > 1 ? resumeAt : 0;
     var vid = document.getElementById('main-video');
+    var resume = !vid.paused;
     transcodeSeekOffset = startAt;
     if (!attachTranscodeStream(vid, transcodeStreamURL(currentEpisodes[playingIndex].filepath, startAt),
             function (reason) { showToast(reason); },
-            function () { playVideo(vid); })) {
+            function () { settlePlayState(vid, resume); })) {
         showToast('This browser cannot play the HLS stream.');
     }
 }
 
 function playerVideoElement() { return document.getElementById('main-video'); }
 
+function currentPlayingFilepath() {
+    var ep = playingIndex >= 0 ? currentEpisodes[playingIndex] : null;
+    return ep ? ep.filepath : null;
+}
+
+// Show the quality steps the current file allows, with the one it plays at
+// highlighted. That is the viewer's choice unless the file is smaller than it;
+// under Auto the header says which step Auto is on.
+function renderStreamQuality() {
+    var filepath = currentPlayingFilepath();
+    var info     = filepath ? cachedMediaInfo(filepath) : null;
+    var chosen   = getStreamQuality();
+    var active   = (chosen === 'auto' || !filepath) ? chosen : effectiveStreamQuality(filepath);
+    $('#set-quality-grid .speed-btn').each(function () {
+        var id = String($(this).data('quality'));
+        $(this).toggle(streamQualityAvailable(id, info))
+               .toggleClass('active', id === active);
+    });
+    var note = (chosen === 'auto' && filepath) ? streamQualityStep(effectiveStreamQuality(filepath)) : null;
+    $('#set-quality-note').text(note ? note.label : '');
+}
+
+// Apply a quality step. Changing it mid-playback re-opens the current file at
+// the new step, resuming where the viewer was.
+function applyStreamQuality(quality, reloadCurrent) {
+    var filepath = currentPlayingFilepath();
+    var previous = filepath ? effectiveStreamQuality(filepath) : getStreamQuality();
+    // Auto starts from whatever is playing now rather than reloading straight away
+    if (quality === 'auto' && filepath) { setAutoQualityStep(filepath, previous); }
+    setStreamQuality(quality);
+    renderStreamQuality();
+
+    if (!reloadCurrent || !filepath || previous === effectiveStreamQuality(filepath)) { return; }
+    // The receiver picks the new step up with the next file it is sent
+    if (castMode && _castConnected()) { return; }
+    reopenCurrentStream(!document.getElementById('main-video').paused);
+}
+
+// Finish re-opening a stream in the state the viewer left it. The pause()
+// matters even on a paused element: it stops a newly set source from starting
+// by itself, which an autoplay attribute would otherwise do.
+function settlePlayState(vid, resume) {
+    if (resume) { playVideo(vid); } else { vid.pause(); }
+}
+
+// Re-open the current file at the current position after a quality change,
+// playing again only when `resume` says it was playing. Unlike a
+// streaming-mode change this can cross between direct playback and a
+// transcode: dropping below the source size always transcodes, and returning
+// to Original plays the file as-is again when the browser can.
+function reopenCurrentStream(resume) {
+    var index = playingIndex;
+    var ep    = currentEpisodes[index];
+    var vid   = document.getElementById('main-video');
+    var ext   = ep.ext ? ep.ext.toLowerCase().replace(/^\./, '') : '';
+    var resumeAt = effectivePlaybackTime();
+    var startAt  = resumeAt > 1 ? resumeAt : 0;
+    // A direct stream knows its own length; a transcode is told it separately
+    var knownDuration = isTranscodedVideo ? transcodeDuration : vid.duration;
+
+    showSeekFreeze();
+    setSubtitleSeekFloor(startAt);
+    resolveDirectPlay(ep.filepath, ext, function (directPlay) {
+        if (playingIndex !== index) { return; }   // episode changed meanwhile
+        clearDirectPlaybackWatch(vid);
+        detachTranscodeStream(vid);
+        $(vid).off('loadedmetadata.quality');   // from a switch made just before
+        isTranscodedVideo = !directPlay;
+
+        if (directPlay) {
+            transcodeSeekOffset = 0;
+            vid.src = MEDIA_API + '?file=' + encodeURIComponent(ep.filepath);
+            $(vid).one('loadedmetadata.quality', function () { vid.currentTime = startAt; });
+            onDirectPlaybackFailure(vid, function () {
+                if (playingIndex !== index) { return; }
+                showToast('This browser cannot decode that file — switching to a transcode');
+                beginEpisodeStream(ep, index, false);
+            });
+            settlePlayState(vid, resume);
+            return;
+        }
+
+        transcodeSeekOffset = startAt;
+        if (knownDuration > 0 && isFinite(knownDuration)) {
+            transcodeDuration = knownDuration;
+        } else {
+            fetch(ao_root + 'media/duration/?file=' + encodeURIComponent(ep.filepath))
+                .then(function (r) { return r.json(); })
+                .then(function (data) {
+                    if (data.duration > 0 && playingIndex === index) { transcodeDuration = data.duration; }
+                }).catch(function () {});
+        }
+        if (!attachTranscodeStream(vid, transcodeStreamURL(ep.filepath, startAt),
+                function (reason) { hideSeekFreeze(); showToast(reason); },
+                function () { settlePlayState(vid, resume); })) {
+            hideSeekFreeze();
+            showToast('This browser cannot play the transcoded stream. Switch streaming mode to MP4 in settings.');
+        }
+    });
+}
+
 // Surface the two streaming modes that cannot work on a given browser. Anything
 // that is simply working says nothing at all.
 function warnIfStreamModeUnplayable() {
@@ -4242,6 +4359,7 @@ function openSettingsPopup() {
     setPlaybackSpeed(playbackSpeed);
     setAlwaysShowVolumeBar(alwaysShowVolumeBar);
     applyStreamMode(getStreamMode(), false);
+    renderStreamQuality();
     $('#player-ctx').hide();
     closeSubtitlePopup();
     $('#settings-popup').addClass('active');
@@ -4322,6 +4440,9 @@ function initSettingsPopup() {
     $('#set-stream-seg').on('click', '.set-seg-btn', function () {
         applyStreamMode(String($(this).data('stream')), true);
     });
+    $('#set-quality-grid').on('click', '.speed-btn', function () {
+        applyStreamQuality(String($(this).data('quality')), true);
+    });
 
     $('#set-video-props').on('click', function () { closeSettingsPopup(); openVideoInfo('props'); });
     $('#set-advanced').on('click',    function () { closeSettingsPopup(); openAdvancedSettings(); });
@@ -4337,6 +4458,16 @@ function initSettingsPopup() {
     setPlaybackSpeed(playbackSpeed);
     setAlwaysShowVolumeBar(alwaysShowVolumeBar);
     applyStreamMode(getStreamMode(), false);
+    renderStreamQuality();
+
+    // Auto quality only ever moves while playing, so it always resumes
+    new AutoQualityController(document.getElementById('main-video'), {
+        filepath: function () {
+            return (castMode && _castConnected()) ? null : currentPlayingFilepath();
+        },
+        isTranscoded: function () { return isTranscodedVideo; },
+        onSwitch: function () { renderStreamQuality(); reopenCurrentStream(true); }
+    });
 
     // Changing episode — or a transcode seek — replaces the media source, which
     // resets playbackRate. Reapply the chosen speed every time media loads.