Przeglądaj źródła

Fixed transcoder and add GPU encoder

Toby Chui 11 godzin temu
rodzic
commit
4b0f11125a

+ 1 - 1
src/go.mod

@@ -41,6 +41,7 @@ require (
 	github.com/robertkrimen/otto v0.5.1
 	github.com/rwcarlsen/goexif v0.0.0-20190401172101-9e8deecbddbd
 	github.com/satori/go.uuid v1.2.0
+	github.com/shirou/gopsutil/v4 v4.26.9
 	github.com/spf13/afero v1.15.0
 	github.com/srwiley/oksvg v0.0.0-20221011165216-be6e8873101c
 	github.com/srwiley/rasterx v0.0.0-20220730225603-2ab79fcdd4ef
@@ -91,7 +92,6 @@ require (
 	github.com/prometheus/procfs v0.22.0 // indirect
 	github.com/quic-go/quic-go v0.63.0 // indirect
 	github.com/rcrowley/go-metrics v0.0.0-20250401214520-65e299d6c5c9 // indirect
-	github.com/shirou/gopsutil/v4 v4.26.9 // indirect
 	github.com/syncthing/notify v0.0.0-20250528144937-c7027d4f7465 // indirect
 	github.com/syncthing/syncthing v1.30.0-rc.1.0.20261020195438-d6d0181f7d46 // indirect
 	github.com/syndtr/goleveldb v1.0.1-0.20220721030215-126854af5e6d // indirect

+ 20 - 10
src/mod/filesystem/metadata/heic.go

@@ -27,8 +27,9 @@ import (
 // HEIC image format extensions supported by the system
 var HeicImageFormats = []string{".heic", ".heif", ".hif"}
 
-// Largest HEIC file that is decoded. An iPhone photo is 1 to 5 MB; the
-// decoded picture costs 4 bytes a pixel on top of the file.
+// Largest HEIC file that is decoded on a host with 4 GB of memory or less
+// (largeimage.go). An iPhone photo is 1 to 5 MB; the decoded picture costs
+// 4 bytes a pixel on top of the file.
 const maxHEICFileSize = 64 << 20
 
 // Thumbnails short side, in pixels
@@ -40,16 +41,23 @@ func IsHEICImageFile(filePath string) bool {
 	return utils.StringInArray(HeicImageFormats, ext)
 }
 
-// readHEIC reads a HEIC file of any file system, refusing oversized ones
-func readHEIC(fsh *filesystem.FileSystemHandler, file string) ([]byte, error) {
+// readHEIC reads a HEIC file of any file system, refusing oversized ones.
+// Without an error, release must be called once the picture is done with.
+func readHEIC(fsh *filesystem.FileSystemHandler, file string) (data []byte, release func(), err error) {
 	fshAbs := fsh.FileSystemAbstraction
 	if !fshAbs.FileExists(file) {
-		return nil, errors.New("source not exists")
+		return nil, nil, errors.New("source not exists")
 	}
-	if fshAbs.GetFileSize(file) > maxHEICFileSize {
-		return nil, errors.New("HEIC file too large")
+	release, ok := admitImageSize(fshAbs.GetFileSize(file), maxHEICFileSize)
+	if !ok {
+		return nil, nil, errors.New("HEIC file too large")
 	}
-	return fshAbs.ReadFile(file)
+	data, err = fshAbs.ReadFile(file)
+	if err != nil {
+		release()
+		return nil, nil, err
+	}
+	return data, release, nil
 }
 
 // decodeHEIC decodes the primary picture upright: the rotation (irot),
@@ -73,10 +81,11 @@ func decodeHEICPreview(data []byte) (image.Image, error) {
 
 // Generate thumbnail for HEIC images
 func generateThumbnailForHEIC(fsh *filesystem.FileSystemHandler, cacheFolder string, file string, generateOnly bool) (string, error) {
-	data, err := readHEIC(fsh, file)
+	data, release, err := readHEIC(fsh, file)
 	if err != nil {
 		return "", err
 	}
+	defer release()
 	img, err := decodeHEICPreview(data)
 	if err != nil {
 		return "", errors.New("failed to decode HEIC image: " + err.Error())
@@ -95,10 +104,11 @@ func generateThumbnailForHEIC(fsh *filesystem.FileSystemHandler, cacheFolder str
 // RenderHEICImage decodes a HEIC photo and returns it as a full size JPEG
 // for browsers that cannot show HEIC
 func RenderHEICImage(fsh *filesystem.FileSystemHandler, file string) ([]byte, error) {
-	data, err := readHEIC(fsh, file)
+	data, release, err := readHEIC(fsh, file)
 	if err != nil {
 		return nil, err
 	}
+	defer release()
 	img, err := decodeHEIC(data)
 	if err != nil {
 		return nil, errors.New("failed to decode HEIC image: " + err.Error())

+ 5 - 2
src/mod/filesystem/metadata/image.go

@@ -23,11 +23,14 @@ func generateThumbnailForImage(fsh *filesystem.FileSystemHandler, cacheFolder st
 	var img image.Image
 	var err error
 
-	if fshAbs.GetFileSize(file) > (25 << 20) {
-		//Maxmium image size to be converted is 25MB, on 500MB (~250MB usable) Linux System
+	//Maxmium image size to be converted is 25MB, on 500MB (~250MB usable) Linux System
+	//Hosts with more than 4GB of memory convert larger files anyway
+	release, ok := admitImageSize(fshAbs.GetFileSize(file), 25<<20)
+	if !ok {
 		//This file is too large to convert
 		return "", errors.New("image file too large")
 	}
+	defer release()
 
 	if filepath.Ext(file) == ".webp" {
 		//Webp image format

+ 52 - 0
src/mod/filesystem/metadata/largeimage.go

@@ -0,0 +1,52 @@
+package metadata
+
+import (
+	"strconv"
+	"sync"
+
+	"github.com/shirou/gopsutil/v4/mem"
+)
+
+/*
+	Image size limits
+
+	Decoding a photo costs far more memory than its file size, so each image
+	renderer refuses files above a limit to protect small hosts. A host with
+	more than 4 GB of memory converts them anyway.
+*/
+
+// Hosts with more physical memory than this ignore the image size limits
+const largeImageMemoryThreshold = 4 << 30
+
+// Physical memory of this host in bytes, 0 if unknown
+var totalSystemMemory = sync.OnceValue(func() uint64 {
+	vm, err := mem.VirtualMemory()
+	if err != nil {
+		return 0
+	}
+	return vm.Total
+})
+
+// Only one oversized image is decoded at a time: a browser asks for many
+// thumbnails at once and decoding them all together could use up the memory.
+var largeImageLock sync.Mutex
+
+// canConvertOversized reports whether a host of this memory size, running a
+// build with this pointer width, may decode images above the size limits.
+// 32 bit builds may not, their address space runs out whatever the host has.
+func canConvertOversized(totalMemory uint64, intSize int) bool {
+	return intSize == 64 && totalMemory > largeImageMemoryThreshold
+}
+
+// admitImageSize decides whether an image file of this size may be decoded.
+// When ok, the caller must call release once it is done with the image.
+func admitImageSize(size int64, limit int64) (release func(), ok bool) {
+	if size <= limit {
+		return func() {}, true
+	}
+	if !canConvertOversized(totalSystemMemory(), strconv.IntSize) {
+		return nil, false
+	}
+	largeImageLock.Lock()
+	return largeImageLock.Unlock, true
+}

+ 78 - 0
src/mod/filesystem/metadata/largeimage_test.go

@@ -0,0 +1,78 @@
+package metadata
+
+import (
+	"strconv"
+	"testing"
+)
+
+func TestCanConvertOversized(t *testing.T) {
+	cases := []struct {
+		name    string
+		memory  uint64
+		intSize int
+		want    bool
+	}{
+		{"unknown memory", 0, 64, false},
+		{"2GB host", 2 << 30, 64, false},
+		{"exactly 4GB", 4 << 30, 64, false},
+		{"just above 4GB", 4<<30 + 1, 64, true},
+		{"16GB host", 16 << 30, 64, true},
+		{"32 bit build on 16GB host", 16 << 30, 32, false},
+	}
+	for _, c := range cases {
+		if got := canConvertOversized(c.memory, c.intSize); got != c.want {
+			t.Errorf("%s: canConvertOversized = %v, want %v", c.name, got, c.want)
+		}
+	}
+}
+
+func TestAdmitImageSize(t *testing.T) {
+	original := totalSystemMemory
+	defer func() { totalSystemMemory = original }()
+
+	const limit = 100
+	cases := []struct {
+		name   string
+		memory uint64
+		size   int64
+		wantOK bool
+	}{
+		{"within limit on small host", 1 << 30, limit, true},
+		{"oversized on small host", 1 << 30, limit + 1, false},
+		{"oversized on large host", 8 << 30, limit + 1, strconv.IntSize == 64},
+	}
+	for _, c := range cases {
+		totalSystemMemory = func() uint64 { return c.memory }
+		release, ok := admitImageSize(c.size, limit)
+		if ok != c.wantOK {
+			t.Fatalf("%s: ok = %v, want %v", c.name, ok, c.wantOK)
+		}
+		if ok {
+			release()
+		}
+	}
+}
+
+// Oversized images hold the decoding lock until they are released
+func TestAdmitImageSizeSerialisesLargeImages(t *testing.T) {
+	if strconv.IntSize != 64 {
+		t.Skip("oversized images are refused on 32 bit builds")
+	}
+	original := totalSystemMemory
+	defer func() { totalSystemMemory = original }()
+	totalSystemMemory = func() uint64 { return 8 << 30 }
+
+	release, ok := admitImageSize(2, 1)
+	if !ok {
+		t.Fatalf("oversized image was refused")
+	}
+	if largeImageLock.TryLock() {
+		largeImageLock.Unlock()
+		t.Fatalf("lock was not held while the image is in use")
+	}
+	release()
+	if !largeImageLock.TryLock() {
+		t.Fatalf("lock was not released")
+	}
+	largeImageLock.Unlock()
+}

+ 8 - 6
src/mod/filesystem/metadata/raw.go

@@ -18,11 +18,12 @@ import (
 func generateThumbnailForRAW(fsh *filesystem.FileSystemHandler, cacheFolder string, file string, generateOnly bool) (string, error) {
 	fshAbs := fsh.FileSystemAbstraction
 
-	// Check file size - skip files larger than 100MB to prevent memory issues
-	fileSize := fshAbs.GetFileSize(file)
-	if fileSize > (100 << 20) {
+	// Skip files larger than 100MB on hosts without the memory for them
+	release, ok := admitImageSize(fshAbs.GetFileSize(file), 100<<20)
+	if !ok {
 		return "", errors.New("RAW file too large (>100MB)")
 	}
+	defer release()
 
 	// Read the RAW file
 	rawData, err := fshAbs.ReadFile(file)
@@ -541,11 +542,12 @@ func getSizeForType(fieldType uint16) uint32 {
 func RenderRAWImage(fsh *filesystem.FileSystemHandler, file string) ([]byte, error) {
 	fshAbs := fsh.FileSystemAbstraction
 
-	// Check file size - skip files larger than 100MB to prevent memory issues
-	fileSize := fshAbs.GetFileSize(file)
-	if fileSize > (100 << 20) {
+	// Skip files larger than 100MB on hosts without the memory for them
+	release, ok := admitImageSize(fshAbs.GetFileSize(file), 100<<20)
+	if !ok {
 		return nil, errors.New("RAW file too large (>100MB)")
 	}
+	defer release()
 
 	// Read the RAW file
 	rawData, err := fshAbs.ReadFile(file)

+ 251 - 0
src/mod/media/transcoder/fallback_test.go

@@ -0,0 +1,251 @@
+package transcoder
+
+import (
+	"errors"
+	"net/http/httptest"
+	"os"
+	"os/exec"
+	"path/filepath"
+	"testing"
+)
+
+// brokenProfile names an encoder ffmpeg does not have, so a transcode using it
+// fails at once without producing anything - the same outcome as a hardware
+// pipeline the driver cannot run for a given source.
+var brokenProfile = &hwEncoderProfile{
+	Name:        "broken test encoder",
+	Codec:       "h264_arozos_does_not_exist",
+	ScaleFilter: nv12ScaleFilter,
+}
+
+// TestSelectWorkingProfiles verifies the probe keeps every working profile in
+// order but only the first working one of each group.
+func TestSelectWorkingProfiles(t *testing.T) {
+	full := &hwEncoderProfile{Name: "full", Group: "full"}
+	fullLP := &hwEncoderProfile{Name: "full LP", Group: "full"}
+	hybrid := &hwEncoderProfile{Name: "hybrid", Group: "hybrid"}
+	hybridLP := &hwEncoderProfile{Name: "hybrid LP", Group: "hybrid"}
+	nvenc := &hwEncoderProfile{Name: "nvenc"}
+	other := &hwEncoderProfile{Name: "other"}
+	candidates := []*hwEncoderProfile{nvenc, full, fullLP, hybrid, hybridLP, other}
+
+	cases := []struct {
+		name  string
+		works map[*hwEncoderProfile]bool
+		want  []*hwEncoderProfile
+	}{
+		{"nothing works", nil, nil},
+		{"all work, groups collapse", map[*hwEncoderProfile]bool{nvenc: true, full: true, fullLP: true, hybrid: true, hybridLP: true, other: true},
+			[]*hwEncoderProfile{nvenc, full, hybrid, other}},
+		{"only low-power encode, no scale_vaapi", map[*hwEncoderProfile]bool{hybridLP: true},
+			[]*hwEncoderProfile{hybridLP}},
+		{"normal fails, low-power stands in", map[*hwEncoderProfile]bool{fullLP: true, hybrid: true},
+			[]*hwEncoderProfile{fullLP, hybrid}},
+	}
+	for _, tc := range cases {
+		t.Run(tc.name, func(t *testing.T) {
+			probed := map[*hwEncoderProfile]bool{}
+			got := selectWorkingProfiles(candidates, func(p *hwEncoderProfile) bool {
+				probed[p] = true
+				return tc.works[p]
+			})
+			if len(got) != len(tc.want) {
+				t.Fatalf("selectWorkingProfiles() = %v, want %v", names(got), names(tc.want))
+			}
+			for i := range got {
+				if got[i] != tc.want[i] {
+					t.Errorf("selectWorkingProfiles()[%d] = %s, want %s", i, got[i].Name, tc.want[i].Name)
+				}
+			}
+			// A group already satisfied is not probed again.
+			if tc.works[full] && probed[fullLP] {
+				t.Error("probed the low-power variant although the normal one works")
+			}
+		})
+	}
+}
+
+func names(profiles []*hwEncoderProfile) []string {
+	out := make([]string, len(profiles))
+	for i, p := range profiles {
+		out[i] = profileName(p)
+	}
+	return out
+}
+
+// TestProbeScaleFilter verifies the probe frame is resized to twice its size.
+func TestProbeScaleFilter(t *testing.T) {
+	cases := []struct {
+		size string
+		want string
+	}{
+		{"320x240", "scale=w=640:h=480"},
+		{"640x480", "scale=w=1280:h=960"},
+		{"", ""},
+		{"banana", ""},
+		{"0x240", ""},
+	}
+	for _, tc := range cases {
+		if got := probeScaleFilter(tc.size); got != tc.want {
+			t.Errorf("probeScaleFilter(%q) = %q, want %q", tc.size, got, tc.want)
+		}
+	}
+}
+
+// TestTranscodeChain verifies software encoding always ends the chain.
+func TestTranscodeChain(t *testing.T) {
+	chain := transcodeChain()
+	if len(chain) == 0 || chain[len(chain)-1] != nil {
+		t.Fatalf("transcodeChain() = %v, want it to end with software (nil)", names(chain))
+	}
+	if profileName(nil) != "software (libx264)" {
+		t.Errorf("profileName(nil) = %q", profileName(nil))
+	}
+}
+
+// TestRunWithFallback verifies when the loop moves to the next entry.
+func TestRunWithFallback(t *testing.T) {
+	a := &hwEncoderProfile{Name: "a"}
+	b := &hwEncoderProfile{Name: "b"}
+	chain := []*hwEncoderProfile{a, b, nil}
+	failure := errors.New("ffmpeg failed")
+
+	type result struct {
+		wrote bool
+		err   error
+	}
+	cases := []struct {
+		name      string
+		results   map[*hwEncoderProfile]result
+		cancelled bool
+		wantTried []string
+		wantWrote bool
+		wantErr   bool
+	}{
+		{"first works", map[*hwEncoderProfile]result{a: {true, nil}},
+			false, []string{"a"}, true, false},
+		{"first fails, second works", map[*hwEncoderProfile]result{a: {false, failure}, b: {true, nil}},
+			false, []string{"a", "b"}, true, false},
+		{"hardware fails, software works", map[*hwEncoderProfile]result{a: {false, failure}, b: {false, failure}, nil: {true, nil}},
+			false, []string{"a", "b", "software (libx264)"}, true, false},
+		{"all fail", map[*hwEncoderProfile]result{a: {false, failure}, b: {false, failure}, nil: {false, failure}},
+			false, []string{"a", "b", "software (libx264)"}, false, true},
+		{"output then error is not retried", map[*hwEncoderProfile]result{a: {true, failure}},
+			false, []string{"a"}, true, true},
+		{"clean exit without output is not retried", map[*hwEncoderProfile]result{a: {false, nil}},
+			false, []string{"a"}, false, false},
+		{"cancelled request is not retried", map[*hwEncoderProfile]result{a: {false, failure}},
+			true, []string{"a"}, false, true},
+	}
+	for _, tc := range cases {
+		t.Run(tc.name, func(t *testing.T) {
+			var tried []string
+			failedCalls := 0
+			wrote, err := runWithFallback(chain, func(hw *hwEncoderProfile) (bool, error) {
+				tried = append(tried, profileName(hw))
+				r := tc.results[hw]
+				return r.wrote, r.err
+			}, func(*hwEncoderProfile, error) {
+				failedCalls++
+			}, func() bool { return tc.cancelled })
+
+			if len(tried) != len(tc.wantTried) {
+				t.Fatalf("tried %v, want %v", tried, tc.wantTried)
+			}
+			for i := range tried {
+				if tried[i] != tc.wantTried[i] {
+					t.Errorf("tried %v, want %v", tried, tc.wantTried)
+				}
+			}
+			if wrote != tc.wantWrote {
+				t.Errorf("wrote = %v, want %v", wrote, tc.wantWrote)
+			}
+			if (err != nil) != tc.wantErr {
+				t.Errorf("err = %v, want error %v", err, tc.wantErr)
+			}
+			// failed is reported for every attempt that is followed by another
+			if want := len(tried) - 1; failedCalls != want {
+				t.Errorf("failed called %d times, want %d", failedCalls, want)
+			}
+		})
+	}
+}
+
+// TestMP4FallsBackToNextEncoder runs a real transcode whose first encoder
+// cannot start and checks the video still arrives, from the next one.
+func TestMP4FallsBackToNextEncoder(t *testing.T) {
+	if _, err := exec.LookPath("ffmpeg"); err != nil {
+		t.Skip("ffmpeg not installed on this host")
+	}
+	source := filepath.Join(t.TempDir(), "source.mp4")
+	generateTestVideo(t, source)
+
+	req := httptest.NewRequest("GET", "/media/transcode", nil)
+	rr := httptest.NewRecorder()
+	var tried []string
+	wrote, err := runWithFallback([]*hwEncoderProfile{brokenProfile, nil}, func(hw *hwEncoderProfile) (bool, error) {
+		tried = append(tried, profileName(hw))
+		args, err := buildMP4Args(source, TranscodeResolution_original, 0, hw)
+		if err != nil {
+			return false, err
+		}
+		return streamMP4(rr, req, args)
+	}, func(*hwEncoderProfile, error) {}, func() bool { return false })
+
+	if !wrote || err != nil {
+		t.Fatalf("wrote = %v, err = %v, want video from the software encoder (tried %v)", wrote, err, tried)
+	}
+	if len(tried) != 2 {
+		t.Errorf("tried %v, want the broken encoder then software", tried)
+	}
+	if rr.Body.Len() == 0 {
+		t.Error("no video reached the response")
+	}
+}
+
+// TestHLSSuperviseFallsBackToNextEncoder starts an HLS session on an encoder
+// that cannot run and checks the supervisor restarts it with the next one.
+func TestHLSSuperviseFallsBackToNextEncoder(t *testing.T) {
+	if _, err := exec.LookPath("ffmpeg"); err != nil {
+		t.Skip("ffmpeg not installed on this host")
+	}
+	tmp := t.TempDir()
+	source := filepath.Join(tmp, "source.mp4")
+	generateTestVideo(t, source)
+
+	session := &HLSSession{
+		ID:     "fallback",
+		Dir:    filepath.Join(tmp, "session"),
+		stderr: &tailBuffer{},
+		exited: make(chan struct{}),
+	}
+	if err := os.MkdirAll(session.Dir, 0755); err != nil {
+		t.Fatal(err)
+	}
+	build := func(hw *hwEncoderProfile) ([]string, error) {
+		return buildHLSArgs(source, session.Dir, TranscodeResolution_original, 0, "/seg/", hw)
+	}
+	chain := []*hwEncoderProfile{brokenProfile, nil}
+	args, err := build(chain[0])
+	if err != nil {
+		t.Fatal(err)
+	}
+	cmd := exec.Command("ffmpeg", args...)
+	cmd.Stderr = session.stderr
+	if err := cmd.Start(); err != nil {
+		t.Fatal(err)
+	}
+	session.cmd = cmd
+	go session.supervise(cmd, chain, build)
+	defer session.stop()
+
+	if err := session.WaitForPlaylist(HLSPlaylistWaitTimeout); err != nil {
+		t.Fatalf("no segment after falling back: %v (ffmpeg: %s)", err, session.StderrTail())
+	}
+	session.mu.Lock()
+	restarted := session.cmd != cmd
+	session.mu.Unlock()
+	if !restarted {
+		t.Error("the session is still on the broken encoder's process")
+	}
+}

+ 83 - 8
src/mod/media/transcoder/hls.go

@@ -119,6 +119,13 @@ func (t *tailBuffer) Write(p []byte) (int, error) {
 	return len(p), nil
 }
 
+// Reset empties the buffer, so it describes the next attempt only.
+func (t *tailBuffer) Reset() {
+	t.mu.Lock()
+	t.data = nil
+	t.mu.Unlock()
+}
+
 func (t *tailBuffer) String() string {
 	t.mu.Lock()
 	defer t.mu.Unlock()
@@ -193,6 +200,75 @@ func (s *HLSSession) stop() {
 	}
 }
 
+// supervise is the sole owner of cmd.Wait: it reaps the transcode whether it
+// finishes the file or is killed, and closes s.exited once it is over.
+//
+// A transcode that dies before writing its first segment is restarted with the
+// next entry of chain (the first entry is the one already running as cmd), so
+// a hardware pipeline that cannot handle this source - see transcodeChain -
+// falls back instead of failing the session. s.exited only closes once no
+// attempt is left, which keeps WaitForPlaylist waiting through the retries.
+func (s *HLSSession) supervise(cmd *exec.Cmd, chain []*hwEncoderProfile, build func(*hwEncoderProfile) ([]string, error)) {
+	defer close(s.exited)
+	current := chain[0]
+	rest := chain[1:]
+	for {
+		waitErr := cmd.Wait()
+		// A clean exit with no segment (a start offset past the end of the
+		// file) is not something another encoder would do better.
+		if waitErr == nil || playlistHasSegment(s.PlaylistPath()) {
+			return
+		}
+		s.mu.Lock()
+		if s.stopped {
+			s.mu.Unlock()
+			return
+		}
+		next, hw, ok := s.restart(&rest, current, waitErr, build)
+		s.mu.Unlock()
+		if !ok {
+			return
+		}
+		cmd, current = next, hw
+	}
+}
+
+// restart starts the next workable entry of *rest in a clean session
+// directory, consuming entries as it goes, and returns the process and the
+// entry it runs. Must be called with s.mu held, so stop cannot miss the new
+// process.
+func (s *HLSSession) restart(rest *[]*hwEncoderProfile, failed *hwEncoderProfile, failure error, build func(*hwEncoderProfile) ([]string, error)) (*exec.Cmd, *hwEncoderProfile, bool) {
+	for len(*rest) > 0 {
+		hw := (*rest)[0]
+		*rest = (*rest)[1:]
+		logger.PrintAndLog("Transcoder", "HLS transcode with "+profileName(failed)+" failed before its first segment, trying "+
+			profileName(hw)+": "+s.StderrTail(), failure)
+
+		// Drop whatever the failed attempt left behind (a playlist header,
+		// an init segment for a stream that never came).
+		os.RemoveAll(s.Dir)
+		if err := os.MkdirAll(s.Dir, 0755); err != nil {
+			return nil, nil, false
+		}
+		s.stderr.Reset()
+
+		args, err := build(hw)
+		if err != nil {
+			failed, failure = hw, err
+			continue
+		}
+		cmd := exec.Command("ffmpeg", args...)
+		cmd.Stderr = s.stderr
+		if err := cmd.Start(); err != nil {
+			failed, failure = hw, err
+			continue
+		}
+		s.cmd = cmd
+		return cmd, hw, true
+	}
+	return nil, nil, false
+}
+
 // validHLSSegmentName reports whether name matches the segment naming this
 // package generates ("seg00000.m4s", plus the fixed init segment name), rejecting anything containing a path
 // separator, "..", or unexpected characters.
@@ -457,8 +533,12 @@ func (m *HLSManager) GetOrCreate(owner string, client string, inputFile string,
 		return nil, err
 	}
 
-	args, err := buildHLSArgs(inputFile, session.Dir, resolution, startTime,
-		m.segmentBaseURL(key), getHWEncoderProfile())
+	segmentBaseURL := m.segmentBaseURL(key)
+	build := func(hw *hwEncoderProfile) ([]string, error) {
+		return buildHLSArgs(inputFile, session.Dir, resolution, startTime, segmentBaseURL, hw)
+	}
+	chain := transcodeChain()
+	args, err := build(chain[0])
 	if err != nil {
 		os.RemoveAll(session.Dir)
 		return nil, err
@@ -474,12 +554,7 @@ func (m *HLSManager) GetOrCreate(owner string, client string, inputFile string,
 	}
 	session.cmd = cmd
 	session.exited = make(chan struct{})
-	//Sole owner of cmd.Wait: reaps the process whether it finishes the file or
-	//is killed, and signals both facts through the same channel.
-	go func(exited chan struct{}) {
-		cmd.Wait()
-		close(exited)
-	}(session.exited)
+	go session.supervise(cmd, chain, build)
 
 	m.mu.Lock()
 	// Another request may have created the same session while ffmpeg was

+ 82 - 19
src/mod/media/transcoder/hwaccel.go

@@ -13,7 +13,9 @@ package transcoder
 
 import (
 	"context"
+	"fmt"
 	"os/exec"
+	"strings"
 	"sync"
 	"time"
 
@@ -35,6 +37,12 @@ type hwEncoderProfile struct {
 	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
+	// Group names profiles that are variants of one pipeline on one device,
+	// such as the normal and low-power VAAPI encoder. Only the first of a
+	// group that passes the probe is kept, so a failing transcode falls back
+	// to a different pipeline rather than to a near copy of the same one.
+	// "" makes the profile a group of its own.
+	Group string
 }
 
 // defaultProbeSize is the test frame size used by testHWEncoder when a profile
@@ -45,7 +53,7 @@ const defaultProbeSize = "320x240"
 
 var (
 	hwProfileOnce sync.Once
-	hwProfile     *hwEncoderProfile // nil if no usable hardware encoder was found
+	hwProfiles    []*hwEncoderProfile // usable hardware profiles, best first; empty if none
 )
 
 // nv12ScaleFilter returns a -vf filter chain that applies the given scale
@@ -60,36 +68,82 @@ func nv12ScaleFilter(scale string) string {
 	return scale + ",format=nv12"
 }
 
-// getHWEncoderProfile probes the host once for a working Intel/AMD hardware
-// H.264 encoder and caches the result for the lifetime of the process.
-func getHWEncoderProfile() *hwEncoderProfile {
+// getHWEncoderProfiles probes the host once for working hardware H.264
+// pipelines and caches the result for the lifetime of the process.
+func getHWEncoderProfiles() []*hwEncoderProfile {
 	hwProfileOnce.Do(func() {
-		hwProfile = probeHWEncoders()
-		if hwProfile != nil {
-			logger.PrintAndLog("Transcoder", "Hardware transcoding enabled: "+hwProfile.Name, nil)
-		} else {
+		hwProfiles = probeHWEncoders()
+		if len(hwProfiles) == 0 {
 			logger.PrintAndLog("Transcoder", "No usable hardware encoder found, using software (libx264) transcoding", nil)
+			return
+		}
+		names := make([]string, len(hwProfiles))
+		for i, profile := range hwProfiles {
+			names[i] = profile.Name
 		}
+		logger.PrintAndLog("Transcoder", "Hardware transcoding enabled: "+strings.Join(names, ", then "), nil)
 	})
-	return hwProfile
+	return hwProfiles
 }
 
-// probeHWEncoders tries each platform candidate in order and returns the
-// first one that can actually complete a throwaway encode, since an encoder
-// can be compiled into ffmpeg yet still fail when no compatible GPU/driver
-// is present on this particular machine.
-func probeHWEncoders() *hwEncoderProfile {
-	for _, profile := range candidateHWProfiles() {
-		if testHWEncoder(profile) {
-			return profile
-		}
+// getHWEncoderProfile returns the best usable hardware profile, or nil when
+// transcoding has to use libx264.
+func getHWEncoderProfile() *hwEncoderProfile {
+	if profiles := getHWEncoderProfiles(); len(profiles) > 0 {
+		return profiles[0]
 	}
 	return nil
 }
 
+// transcodeChain lists the encoder settings a transcode tries in turn: every
+// usable hardware profile, best first, then nil for libx264. The probe only
+// shows that a pipeline works for a synthetic 8-bit frame; a real source can
+// still break it - a 10-bit HDR film needs a pixel format conversion the GPU
+// may not offer - so a transcode that fails before producing anything moves
+// on to the next entry instead of leaving the player waiting forever.
+func transcodeChain() []*hwEncoderProfile {
+	return append(append([]*hwEncoderProfile{}, getHWEncoderProfiles()...), nil)
+}
+
+// probeHWEncoders tries each platform candidate in order and keeps those that
+// can actually complete a throwaway encode, since an encoder can be compiled
+// into ffmpeg yet still fail when no compatible GPU/driver is present on this
+// particular machine. Within a Group only the first that works is kept.
+func probeHWEncoders() []*hwEncoderProfile {
+	return selectWorkingProfiles(candidateHWProfiles(), testHWEncoder)
+}
+
+// selectWorkingProfiles is the probing loop of probeHWEncoders, separated so
+// the grouping rule can be tested without ffmpeg.
+func selectWorkingProfiles(candidates []*hwEncoderProfile, works func(*hwEncoderProfile) bool) []*hwEncoderProfile {
+	var usable []*hwEncoderProfile
+	satisfied := map[string]bool{}
+	for _, profile := range candidates {
+		if profile.Group != "" && satisfied[profile.Group] {
+			continue
+		}
+		if !works(profile) {
+			continue
+		}
+		usable = append(usable, profile)
+		if profile.Group != "" {
+			satisfied[profile.Group] = true
+		}
+	}
+	return usable
+}
+
 // probeArgs builds the ffmpeg argument list for a profile's throwaway probe
 // encode: a single synthetic frame pushed through the real encoder settings
 // and discarded.
+//
+// The frame is resized on the way, to twice the probe size. Without that the
+// probe proved nothing about GPU scaling: scale_vaapi passes a frame straight
+// through when neither size nor format changes, so a driver with no video
+// processing entrypoint at all (Debian's free Intel driver on 9th generation
+// graphics) passed the probe and then failed every real transcode. Doubling
+// rather than halving keeps the frame above the minimum size some encoders
+// accept.
 func probeArgs(profile *hwEncoderProfile) []string {
 	size := profile.ProbeSize
 	if size == "" {
@@ -100,7 +154,7 @@ func probeArgs(profile *hwEncoderProfile) []string {
 		"-hide_banner", "-loglevel", "error",
 		"-f", "lavfi", "-i", "color=c=black:s="+size+":d=0.1",
 	)
-	if vf := profile.ScaleFilter(""); vf != "" {
+	if vf := profile.ScaleFilter(probeScaleFilter(size)); vf != "" {
 		args = append(args, "-vf", vf)
 	}
 	args = append(args, "-frames:v", "1", "-vcodec", profile.Codec)
@@ -116,3 +170,12 @@ func testHWEncoder(profile *hwEncoderProfile) bool {
 	cmd := exec.CommandContext(ctx, "ffmpeg", probeArgs(profile)...)
 	return cmd.Run() == nil
 }
+
+// probeScaleFilter returns a scale filter to twice the given WxH probe size.
+func probeScaleFilter(size string) string {
+	w, h := 0, 0
+	if _, err := fmt.Sscanf(size, "%dx%d", &w, &h); err != nil || w <= 0 || h <= 0 {
+		return ""
+	}
+	return fmt.Sprintf("scale=w=%d:h=%d", w*2, h*2)
+}

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

@@ -74,7 +74,7 @@ func TestProbeArgs(t *testing.T) {
 				EncodeArgs:  []string{"-preset", "fast"},
 			},
 			wantSize:    defaultProbeSize,
-			wantOrdered: []string{"-i", "-vf", "format=nv12", "-vcodec", "h264_fake", "-preset", "fast", "-f", "null", "-"},
+			wantOrdered: []string{"-i", "-vf", "scale=w=640:h=480,format=nv12", "-vcodec", "h264_fake", "-preset", "fast", "-f", "null", "-"},
 		},
 		{
 			name: "explicit probe size overrides the default",
@@ -86,7 +86,7 @@ func TestProbeArgs(t *testing.T) {
 				ProbeSize:   "640x480",
 			},
 			wantSize:    "640x480",
-			wantOrdered: []string{"-i", "-vcodec", "h264_videotoolbox", "-realtime", "1"},
+			wantOrdered: []string{"-i", "-vf", "scale=w=1280:h=960,format=nv12", "-vcodec", "h264_videotoolbox", "-realtime", "1"},
 			wantAbsent:  []string{"color=c=black:s=" + defaultProbeSize + ":d=0.1"},
 		},
 		{

+ 37 - 20
src/mod/media/transcoder/hwaccel_vaapi.go

@@ -13,18 +13,24 @@ package transcoder
 	    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.
+	    was offloaded: an HEVC source was still decoded on the CPU, which a
+	    low-end dual-core cannot keep up with at 4K.
+	  - GPU decode, CPU scale: the GPU decodes and encodes, ffmpeg copies the
+	    decoded frames to system memory in between so they can be scaled and
+	    converted to 8-bit NV12 in software. This is for drivers without the
+	    video processing (VPP) entrypoint scale_vaapi needs - Debian's free
+	    intel-media-va-driver build has none on 9th generation graphics (UHD
+	    610/620/630) - and it still takes the decode, by far the most expensive
+	    step for HEVC, off the CPU. A source the GPU cannot decode is decoded in
+	    software by ffmpeg instead, so this also covers every encode-only case.
 
 	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.
+	either through the full encode entrypoint or the low-power (VDEnc) one, and
+	the free driver build only has the low-power one on most generations. The
+	ffmpeg 7.1 Debian ships picks the low-power one on its own when it is the
+	only one, but releases that do not would need -low_power 1, so a low-power
+	variant is probed when the normal one fails. Both share a Group, so only
+	one of them ends up in the fallback chain.
 */
 
 import (
@@ -57,41 +63,52 @@ func vaapiRenderNodes() []string {
 func vaapiProfiles(device string) []*hwEncoderProfile {
 	preInput := []string{"-vaapi_device", device}
 	lowPower := []string{"-low_power", "1"}
+	name := filepath.Base(device)
 	// -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)
+	gpuFrames := []string{"-hwaccel", "vaapi", "-hwaccel_output_format", "vaapi"}
+	// Without -hwaccel_output_format, ffmpeg copies each GPU-decoded frame
+	// back to system memory, which is what the software scale filter needs.
+	cpuFrames := []string{"-hwaccel", "vaapi"}
 
+	full := "vaapi-full:" + device
+	hybrid := "vaapi-hybrid:" + device
 	return []*hwEncoderProfile{
 		{
-			Name:        "Intel/AMD VAAPI, hardware decode and encode (" + name + ")",
+			Name:        "Intel/AMD VAAPI, GPU decode, scale and encode (" + name + ")",
 			Codec:       "h264_vaapi",
 			PreInput:    preInput,
-			DecodeArgs:  decode,
+			DecodeArgs:  gpuFrames,
 			ScaleFilter: vaapiHWFilter,
+			Group:       full,
 		},
 		{
-			Name:        "Intel/AMD VAAPI low-power, hardware decode and encode (" + name + ")",
+			Name:        "Intel/AMD VAAPI low-power, GPU decode, scale and encode (" + name + ")",
 			Codec:       "h264_vaapi",
 			PreInput:    preInput,
-			DecodeArgs:  decode,
+			DecodeArgs:  gpuFrames,
 			ScaleFilter: vaapiHWFilter,
 			EncodeArgs:  lowPower,
+			Group:       full,
 		},
 		{
-			Name:        "Intel/AMD VAAPI, encode only (" + name + ")",
+			Name:        "Intel/AMD VAAPI, GPU decode and encode, CPU scale (" + name + ")",
 			Codec:       "h264_vaapi",
 			PreInput:    preInput,
+			DecodeArgs:  cpuFrames,
 			ScaleFilter: vaapiUploadFilter,
+			Group:       hybrid,
 		},
 		{
-			Name:        "Intel/AMD VAAPI low-power, encode only (" + name + ")",
+			Name:        "Intel/AMD VAAPI low-power, GPU decode and encode, CPU scale (" + name + ")",
 			Codec:       "h264_vaapi",
 			PreInput:    preInput,
+			DecodeArgs:  cpuFrames,
 			ScaleFilter: vaapiUploadFilter,
 			EncodeArgs:  lowPower,
+			Group:       hybrid,
 		},
 	}
 }
@@ -117,8 +134,8 @@ func vaapiScaleFilter(scale string) string {
 	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.
+// vaapiUploadFilter is the -vf chain of the CPU-scale pipeline: scale and
+// convert to 8-bit NV12 in software, then upload for the encoder.
 func vaapiUploadFilter(scale string) string {
 	if scale == "" {
 		return "format=nv12,hwupload"

+ 28 - 13
src/mod/media/transcoder/hwaccel_vaapi_test.go

@@ -76,13 +76,14 @@ func TestVAAPIProfiles(t *testing.T) {
 	const device = "/dev/dri/renderD129"
 	profiles := vaapiProfiles(device)
 	want := []struct {
-		hwDecode bool
-		lowPower bool
+		gpuFrames bool // decoded frames stay on the GPU and are scaled there
+		lowPower  bool
+		group     string
 	}{
-		{true, false},
-		{true, true},
-		{false, false},
-		{false, true},
+		{true, false, "vaapi-full:" + device},
+		{true, true, "vaapi-full:" + device},
+		{false, false, "vaapi-hybrid:" + device},
+		{false, true, "vaapi-hybrid:" + device},
 	}
 	if len(profiles) != len(want) {
 		t.Fatalf("vaapiProfiles() returned %d profiles, want %d", len(profiles), len(want))
@@ -97,12 +98,20 @@ func TestVAAPIProfiles(t *testing.T) {
 		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)
+		// Every VAAPI profile decodes on the GPU; they differ in where the
+		// decoded frames go.
+		wantDecode := "-hwaccel vaapi"
+		if want[i].gpuFrames {
+			wantDecode += " -hwaccel_output_format vaapi"
 		}
-		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(""))
+		if got := strings.Join(p.DecodeArgs, " "); got != wantDecode {
+			t.Errorf("profile %d (%s) DecodeArgs = %q, want %q", i, p.Name, got, wantDecode)
+		}
+		if want[i].gpuFrames != strings.Contains(p.ScaleFilter(""), "scale_vaapi") {
+			t.Errorf("profile %d (%s) GPU frames %v does not match filter %q", i, p.Name, want[i].gpuFrames, p.ScaleFilter(""))
+		}
+		if p.Group != want[i].group {
+			t.Errorf("profile %d (%s) Group = %q, want %q", i, p.Name, p.Group, want[i].group)
 		}
 		lowPower := strings.Join(p.EncodeArgs, " ") == "-low_power 1"
 		if lowPower != want[i].lowPower {
@@ -133,8 +142,14 @@ func TestProbeArgsOmitDecodeArgs(t *testing.T) {
 	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)
+	// The probe has to resize: scale_vaapi passes a frame of unchanged size
+	// and format straight through, which once hid a driver with no video
+	// processing support at all.
+	if vf := indexOf(args, "-vf"); vf == -1 || args[vf+1] != vaapiHWFilter(probeScaleFilter(defaultProbeSize)) {
+		t.Errorf("probeArgs() = %v, want the full hardware filter chain with a resize", args)
+	}
+	if !strings.Contains(strings.Join(args, " "), "scale_vaapi=w=640:h=480:format=nv12") {
+		t.Errorf("probeArgs() = %v, want scale_vaapi to resize the probe frame", args)
 	}
 }
 

+ 99 - 54
src/mod/media/transcoder/transcoder.go

@@ -14,6 +14,7 @@ import (
 	"net/http"
 	"os/exec"
 	"strconv"
+	"strings"
 	"time"
 
 	"imuslab.com/arozos/mod/info/logger"
@@ -35,85 +36,129 @@ const (
 // When the host has a usable hardware H.264 encoder - NVENC / VAAPI / Quick
 // 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
+// getHWEncoderProfiles); otherwise this falls back to the original software
+// path. With VAAPI the source is decoded on the GPU as well, which is what
 // keeps an HEVC source from saturating a low-end CPU.
+//
+// A pipeline that fails before sending a single byte (see transcodeChain) is
+// retried with the next one, and if every one fails the client gets an error
+// rather than an empty response it would wait on forever.
 func TranscodeAndStream(w http.ResponseWriter, r *http.Request, inputFile string, resolution TranscodeOutputResolution, startTime float64) {
-	// Build the FFmpeg command based on the resolution parameter
-	args, err := buildMP4Args(inputFile, resolution, startTime, getHWEncoderProfile())
-	if err != nil {
+	if _, err := resolutionScaleFilter(resolution); err != nil {
 		http.Error(w, "Invalid resolution parameter", http.StatusBadRequest)
 		return
 	}
-	cmd := exec.Command("ffmpeg", args...)
 
-	// Set response headers for streaming MP4 video
+	// Set response headers for streaming MP4 video. Nothing is sent until the
+	// first byte of video, so they are withdrawn again if no attempt succeeds.
 	w.Header().Set("Content-Type", "video/mp4")
 	w.Header().Set("Transfer-Encoding", "chunked")
 	w.Header().Set("Cache-Control", "public, max-age=3600, s-maxage=3600, must-revalidate")
 	w.Header().Set("Accept-Ranges", "bytes")
 
-	// Get the command output pipe
-	stdout, err := cmd.StdoutPipe()
-	if err != nil {
-		http.Error(w, "Failed to create output pipe", http.StatusInternalServerError)
+	wrote, err := runWithFallback(transcodeChain(), func(hw *hwEncoderProfile) (bool, error) {
+		args, err := buildMP4Args(inputFile, resolution, startTime, hw)
+		if err != nil {
+			return false, err
+		}
+		return streamMP4(w, r, args)
+	}, func(hw *hwEncoderProfile, err error) {
+		logger.PrintAndLog("Transcoder", "Transcode with "+profileName(hw)+" failed before producing any video, trying the next encoder", err)
+	}, func() bool {
+		return r.Context().Err() != nil
+	})
+
+	if !wrote && err != nil && r.Context().Err() == nil {
+		for _, header := range []string{"Content-Type", "Transfer-Encoding", "Cache-Control", "Accept-Ranges"} {
+			w.Header().Del(header)
+		}
+		logger.PrintAndLog("Transcoder", "Every encoder failed to transcode "+inputFile, err)
+		http.Error(w, "Failed to transcode video", http.StatusInternalServerError)
 		return
 	}
+	logger.PrintAndLog("Transcoder", "[Media Server] Transcode client disconnected", nil)
+}
 
-	// Get the command error pipe to capture standard error
-	stderr, err := cmd.StderrPipe()
-	if err != nil {
-		http.Error(w, "Failed to create error pipe", http.StatusInternalServerError)
-		logger.PrintAndLog("Transcoder", fmt.Sprintf("Failed to create error pipe: %v", err), nil)
-		return
+// profileName names a transcodeChain entry for logs; nil is libx264.
+func profileName(hw *hwEncoderProfile) string {
+	if hw == nil {
+		return "software (libx264)"
 	}
+	return hw.Name
+}
 
-	// Start the command
-	if err := cmd.Start(); err != nil {
-		http.Error(w, "Failed to start FFmpeg", http.StatusInternalServerError)
-		return
+// runWithFallback runs attempt with each entry of chain in turn until one
+// produces output, ends without an error, the request is cancelled, or the
+// chain runs out. It reports whether any attempt produced output and the last
+// attempt's error. failed is called for every attempt that is followed by
+// another.
+func runWithFallback(chain []*hwEncoderProfile, attempt func(*hwEncoderProfile) (bool, error), failed func(*hwEncoderProfile, error), cancelled func() bool) (bool, error) {
+	var err error
+	for i, hw := range chain {
+		var wrote bool
+		wrote, err = attempt(hw)
+		// A clean exit with no output (a start offset past the end of the
+		// file) is not something another encoder would do better.
+		if wrote || err == nil || cancelled() {
+			return wrote, err
+		}
+		if i < len(chain)-1 {
+			failed(hw, err)
+		}
 	}
+	return false, err
+}
 
-	// Buffered so both the natural-end goroutine and the client-disconnect goroutine
-	// can send without blocking — only the first signal is consumed.
-	done := make(chan struct{}, 2)
-
-	// Monitor client connection close
-	go func() {
-		<-r.Context().Done()
-		time.Sleep(300 * time.Millisecond)
-		cmd.Process.Kill()
-		done <- struct{}{}
-	}()
+// countingWriter remembers whether anything has been written through it.
+type countingWriter struct {
+	w io.Writer
+	n int64
+}
 
-	// Copy the command output to the HTTP response in a separate goroutine
-	go func() {
-		if _, err := io.Copy(w, stdout); err != nil {
-			cmd.Process.Kill()
-		}
-		// Signal natural end so the handler returns and the chunked-transfer
-		// terminator is flushed to the client.
-		done <- struct{}{}
-	}()
+func (c *countingWriter) Write(p []byte) (int, error) {
+	n, err := c.w.Write(p)
+	c.n += int64(n)
+	return n, err
+}
 
-	// Read and log the command standard error
-	go func() {
-		errOutput, _ := io.ReadAll(stderr)
-		if len(errOutput) > 0 {
-			logger.PrintAndLog("Transcoder", fmt.Sprintf("FFmpeg error output: %s", string(errOutput)), nil)
-		}
-	}()
+// streamMP4 runs one ffmpeg with the given arguments and copies its output to
+// the response until it finishes or the client goes away. It reports whether
+// any video reached the client, and ffmpeg's error if it failed.
+func streamMP4(w http.ResponseWriter, r *http.Request, args []string) (bool, error) {
+	cmd := exec.Command("ffmpeg", args...)
+	stdout, err := cmd.StdoutPipe()
+	if err != nil {
+		return false, err
+	}
+	// Only the end of stderr is kept: it holds the reason for a failure,
+	// while the start is the banner and the full stream listing.
+	stderr := &tailBuffer{}
+	cmd.Stderr = stderr
+	if err := cmd.Start(); err != nil {
+		return false, err
+	}
 
+	// Kill ffmpeg when the client goes away; the copy below then ends too.
+	finished := make(chan struct{})
+	defer close(finished)
 	go func() {
-		if err := cmd.Wait(); err != nil {
-			logger.PrintAndLog("Transcoder", fmt.Sprintf("FFmpeg process exited: %v", err), nil)
-			return
+		select {
+		case <-r.Context().Done():
+			time.Sleep(300 * time.Millisecond)
+			cmd.Process.Kill()
+		case <-finished:
 		}
 	}()
 
-	// Wait for the command to finish or client disconnect
-	<-done
-	logger.PrintAndLog("Transcoder", "[Media Server] Transcode client disconnected", nil)
+	out := &countingWriter{w: w}
+	if _, err := io.Copy(out, stdout); err != nil {
+		cmd.Process.Kill()
+	}
+	waitErr := cmd.Wait()
+	if waitErr != nil && r.Context().Err() == nil {
+		logger.PrintAndLog("Transcoder", "FFmpeg exited with an error: "+strings.TrimSpace(stderr.String()), waitErr)
+	}
+	return out.n > 0, waitErr
 }
 
 // buildMP4Args assembles the ffmpeg command line of TranscodeAndStream: the