{"record":{"id":"c7b0fc0c42ca2c59","repo":"affaan-m/ECC","slug":"ffmpeg-encode-failed-err-grade","errorCode":null,"errorMessage":"ffmpeg encode failed: {err}","messagePattern":"ffmpeg encode failed: (.+?)","errorType":"exception","errorClass":"RuntimeError","httpStatus":null,"severity":"error","filePath":"skills/taste-distillation/scripts/taste/grade.py","lineNumber":817,"sourceCode":"                       tone_mode=tone_mode)\n        proc.stdin.write((np.clip(out, 0, 1) * 255).astype(np.uint8).tobytes())\n        buf.clear()\n\n    try:\n        while True:\n            ok, bgr = cap.read()\n            if not ok:\n                break\n            buf.append(_cv2.cvtColor(bgr, _cv2.COLOR_BGR2RGB).astype(np.float32) / 255.0)\n            if len(buf) >= batch:\n                flush()\n        flush()\n    finally:\n        cap.release()\n        proc.stdin.close()\n        err = proc.stderr.read().decode()[-400:]\n        if proc.wait() != 0:\n            raise RuntimeError(f\"ffmpeg encode failed: {err}\")\n    return dst\n","sourceCodeStart":799,"sourceCodeEnd":819,"githubUrl":"https://github.com/affaan-m/ECC/blob/8321021c54d670126ce3b2969d5deb880b4b0c2a/skills/taste-distillation/scripts/taste/grade.py#L799-L819","documentation":"grade_clip_direct writes raw rgb24 frames to ffmpeg's stdin and lets ffmpeg encode with libx264. When the process exits non-zero, the finally-block reads ffmpeg's stderr and raises RuntimeError('ffmpeg encode failed: <tail of stderr>'). The Python-side frame feeding worked; the failure happened inside the encoder.","triggerScenarios":"ffmpeg exits non-zero while encoding the piped rawvideo stream: mismatch between the declared -s/-pix_fmt/-r and the frames actually written (wrong frame size or channel count from OpenCV), stdin closed early, an invalid dst path, or libx264 rejecting the pixel format.","commonSituations":"Source video with odd dimensions or an unusual fps that was probed wrong; frames read as BGR/4-channel but piped as rgb24; dst on a read-only or full filesystem; OpenCV returning fewer/garbled frames so ffmpeg gets a truncated stream; ffmpeg build without libx264.","solutions":["Read the stderr tail in the exception - it pinpoints the encoder complaint (dimension mismatch, no x264, permission).","Ensure frames match the declared rawvideo parameters: convert each frame to 3-channel RGB and resize to info.width x info.height before cap.write/proc.stdin.write(frame.tobytes()).","Sanitize dimensions to even numbers for yuv420p/libx264 (round width/height down to even) before building the ffmpeg command.","Verify ffmpeg has libx264 (ffmpeg -version shows --enable-libx264) or switch the command to a codec your build has (e.g. mpeg4).","Check dst is writable and the filesystem has free space; ffmpeg cannot append - make sure dst does not conflict with an open handle."],"exampleFix":"// before\nproc.stdin.write(frame.tobytes())  # frame is BGR / 4-channel -> encoder fails\n// after\nrgb = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)\nif rgb.shape[:2] != (info.height, info.width):\n    rgb = cv2.resize(rgb, (info.width, info.height))\nproc.stdin.write(rgb.tobytes())","handlingStrategy":"validation","validationCode":"import cv2\ncap = cv2.VideoCapture(str(src))\nok, frame = cap.read()\ncap.release()\nassert ok, f'cannot read first frame of {src}'\nassert frame.ndim == 3 and frame.shape[2] == 3, f'unexpected channels: {frame.shape}'\nh, w = frame.shape[:2]\nassert w % 2 == 0 and h % 2 == 0, f'odd dimensions {w}x{h} break yuv420p; resize first'","typeGuard":null,"tryCatchPattern":"try:\n    grade_clip_direct(src, dst)\nexcept RuntimeError as e:\n    logger.error('ffmpeg encode failed: %s', str(e).split(': ', 1)[-1])\n    # fall back to the simple lut3d path which lets ffmpeg decode natively\n    grade_clip(src, dst, lut=lut)","preventionTips":["Convert every frame to 3-channel RGB and the probed width/height before writing to stdin.","Keep width/height even for libx264 yuv420p output.","Confirm libx264 support in the target environment's ffmpeg before batch runs.","Write to a temp file then atomically rename, so failed encodes never leave half-written outputs."],"tags":["ffmpeg","subprocess","video","encoding"],"backgroundTag":"ffmpeg-command-failed","analyzedSha":"8321021c54d670126ce3b2969d5deb880b4b0c2a","analyzedAt":"2026-09-16T10:08:13.343Z","contentChangedAt":"2026-09-16T10:08:13.343Z","schemaVersion":2},"datasetVersion":"2026-09-23T08:17:48.524Z"}