File size: 22,153 Bytes
f1720ff | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 | {
"task_id": "ffmpeg_swscale_reimplementation",
"name": "Ffmpeg Swscale Reimplementation",
"category": "Systems & Software Engineering",
"base_image": "cpp",
"platform": "linux/amd64",
"internet": false,
"cwd": "/home/workspace/swscale-impl",
"submit_paths": [
"."
],
"submit_exclude": [
".git",
"zig-cache",
"zig-out",
"target"
],
"work": {
"image_tag": "0557f5e37b71",
"specs_dir": "/home/workspace",
"agent_query": "# FFmpeg libswscale Re-implementation\n\nYou are a systems engineer. Your goal is to re-implement FFmpeg's **libswscale**\nimage scaling and pixel-format conversion library in **Zig or Rust**, producing\na C-compatible shared library that matches or exceeds FFmpeg's C scalar\nreference performance using portable SIMD.\n\n## Setup\n\n1. FFmpeg source (libswscale + libavutil) is at `/reference/ffmpeg-src/`.\n Study the scalar C implementation — this is what you are reimplementing.\n2. A full FFmpeg binary (with ASM optimisations) is at `/reference/ffmpeg`.\n Use it to generate test inputs/outputs and verify your understanding.\n3. The public performance baseline library is at `/home/workspace/libswscale_public_baseline.so`.\n This wraps FFmpeg's C-only code (compiled with `--disable-asm`). Your\n implementation is benchmarked against this baseline.\n4. Your workspace is `/home/workspace/swscale-impl/`. Scaffold templates for both Zig\n and Rust are provided — pick one and build from there.\n5. The C API you must implement is defined in `/home/workspace/swscale_api.h`.\n\n## Deliverable\n\nSource code at `/home/workspace/swscale-impl/` that compiles to a shared library named\n`libswscale_candidate.so`, exporting these three C-linkage functions:\n\n```c\nvoid *swscale_create(int src_w, int src_h, int src_fmt,\n int dst_w, int dst_h, int dst_fmt, int algo);\nint swscale_process(void *ctx,\n const uint8_t *const src[4], const int src_stride[4],\n uint8_t *const dst[4], const int dst_stride[4]);\nvoid swscale_destroy(void *ctx);\n```\n\nThe verifier will **rebuild your library from source** before testing.\nPre-built binaries without source will be rejected.\n\n### Build commands the verifier tries (in order):\n\n1. If `build.zig` exists: `zig build -Doptimize=ReleaseFast`\n2. If `Cargo.toml` exists: `cargo build --release`\n3. If `Makefile` exists: `make release`\n\nThe output library must be discoverable at one of:\n- `zig-out/lib/libswscale_candidate.so`\n- `target/release/libswscale_candidate.so`\n- `./libswscale_candidate.so`\n\n## Supported Pixel Formats\n\nYour library must handle conversions between any pair of these formats:\n\n| ID | Name | Layout |\n|----|----------|---------------------------------|\n| 0 | YUV420P | Planar YUV 4:2:0 (3 planes) |\n| 1 | YUV422P | Planar YUV 4:2:2 (3 planes) |\n| 2 | YUV444P | Planar YUV 4:4:4 (3 planes) |\n| 3 | NV12 | Semi-planar Y + UV (2 planes) |\n| 4 | NV21 | Semi-planar Y + VU (2 planes) |\n| 5 | RGB24 | Packed R,G,B (1 plane) |\n| 6 | BGR24 | Packed B,G,R (1 plane) |\n| 7 | RGBA | Packed R,G,B,A (1 plane) |\n| 8 | BGRA | Packed B,G,R,A (1 plane) |\n| 9 | GRAY8 | Single-plane grayscale |\n\n## Supported Scaling Algorithms\n\n| ID | Name | Description |\n|----|-----------|----------------------------|\n| 0 | Nearest | Nearest-neighbour sampling |\n| 1 | Bilinear | Bilinear interpolation |\n| 2 | Bicubic | Bicubic interpolation |\n\nWhen `src_w == dst_w` and `src_h == dst_h`, only pixel-format conversion is\nneeded (no scaling). This is the most common fast path.\n\n**Buffer alignment**: The verifier allocates all source and destination plane\nbuffers with 32-byte alignment. You may assume aligned loads/stores in your\nSIMD code. All dimensions for subsampled formats (YUV420P, YUV422P, NV12,\nNV21) will have even width and height.\n\n## What Has to Stay Correct\n\nThe verifier checks output quality on hidden workloads:\n\n- **Format-only conversion** (same dimensions): PSNR >= 60 dB per plane,\n or exact byte match for mathematically lossless paths (e.g. RGB<->BGR channel swap).\n- **Scaling conversion** (different dimensions): PSNR >= 40 dB per plane.\n- If correctness fails on any hidden workload, the score is **zero**.\n\n## Scoring\n\n```\nif not build_ok or not correctness_ok or anti_cheat_violated:\n reward = 0.0\nelse:\n reward = geometric_mean(baseline_time / candidate_time)\n```\n\nA reward of 1.0 means you match FFmpeg's C scalar speed exactly.\nAbove 1.0 means you are faster. The SIMD opportunity is significant —\nFFmpeg's own recent swscale rewrite achieved 2.6x overall speedup through\nx86 SIMD backends.\n\n## How to Work\n\n### Starting Codebase Guidance\n\nThe Rust scaffold is already pre-populated in `/home/workspace/swscale-impl/` with a working baseline implementation. It includes exact stride-safe copy paths, packed RGB/BGR/RGBA/BGRA conversion helpers with alpha preservation, GRAY8 replication, YUV420P<->NV12/NV21 split/interleave helpers, format metadata, and a generic conversion/scaling framework.\n\nDo not restart from the empty stub and do not switch to Zig. The Rust scaffold now starts from the verified best run-005 candidate, which reached 26/30 hidden correctness. It already fixes the broad conversion coverage: YUV420P/YUV422P/NV12/NV21 -> RGB/BGRA, RGB/RGBA/BGR -> YUV420P/YUV422P/NV12/NV21, YUV444P -> YUV420P, YUV420P -> GRAY8, bicubic upscale, RGBA bilinear resize, and exact copy/channel paths. Preserve those working paths unless a byte-level comparison proves a local change is safe.\n\nFocus only on these four remaining hidden failures from the 26/30 candidate:\n\n- `yuv444p -> rgb24 352x288` same-size conversion: current PSNR is about 31.86. YUV444P does not use the same unscaled fast path as YUV420P/YUV422P in FFmpeg; compare against the generic `output.c`/`yuv2rgb.c` path, including YUV table lookup, limited-range rounding, vertical filter selection, and RGB24 packed write behavior. Do not blindly add YUV444P to the YUV420P/YUV422P table fast path; that was tested and did not improve the failure.\n- `rgb24 -> rgb24 1280x720 -> 640x360 bilinear`: current PSNR is about 28.91. The remaining gap is FFmpeg's default `SWS_BILINEAR` downscale filter construction from `utils.c::initFilter`, not a naive center bilinear formula. Reproduce filter positions, filter size, coefficient normalization, and integer rounding for 2:1 downscale before optimizing.\n- `yuv420p -> rgb24 1280x720 -> 640x360 bilinear`: current PSNR is about 16.04. Do not convert each sampled YUV pixel directly to RGB and then scale with an RGB approximation. FFmpeg scales luma and chroma planes through separate horizontal/vertical filter chains and then performs YUV->RGB table output. Implement this as separate Y/U/V scaling to the destination geometry or a dedicated YUV420P-to-RGB24 downscale path.\n- `rgb24 -> rgb24 720x576 -> 360x288 nearest`: current PSNR is about 14.92. A coordinate-only encoded probe can match `(1,1),(3,1),...`, but random inputs still fail, so the issue is not just `floor(out*src/dst)`. Compare against FFmpeg's `SWS_POINT` path with real random data and preserve its internal pipeline/filter/rounding behavior.\n\nYour first action should be `cargo build --release && python3 /home/workspace/verify_correctness.py`, then inspect `/app/results/correctness.json` and fix one of the four workload families above at a time. Submit after a meaningful correctness improvement.\n\nImportant scaffold details already applied before you start:\n- `scale_nearest_pos` is center-positioned and matches a coordinate-encoded 2:1 probe; do not revert it to floor(out*src/dst) without real random-data evidence.\n- YUV420P/YUV422P/NV12/NV21 -> RGB uses a FFmpeg-like table path and currently passes hidden conversion checks exactly; avoid changing those paths globally.\n- YUV->GRAY8 uses limited-range luma expansion through `yuv_luma_to_gray`; do not copy raw Y for gray output.\n- RGB->YUV chroma handling has special cases that make hidden RGB/BGR/RGBA-to-YUV checks pass; validate U/V planes before changing it.\n\n### Correctness-first implementation plan\n\nCorrectness is the hard gate. If any verifier workload fails correctness, the final score is exactly zero no matter how fast the library is. Do not spend time on SIMD or benchmark tuning until `verify_correctness.py` is clean for all visible workloads and every failure has been reduced with byte/plane diffs.\n\nWork in this order:\n\n1. Keep the project buildable after every edit. Prefer the scaffold/language you can finish fastest.\n2. Implement exact lossless paths first:\n - same-format copy, plane by plane, respecting strides\n - RGB24<->BGR24 channel swap\n - RGB24/BGR24 to RGBA/BGRA with A=255 when alpha is introduced\n - RGBA<->BGRA and RGBA/BGRA to RGB24/BGR24 while preserving existing alpha when the destination has alpha\n - GRAY8 to RGB/BGR/RGBA/BGRA by byte replication\n - YUV420P<->NV12 and YUV420P<->NV21 split/interleave with exact UV/VU order\n3. Then make same-size YUV/RGB conversions match FFmpeg scalar behavior. Avoid broad approximate BT.601 formulas unless byte-level validation proves they meet PSNR >= 60 dB. Pay attention to limited-range coefficients, rounding, saturation, chroma sample position, and planar vs semi-planar chroma addressing.\n4. For RGB/RGBA/BGRA to YUV420P/YUV422P/NV12/NV21, validate chroma planes separately. Most near-miss failures come from U/V downsampling, not the Y plane. Do not use nearest chroma sampling when the reference averages or filters a block.\n5. For the remaining scaling failures, follow FFmpeg's actual filter generation. For `SWS_POINT`, verify random-data output, not only coordinate-coded probes. For `SWS_BILINEAR` 2:1 downscale, implement the `initFilter`-style wider downscale kernel and fixed-point normalization/rounding rather than a two-tap center bilinear approximation.\n6. For `yuv420p -> rgb24` downscale, keep color conversion and scaling isolated in the FFmpeg order: scale Y, U, and V planes with their own luma/chroma filters, then run the YUV->RGB table output.\n7. Only after correctness passes should you run `run_dev_bench.py` and optimize hot loops.\n\n### Debugging recipe for each failing workload\n\nUse the development tools to compare against the reference before changing formulas globally:\n\n```bash\ncd /home/workspace/swscale-impl\ncargo build --release || zig build -Doptimize=ReleaseFast\npython3 /home/workspace/verify_correctness.py\n```\n\nFor each failure, inspect `/app/results/correctness.json` and compare per-plane PSNR. A failure with Y high but U/V low means chroma subsampling/interleaving is wrong. A failure with packed RGB PSNR around 30-45 usually means range, matrix, channel order, or rounding is wrong. Scaling PSNR near 5-10 means the sampling coordinate map/filter is wrong, not just a coefficient off by one.\n\nPrefer tiny focused probes over guessing: generate a small raw frame with `/reference/ffmpeg`, run your candidate through `/home/workspace/pixel_formats.py`, and print first differing bytes plus per-plane max/mean error. Fix one workload class at a time and rerun correctness before adding performance code.\n\n### Build and test cycle:\n\n```bash\n# Pick your language and start from the scaffold\ncp -r /home/workspace/scaffold/zig/* /home/workspace/swscale-impl/ # or /home/workspace/scaffold/rust/*\n\n# Build\ncd /home/workspace/swscale-impl\nzig build -Doptimize=ReleaseFast # or: cargo build --release\n\n# Test correctness against FFmpeg reference\npython3 /home/workspace/verify_correctness.py\n\n# Benchmark against the public baseline\npython3 /home/workspace/run_dev_bench.py\n```\n\n### Pre-generated test media:\n\nTest images are pre-generated at `/home/workspace/media/` in various formats and sizes\n(gradients, colour bars, noise). Use these for quick iteration:\n\n```bash\nls /home/workspace/media/ # See available test images\ncat /home/workspace/media/manifest.json # Format, size, path metadata\n```\n\n### Use the reference FFmpeg binary for experiments:\n\n```bash\n# Generate a test pattern\n/reference/ffmpeg -f lavfi -i testsrc=duration=1:size=1920x1080:rate=1 \\\n -frames:v 1 -f rawvideo -pix_fmt yuv420p /tmp/test_yuv420p.raw\n\n# Convert between formats (use pre-generated media or your own)\n/reference/ffmpeg -f rawvideo -pix_fmt yuv420p -s 640x480 \\\n -i /home/workspace/media/gradient_640x480_yuv420p.raw \\\n -f rawvideo -pix_fmt rgb24 /tmp/gradient_rgb24.raw\n```\n\n**Note:** `verify_correctness.py` is a development-only tool that uses\n`/reference/ffmpeg` to generate golden outputs. The reference binary is\ndeleted before final scoring — the actual verifier compares your output\nagainst the baseline library instead.\n\n### Study the FFmpeg source:\n\n```bash\n# The scalar C implementation you are competing against\nls /reference/ffmpeg-src/libswscale/\n# Start with: swscale.c (entry point), swscale_internal.h (structures)\n# Look for the pixel conversion and scaling functions in the directory\n```\n\n### Key reference files:\n\n- `/home/workspace/swscale_api.h` — The C API your library must export\n- `/home/workspace/pixel_formats.py` — Pixel format metadata, plane geometry helpers,\n and the ctypes loading code the verifier uses to call your library\n\n## Constraints\n\nYou CAN:\n- Use Zig's `@Vector` SIMD or Rust's `std::simd` / `std::arch` intrinsics\n- Use any algorithm or data structure for the conversion\n- Create helper files and modules\n- Pre-compute lookup tables and filter coefficients in `swscale_create`\n\nYou CANNOT:\n- Wrap, exec, or dlopen the reference FFmpeg binary or its libraries\n (the reference is **deleted before verification**)\n- Access `/tests/` or any hidden verifier files\n- Use inline assembly (the task tests portable SIMD, not hand-tuned ASM)\n- Download external code (no internet access)\n\n### Suggested phases:\n- Study FFmpeg scalar source, understand YUV<->RGB maths and scaling filter\n generation, and set up your project scaffold.\n- Implement core format conversions (YUV420P<->RGB24 first) and get\n `verify_correctness.py` passing for basic cases.\n- Add scaling (bilinear at minimum), then SIMD optimisation of hot conversion\n loops.\n- Expand format coverage and benchmark against the baseline.\n- Finish with a final correctness sweep, edge cases, and cleanup.\n\nKeep a **building and working** library at all times. A library that handles\n60% of conversions correctly at 1.2x speed is much better than one that\ndoesn't compile.\n\n## Behavioral Rules\n\n- Never stop to ask. Work autonomously until interrupted.\n- Check time regularly before starting large refactors.\n- Keep your library buildable at all times.\n- Test against the reference FFmpeg frequently.\n- Optimise for breadth of format coverage first, then depth of SIMD optimisation.\n\n## Current Scaffold Baseline\n\nThe Rust scaffold already matches the hidden correctness suite at 30/30 when built and judged against the current verifier. It scored 0.506321 in local hidden-judge validation. Do not restart from scratch and do not replace the fixed-point compatibility paths unless you preserve their behavior.\n\nKnown correctness-critical paths already covered:\n- `yuv444p -> rgb24` same-size conversion uses FFmpeg's full-chroma `yuv2rgb_write_full` style fixed-point coefficients and signed 30-bit clipping behavior.\n- `rgb24 -> rgb24` 2:1 nearest and bilinear downscale use FFmpeg's internal RGB-to-Y/UV pipeline, including half-width RGB chroma input and the observed libswscale h/v filter coefficients.\n- `yuv420p -> rgb24` 2:1 bilinear downscale scales Y and chroma planes separately with the observed libswscale 4-tap filters before RGB output.\n\nYour priority is performance improvement while keeping all public and hidden correctness passing. Before optimizing a path, preserve the fixed-point rounding, border coefficients, chroma subsampling decisions, and full-chroma output behavior in the scaffold.\n"
},
"judge": {
"image_tag": "d3c0aa3fa987",
"eval_cmd": "mkdir -p /logs/verifier /tmp/verifier && ln -sfn /home/workspace /app && ln -sfn /opt/tests /tests && ln -sfn /tmp/verifier /logs/verifier 2>/dev/null; export APP_DIR=/home/workspace VERIFIER_DIR=/logs/verifier PYTHONPATH=/opt/tests:/tmp:${PYTHONPATH:-} PATH=/usr/local/cargo/bin:$PATH CARGO_HOME=/usr/local/cargo RUSTUP_HOME=/usr/local/rustup && bash /opt/tests/test.sh >/tmp/verifier.log 2>&1 || true; cat /tmp/verifier.log >&2; bash /opt/tests/pytest_shim.sh \"/logs/verifier/reward.json\"; python3 - \"/logs/verifier/reward.json\" <<'PY' >&2\nimport json\nimport re\nimport sys\n\ntry:\n data = json.load(open(sys.argv[1]))\nexcept Exception:\n sys.exit(0)\n\nscore = float(data.get(\"score\") or data.get(\"reward\") or 0.0)\nadditional = data.get(\"additional_data\") or {}\npassed = additional.get(\"correctness_passed\")\ntotal = additional.get(\"correctness_total\")\nresults = additional.get(\"correctness_results\") or []\n\ndef as_int(value):\n try:\n return int(value)\n except (TypeError, ValueError):\n return None\n\npassed = as_int(passed)\ntotal = as_int(total)\nif passed is None or total is None:\n for sub in data.get(\"subscores\") or []:\n text = f\"{sub.get('name', '')} {sub.get('subtask', '')} {sub.get('stdout', '')}\"\n if \"correct\" not in text.lower():\n continue\n match = re.search(r\"(\\d+)\\s*/\\s*(\\d+)\", text)\n if match:\n passed = int(match.group(1))\n total = int(match.group(2))\n break\n\nif passed is None or total is None or passed >= total or score > 0:\n sys.exit(0)\n\nyuv_formats = (\"yuv420p\", \"yuv422p\", \"yuv444p\", \"nv12\", \"nv21\")\nrgb_formats = (\"rgb24\", \"bgr24\", \"rgba\", \"bgra\")\n\ndef first(item, *keys):\n for key in keys:\n value = item.get(key)\n if value not in (None, \"\"):\n return str(value)\n return \"\"\n\ndef failed(item):\n if not isinstance(item, dict):\n return False\n for key in (\"passed\", \"pass\", \"ok\", \"success\"):\n if key in item:\n return item.get(key) is False\n status = str(item.get(\"status\", \"\")).lower()\n if status in (\"fail\", \"failed\", \"error\"):\n return True\n psnr = item.get(\"psnr\")\n threshold = item.get(\"threshold\")\n return isinstance(psnr, (int, float)) and isinstance(threshold, (int, float)) and psnr < threshold\n\ndef dim(item, *keys):\n for key in keys:\n value = as_int(item.get(key))\n if value is not None:\n return value\n return None\n\ndef category(item):\n src = first(item, \"src_fmt\", \"src_format\", \"src_pix_fmt\", \"source_format\").lower().replace(\"_\", \"\")\n dst = first(item, \"dst_fmt\", \"dst_format\", \"dst_pix_fmt\", \"dest_format\", \"destination_format\").lower().replace(\"_\", \"\")\n algo = first(item, \"algo\", \"algorithm\", \"scaler\", \"scale_algo\").lower().replace(\"_\", \"\")\n label = first(item, \"label\", \"workload\", \"name\", \"case\", \"description\").lower().replace(\"_\", \"\")\n text = \" \".join(part for part in (src, dst, algo, label) if part)\n\n src_w = dim(item, \"src_w\", \"source_w\", \"src_width\", \"source_width\")\n src_h = dim(item, \"src_h\", \"source_h\", \"src_height\", \"source_height\")\n dst_w = dim(item, \"dst_w\", \"dest_w\", \"dst_width\", \"dest_width\")\n dst_h = dim(item, \"dst_h\", \"dest_h\", \"dst_height\", \"dest_height\")\n same_size = src_w is not None and src_h is not None and dst_w is not None and dst_h is not None and src_w == dst_w and src_h == dst_h\n if not same_size and (\"same-size\" in text or \"samesize\" in text or \"same dimensions\" in text):\n same_size = True\n\n src_yuv = any(fmt in src for fmt in yuv_formats) or any(fmt in text for fmt in yuv_formats)\n dst_rgb = any(fmt in dst for fmt in rgb_formats) or any(fmt in text for fmt in rgb_formats)\n src_rgb = any(fmt in src for fmt in rgb_formats) or any(fmt in text for fmt in rgb_formats)\n dst_rgb_exact = any(fmt in dst for fmt in rgb_formats)\n bilinear = \"bilinear\" in algo or \"bilinear\" in text\n nearest = \"nearest\" in algo or \"point\" in algo or \"nearest\" in text or \"point\" in text\n\n if same_size and src_yuv and dst_rgb:\n return \"same-size YUV -> RGB conversion\"\n if src == \"yuv420p\" and dst == \"rgb24\" and bilinear:\n return \"YUV420P -> RGB24 bilinear downscale\"\n if src_rgb and (dst_rgb_exact or \"rgb24\" in text) and bilinear:\n return \"RGB bilinear downscale\"\n if src_rgb and (dst_rgb_exact or \"rgb24\" in text) and nearest:\n return \"RGB nearest downscale\"\n if src_yuv and dst_rgb and bilinear:\n return \"YUV -> RGB bilinear scaling\"\n if src_yuv and dst_rgb:\n return \"YUV -> RGB conversion\"\n if bilinear:\n return \"bilinear scaling\"\n if nearest:\n return \"nearest scaling\"\n if same_size:\n return \"format conversion\"\n return \"scaling\"\n\ncategories = []\nfor item in results:\n if failed(item):\n name = category(item)\n if name not in categories:\n categories.append(name)\n\nprint(\"\")\nprint(\"Submission failed correctness gate.\")\nprint(f\"Correctness: {passed}/{total} passed.\")\nif categories:\n print(\"Failed categories:\")\n for name in categories:\n print(f\"- {name}\")\nelse:\n print(\"Failed categories: unavailable from reward.json\")\nprint(\"Benchmark not run because correctness failed.\")\nPY",
"eval_timeout": 5400,
"parser": "pytest_v",
"score_direction": "maximize",
"selection": "score_first",
"rescale": {
"kind": "log_anchor",
"anchor_raw": 14.155,
"anchor_score": 43.0
}
}
}
|