Skip to content

High-performance browser automation bridge and multi-instance orchestrator with advanced stealth injection and real-time dashboard.

fix: record valid mp4/webm and honor gif scale at full resolution

Bosch5db678f7ca90
diff --git a/internal/cli/actions/actions_record.go b/internal/cli/actions/actions_record.go
index 1d1c18db..cd7776fa 100644
--- a/internal/cli/actions/actions_record.go
+++ b/internal/cli/actions/actions_record.go
@@ -108,11 +108,24 @@ func RecordStop(client *http.Client, base, token string) {
cli.Fatal("Encoding failed: %s", strings.TrimPrefix(err.Error(), "encode failed: "))
}
+ var warning string
+ if raw := apiclient.DoGetRaw(client, base, token, "/record/status", nil); raw != nil {
+ var st struct {
+ Warning string `json:"warning"`
+ }
+ if json.Unmarshal(raw, &st) == nil {
+ warning = st.Warning
+ }
+ }
+
if err := os.Rename(serverPath, outFile); err != nil {
cli.Fatal("Failed to move %s → %s: %v", serverPath, outFile, err)
}
fmt.Println(cli.StyleStdout(cli.SuccessStyle,
fmt.Sprintf("Saved → %s", outFile)))
+ if warning != "" {
+ fmt.Println(cli.StyleStdout(cli.WarningStyle, "Warning: "+warning))
+ }
}
func RecordStatus(client *http.Client, base, token string) {
diff --git a/internal/handlers/record.go b/internal/handlers/record.go
index c5c70dcf..aa8353eb 100644
--- a/internal/handlers/record.go
+++ b/internal/handlers/record.go
@@ -11,10 +11,8 @@ import (
const (
maxRecordDuration = 5 * time.Minute
- maxRecordFrames = 9000 // 5min × 30fps
- maxGIFFrames = 600 // ~2min at 5fps
- maxGIFFramePixels = 1280 * 720
- maxGIFEncodeBytes = 256 << 20 // 256 MB total paletted frame budget
+ maxRecordFrames = 9000 // 5min × 30fps
+ maxGIFFrames = 600 // ~2min at 5fps
maxTempBytes = 1 << 30 // 1 GB disk
maxOutputBytes = 256 << 20 // 256 MB encoded
encodeTimeout = 2 * time.Minute
@@ -24,6 +22,12 @@ const (
maxScale = 1.0
)
+// maxGIFEncodeBytes bounds the total in-memory paletted GIF frame data. It is the
+// real GIF safeguard now that --scale is honored at full resolution: oversized
+// captures simply fit fewer frames before truncation rather than being downscaled.
+// A var (not const) so tests can lower it to exercise budget truncation.
+var maxGIFEncodeBytes int64 = 256 << 20 // 256 MB
+
type recorderState int
const (
@@ -68,6 +72,7 @@ type RecordingStatus struct {
FPS int `json:"fps,omitempty"`
OutputPath string `json:"outputPath,omitempty"`
Error string `json:"error,omitempty"`
+ Warning string `json:"warning,omitempty"`
}
type recorder struct {
@@ -89,6 +94,7 @@ type recorder struct {
doneCh chan struct{}
outputPath string // final destination set by stop(); encoding writes here
encodeErr error // set by background encode goroutine
+ encodeWarn string // non-fatal encode warning (e.g. GIF truncated to fit budget)
captureFrame func(ctx context.Context, quality int) ([]byte, error)
}
@@ -206,7 +212,7 @@ func (rec *recorder) stop(callerOwner, outputPath string) (RecordStopResult, err
go func() {
tmpOut := outputPath + ".encoding.tmp"
- encErr := encodeToFile(tmpDir, tmpOut, format, fps, scale)
+ warn, encErr := encodeToFile(tmpDir, tmpOut, format, fps, scale)
if encErr == nil {
encErr = os.Rename(tmpOut, outputPath)
if encErr != nil {
@@ -218,6 +224,7 @@ func (rec *recorder) stop(callerOwner, outputPath string) (RecordStopResult, err
rec.mu.Lock()
rec.encodeErr = encErr
+ rec.encodeWarn = warn
rec.state = stateFinished
if rec.tabCancel != nil {
rec.tabCancel()
@@ -265,6 +272,7 @@ func (rec *recorder) cleanup() {
rec.owner = ""
rec.outputPath = ""
rec.encodeErr = nil
+ rec.encodeWarn = ""
}
func (rec *recorder) activeFormat() string {
@@ -293,6 +301,7 @@ func (rec *recorder) status() RecordingStatus {
if rec.encodeErr != nil {
s.Error = rec.encodeErr.Error()
}
+ s.Warning = rec.encodeWarn
return s
}
return RecordingStatus{
diff --git a/internal/handlers/record_encode.go b/internal/handlers/record_encode.go
index a79bfffa..cb43e87a 100644
--- a/internal/handlers/record_encode.go
+++ b/internal/handlers/record_encode.go
@@ -18,7 +18,7 @@ import (
"strconv"
)
-func encodeToFile(tmpDir, outputPath, format string, fps int, scale float64) error {
+func encodeToFile(tmpDir, outputPath, format string, fps int, scale float64) (string, error) {
ctx, cancel := context.WithTimeout(context.Background(), encodeTimeout)
defer cancel()
@@ -26,18 +26,18 @@ func encodeToFile(tmpDir, outputPath, format string, fps int, scale float64) err
case "gif":
return encodeGIFToFile(tmpDir, outputPath, fps, scale)
case "webm":
- return encodeFFmpegToFile(ctx, tmpDir, outputPath, format, fps, scale, "libvpx", "-crf", "10", "-b:v", "1M")
+ return "", encodeFFmpegToFile(ctx, tmpDir, outputPath, format, fps, scale, "libvpx", "-crf", "10", "-b:v", "1M")
case "mp4":
- return encodeFFmpegToFile(ctx, tmpDir, outputPath, format, fps, scale, "libx264", "-pix_fmt", "yuv420p", "-crf", "23")
+ return "", encodeFFmpegToFile(ctx, tmpDir, outputPath, format, fps, scale, "libx264", "-pix_fmt", "yuv420p", "-crf", "23")
default:
- return fmt.Errorf("unsupported format: %s", format)
+ return "", fmt.Errorf("unsupported format: %s", format)
}
}
-func encodeGIFToFile(tmpDir, outputPath string, fps int, scale float64) error {
+func encodeGIFToFile(tmpDir, outputPath string, fps int, scale float64) (string, error) {
files, err := discoverFrames(tmpDir, maxGIFFrames)
if err != nil {
- return err
+ return "", err
}
delay := 100 / fps
@@ -47,12 +47,13 @@ func encodeGIFToFile(tmpDir, outputPath string, fps int, scale float64) error {
outFile, err := os.OpenFile(outputPath, os.O_WRONLY|os.O_CREATE|os.O_EXCL, 0600)
if err != nil {
- return fmt.Errorf("create gif output: %w", err)
+ return "", fmt.Errorf("create gif output: %w", err)
}
defer func() { _ = outFile.Close() }()
g := &gif.GIF{LoopCount: 0}
var palettedBytes int64
+ truncated := false
for _, f := range files {
img, ok := loadFrame(f)
@@ -61,11 +62,15 @@ func encodeGIFToFile(tmpDir, outputPath string, fps int, scale float64) error {
}
img = scaleFrameForGIF(img, scale)
-
bounds := img.Bounds()
pixels := bounds.Dx() * bounds.Dy()
- if palettedBytes+int64(pixels) > maxGIFEncodeBytes {
+
+ // Honor the requested resolution; cap total frames (not per-frame size) so
+ // memory stays bounded. The first frame is always kept so a single large
+ // frame still produces a valid GIF.
+ if len(g.Image) > 0 && palettedBytes+int64(pixels) > maxGIFEncodeBytes {
slog.Info("GIF encode: memory budget reached, truncating", "frames", len(g.Image))
+ truncated = true
break
}
@@ -77,14 +82,23 @@ func encodeGIFToFile(tmpDir, outputPath string, fps int, scale float64) error {
}
if len(g.Image) == 0 {
- return fmt.Errorf("no frames to encode")
+ return "", fmt.Errorf("no frames to encode")
}
lw := &limitedWriter{w: outFile, max: int64(maxOutputBytes)}
if err := gif.EncodeAll(lw, g); err != nil {
- return fmt.Errorf("gif encode: %w", err)
+ return "", fmt.Errorf("gif encode: %w", err)
+ }
+
+ var warning string
+ if truncated {
+ warning = fmt.Sprintf(
+ "GIF was truncated to %d frames to stay within the ~%d MB in-memory budget at this "+
+ "resolution. Lower --scale or record to .mp4 or .webm for the full-length clip.",
+ len(g.Image), maxGIFEncodeBytes>>20)
+ slog.Warn("GIF encode: truncated to fit memory budget", "frames", len(g.Image))
}
- return outFile.Close()
+ return warning, outFile.Close()
}
// discoverFrames returns the sorted list of captured JPEG frame files in tmpDir,
@@ -115,18 +129,12 @@ func loadFrame(path string) (img image.Image, ok bool) {
return img, true
}
-// scaleFrameForGIF applies the caller-requested scale, then enforces the GIF
-// per-frame pixel budget by downscaling oversized frames.
+// scaleFrameForGIF applies the caller-requested scale. At scale 1.0 the frame is
+// kept at full resolution — no forced downscale. Memory is bounded by the total
+// frame budget in encodeGIFToFile, not by shrinking individual frames.
func scaleFrameForGIF(img image.Image, scale float64) image.Image {
if scale != 1.0 && scale > 0 {
- img = scaleImage(img, scale)
- }
-
- bounds := img.Bounds()
- pixels := bounds.Dx() * bounds.Dy()
- if pixels > maxGIFFramePixels {
- ratio := float64(maxGIFFramePixels) / float64(pixels)
- img = scaleImage(img, ratio)
+ return scaleImage(img, scale)
}
return img
}
@@ -153,6 +161,11 @@ func encodeFFmpegToFile(ctx context.Context, tmpDir, outputPath, format string,
args = append(args, "-c:v", codec)
args = append(args, extraArgs...)
args = append(args, "-fs", strconv.Itoa(maxOutputBytes))
+ // The output path carries a ".encoding.tmp" suffix (see recorder.stop), so
+ // ffmpeg cannot infer the container from the extension. Name the muxer
+ // explicitly — "mp4"/"webm" are valid format names — or it aborts with
+ // "Unable to choose an output format" (issue #585).
+ args = append(args, "-f", format)
args = append(args, outputPath)
// #nosec G204 -- ffmpeg executable is fixed and args are built from validated,
diff --git a/internal/handlers/record_encode_e2e_test.go b/internal/handlers/record_encode_e2e_test.go
new file mode 100644
index 00000000..8eb44327
--- /dev/null
+++ b/internal/handlers/record_encode_e2e_test.go
@@ -0,0 +1,195 @@
+package handlers
+
+import (
+ "bytes"
+ "fmt"
+ "image"
+ "image/color"
+ "image/gif"
+ "image/jpeg"
+ "os"
+ "os/exec"
+ "path/filepath"
+ "strings"
+ "testing"
+)
+
+// writeTestFrames generates n solid-colour JPEG frames named frame_%06d.jpg in
+// dir, matching the names ffmpeg expects (see encodeFFmpegToFile).
+func writeTestFrames(t *testing.T, dir string, n, w, h int) {
+ t.Helper()
+ for i := 0; i < n; i++ {
+ img := image.NewRGBA(image.Rect(0, 0, w, h))
+ shade := uint8((i * 40) % 256)
+ for y := 0; y < h; y++ {
+ for x := 0; x < w; x++ {
+ img.Set(x, y, color.RGBA{R: shade, G: uint8(x % 256), B: uint8(y % 256), A: 255})
+ }
+ }
+ var buf bytes.Buffer
+ if err := jpeg.Encode(&buf, img, &jpeg.Options{Quality: 90}); err != nil {
+ t.Fatalf("encode frame %d: %v", i, err)
+ }
+ name := filepath.Join(dir, fmt.Sprintf("frame_%06d.jpg", i))
+ if err := os.WriteFile(name, buf.Bytes(), 0600); err != nil {
+ t.Fatalf("write frame %d: %v", i, err)
+ }
+ }
+}
+
+// TestEncodeToFile_TempSuffixProducesValidContainer is the regression test for
+// issue #585: recordings are encoded to a "<output>.encoding.tmp" path (see
+// recorder.stop), so ffmpeg cannot infer the container from the file extension.
+// Before the fix the mp4/webm muxer aborts with "Unable to choose an output
+// format ... .encoding.tmp"; after the fix the format is passed explicitly and
+// a valid container is written. The test drives the exact production call path:
+// encodeToFile(tmpDir, output+".encoding.tmp", format, ...).
+func TestEncodeToFile_TempSuffixProducesValidContainer(t *testing.T) {
+ if !ffmpegAvailable() {
+ t.Skip("ffmpeg not available")
+ }
+
+ cases := []struct {
+ format string
+ muxerName string // container ffprobe should report
+ }{
+ {"mp4", "mp4"},
+ {"webm", "webm"},
+ }
+
+ for _, tc := range cases {
+ t.Run(tc.format, func(t *testing.T) {
+ frameDir := t.TempDir()
+ writeTestFrames(t, frameDir, 4, 320, 240)
+
+ outDir := t.TempDir()
+ finalPath := filepath.Join(outDir, "capture."+tc.format)
+ // Replicate recorder.stop(): encode into the .encoding.tmp sibling.
+ tmpOut := finalPath + ".encoding.tmp"
+
+ if _, err := encodeToFile(frameDir, tmpOut, tc.format, 30, 1.0); err != nil {
+ t.Fatalf("encodeToFile(%s) failed (issue #585): %v", tc.format, err)
+ }
+
+ info, err := os.Stat(tmpOut)
+ if err != nil {
+ t.Fatalf("expected encoded file at %s: %v", tmpOut, err)
+ }
+ if info.Size() == 0 {
+ t.Fatalf("encoded %s file is empty", tc.format)
+ }
+
+ // Prove the bytes are a real container of the requested format, not
+ // just a non-empty file, by asking ffprobe to name the format.
+ assertContainerFormat(t, tmpOut, tc.muxerName)
+ })
+ }
+}
+
+// TestEncodeGIF_HonorsScaleAndWarnsOnTruncation covers the GIF half of issue #585.
+// After the fix the requested --scale is honored at full resolution (no forced
+// per-frame downscale); memory is bounded by a total-frame budget, and when that
+// budget truncates the frame count a warning is surfaced so it is not silent.
+func TestEncodeGIF_HonorsScaleAndWarnsOnTruncation(t *testing.T) {
+ // A large HiDPI-style frame that the old code would have force-downscaled.
+ const bigW, bigH = 1600, 1000
+
+ t.Run("scale_1_keeps_full_resolution", func(t *testing.T) {
+ frameDir := t.TempDir()
+ writeTestFrames(t, frameDir, 3, bigW, bigH)
+ out := filepath.Join(t.TempDir(), "capture.gif.encoding.tmp")
+
+ warning, err := encodeToFile(frameDir, out, "gif", 5, 1.0)
+ if err != nil {
+ t.Fatalf("encodeToFile(gif) failed: %v", err)
+ }
+ if warning != "" {
+ t.Fatalf("expected no warning at scale 1 within budget, got %q", warning)
+ }
+ w, h := gifDimensions(t, out)
+ if w != bigW || h != bigH {
+ t.Fatalf("scale 1 must keep full resolution %dx%d, got %dx%d", bigW, bigH, w, h)
+ }
+ })
+
+ t.Run("scale_downscale_honored", func(t *testing.T) {
+ frameDir := t.TempDir()
+ writeTestFrames(t, frameDir, 3, bigW, bigH)
+ out := filepath.Join(t.TempDir(), "capture.gif.encoding.tmp")
+
+ warning, err := encodeToFile(frameDir, out, "gif", 5, 0.5)
+ if err != nil {
+ t.Fatalf("encodeToFile(gif) failed: %v", err)
+ }
+ if warning != "" {
+ t.Fatalf("expected no warning at scale 0.5, got %q", warning)
+ }
+ w, h := gifDimensions(t, out)
+ if w != bigW/2 || h != bigH/2 {
+ t.Fatalf("expected --scale honored to %dx%d, got %dx%d", bigW/2, bigH/2, w, h)
+ }
+ })
+
+ t.Run("budget_truncation_warns", func(t *testing.T) {
+ // Shrink the budget so a handful of frames overflows it, exercising the
+ // truncation path cheaply. Restore afterwards.
+ orig := maxGIFEncodeBytes
+ maxGIFEncodeBytes = int64(bigW*bigH) * 2 // room for ~2 frames
+ defer func() { maxGIFEncodeBytes = orig }()
+
+ frameDir := t.TempDir()
+ writeTestFrames(t, frameDir, 5, bigW, bigH) // 5 recorded, only ~2 fit
+ out := filepath.Join(t.TempDir(), "capture.gif.encoding.tmp")
+
+ warning, err := encodeToFile(frameDir, out, "gif", 5, 1.0)
+ if err != nil {
+ t.Fatalf("encodeToFile(gif) failed: %v", err)
+ }
+ if warning == "" {
+ t.Fatal("expected a truncation warning when frames overflow the budget, got none")
+ }
+ // Full resolution is still preserved on the frames that were kept.
+ w, h := gifDimensions(t, out)
+ if w != bigW || h != bigH {
+ t.Fatalf("truncated GIF must keep full resolution %dx%d, got %dx%d", bigW, bigH, w, h)
+ }
+ })
+}
+
+// gifDimensions decodes the GIF at path and returns its frame dimensions.
+func gifDimensions(t *testing.T, path string) (w, h int) {
+ t.Helper()
+ data, err := os.ReadFile(path)
+ if err != nil {
+ t.Fatalf("read gif: %v", err)
+ }
+ img, err := gif.DecodeAll(bytes.NewReader(data))
+ if err != nil {
+ t.Fatalf("decode gif: %v", err)
+ }
+ if len(img.Image) == 0 {
+ t.Fatal("gif has no frames")
+ }
+ b := img.Image[0].Bounds()
+ return b.Dx(), b.Dy()
+}
+
+// assertContainerFormat uses ffprobe (shipped with ffmpeg) to confirm the file
+// is a valid container whose detected format includes want.
+func assertContainerFormat(t *testing.T, path, want string) {
+ t.Helper()
+ if _, err := exec.LookPath("ffprobe"); err != nil {
+ t.Logf("ffprobe not available; skipping container-format assertion")
+ return
+ }
+ out, err := exec.Command("ffprobe", "-v", "error",
+ "-show_entries", "format=format_name",
+ "-of", "default=nokey=1:noprint_wrappers=1", path).Output()
+ if err != nil {
+ t.Fatalf("ffprobe could not parse %s as a media file: %v", path, err)
+ }
+ got := strings.TrimSpace(string(out))
+ if !strings.Contains(got, want) {
+ t.Fatalf("ffprobe reports format %q, want it to contain %q", got, want)
+ }
+}