Skip to main content

edgecut

Frame-accurate clips from H.264 and HEVC videos in seconds. edgecut copies the original video between keyframes and re-encodes only the few frames at each edge of the cut, so almost every frame of the clip is bit-identical to the source.

It is a single Python file with no dependencies beyond the standard library. All video work is done by the ffmpeg and ffprobe command-line tools.

Inspired by skeskinen/smartcut and its approach of cutting video with minimal re-encoding around the cut points.

edgecut movie.mkv 1:02:03.5 1:04:10 clip.mp4

Install

Requirements: Python 3.9+, and FFmpeg with libx264 (and libx265 for HEVC sources).

uv tool install edgecut
# or
pipx install edgecut

Or copy edgecut.py into your project.

Usage

edgecut [-v] SOURCE START END OUTPUT
  • START and END are seconds, MM:SS or HH:MM:SS (fractions allowed). The clip holds every frame shown in [START, END) on the source timeline.
  • OUTPUT is an MP4 file with the video tagged avc1/hvc1, +faststart, and timestamps starting at 0.
  • The CLI rejects an output that refers to the source file, including symbolic and hard links.
  • -v prints the plan and every FFmpeg command.
  • Exit status: 0 success, 2 source or range not supported (nothing was written; use a full re-encode), 1 a step or the output check failed.

From Python:

import tempfile, edgecut

with tempfile.TemporaryDirectory() as work:
    try:
        clip = edgecut.cut('movie.mp4', 3723.5, 3850.0, work)  # returns work/clip.mp4
    except edgecut.Unsupported:   # raised before anything runs
        ...                       # fall back to a full re-encode
    except edgecut.CutFailed:     # a step or the output check failed
        ...

cut() takes optional run(argv, engine) -> (returncode, output) and event(status, **details) callbacks, so an application can run the FFmpeg commands under its own logging and timeouts.

Times use the source's absolute presentation timestamps. For sources with a nonzero start time (common in MPEG-TS), include that offset in START and END; inspect it with ffprobe -v error -show_entries format=start_time -of default=nw=1 SOURCE. CLI decimal times are parsed exactly. Python callers can pass Fraction values; float inputs are interpreted using their decimal spelling.

How it works

source   ──K0──────s──K1════════════════════K2──e────K3──
clip               [head)[      body       )[tail)
                   re-     stream-copied     re-
                   encoded                   encoded
  1. Plan with ffprobe, without decoding. List the video packets from the keyframe before start to 3 s past end (with B-frames, frames shown just before end can come later in decode order). K1 is the first IDR keyframe at or after start, K2 the last at or before end; the NAL unit type of each candidate is checked (H.264 5, HEVC 19/20). The clip is rejected if it has fewer than two IDR keyframes or any packet between them is shown outside [K1, K2) (open GOP).
  2. Body. Stream-copy [K1, K2) to MPEG-TS with the source timestamps and in-band parameter sets.
  3. Head and tail. Re-encode [start, K1) and [K2, end) with libx264 (veryfast, CRF 16) or libx265 (superfast, CRF 18), without B-frames, matching the source pixel format, H.264 profile, colour properties and time base. Their DTS is shifted by the body's reorder delay, read from the written body because Matroska stores no DTS, so DTS keeps increasing across both joins.
  4. Mux. Concatenate the TS parts, add the source audio (AAC/MP3 copied, others encoded to AAC), shift the first frame to 0, and write MP4.
  5. Check. The frame count must equal the plan, the duration must be within 0.5 s of the clip, and FFmpeg must decode 2 s around the start and each join without errors.

Input seeks use absolute timestamps (-seek_timestamp 1). Matroska seeks to a cue, while MPEG-TS can land inside a GOP; the planner backs up until it includes a keyframe before the range. Every step then selects frames and packets by source PTS: integer time-base ticks in the noise bitstream filter and video select filter, and atrim for decoded audio. Packet boundaries follow [start, end) without a fixed time tolerance.

Only the clip and the preceding GOP needed for seeking are read, so the time does not grow with the length of the source. It is dominated by encoding the edges, so it follows the source's keyframe interval.

Results

On real 1080p–1440p sources (MP4 and MKV, clips of 28–140 s), compared with a frame-accurate decode of the same range:

  • 3.4–16.5 s per clip (median 5.8 s) versus about 145 s for a full libx264 re-encode of the same clip.
  • Same frame count as the reference; all copied frames bit-identical; re-encoded edge frames at 47–69 dB PSNR.
  • Audio packets identical to the source; video and audio start at 0; timestamps within 0.011 ms of the source.
  • Plays in Chromium without media errors, including seeks across the joins.

Limitations

  • Video codecs: H.264 and HEVC with IDR keyframes. Open-GOP sources, other codecs, rotated video, and clips shorter than about two keyframe intervals raise Unsupported.
  • Only the first video stream and the first audio stream are kept; subtitles, chapters and metadata are dropped.
  • Not yet verified: HEVC output in browsers, and Safari/iOS playback across the joins, where parameter sets change in-band under the avc1/hvc1 tags.

Tests

python3 -m unittest discover -s tests -v

The tests generate short videos with FFmpeg and compare every decoded frame of each clip with the source range: H.264 with B-frames, HEVC, 10-bit, Matroska, clips starting at 0, and start/end exactly on keyframes. They also check rejection of unsupported sources and errors from failed steps.

They verify every copied body frame at its original position, presentation timestamps, increasing DTS across joins, edge-frame quality (PSNR), AAC/MP3 packet hashes and audio timing, PCM-to-AAC audio, video without audio, fractional frame rates, colour metadata and MP4 faststart. Failure tests cover invalid ranges, corrupt output, each failed encoding/muxing stage, CLI exit codes, preserving existing output on failure and temporary-file cleanup.

Input validation, probing and CLI failure tests also run without FFmpeg:

python3 -m unittest discover -s tests -p test_contracts.py -v

CI runs the suite on Python 3.9 and 3.14 with Ubuntu 24.04. It measures statement and branch coverage with coverage.py and requires at least 95% combined coverage.

License

MIT

Release maintainers: see RELEASING.md for packaging checks and the PyPI Trusted Publishing workflow.

Metadata

Release files for edgecut 0.1.1

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for edgecut 0.1.1
File Size Uploaded Provenance Actions
edgecut-0.1.1.tar.gz 18.1 kB With provenance Details for edgecut-0.1.1.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for edgecut 0.1.1
File Interpreter ABI Platform Actions
edgecut-0.1.1-py3-none-any.whl Python 3 none any Details for edgecut-0.1.1-py3-none-any.whl

Total release size: 30.0 kB

Release files / edgecut-0.1.1.tar.gz

Download URL edgecut-0.1.1.tar.gz
Size 18.1 kB
Tags Source
SHA-256 checksum
How to use checksums
d1b13ae3ea6e2ecded171ff61bdefce71b5613627a94b09b0cc8c2e4336cf3a3
BLAKE2b-256 checksum
How to use checksums
bd03b9f1f68ad34f5e11147be5f3bf447a31dada080fc9cc0c99d6d80acb51a6
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/7.0.0 CPython/3.13.16

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Nov 13, 2026.

Transparency log

Release files / edgecut-0.1.1-py3-none-any.whl

Download URL edgecut-0.1.1-py3-none-any.whl
Size 11.9 kB
Tags Python 3
SHA-256 checksum
How to use checksums
cac11396ec30ddc43aeaacd6e360e1921ce77390bd3ec8d345ca89f489eb3c8a
BLAKE2b-256 checksum
How to use checksums
de6f64307dd4cd8fd244bd42ad9b52b4ca409b9265ad2b64ecabbeb135b4e15d
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/7.0.0 CPython/3.13.16

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Nov 13, 2026.

Transparency log

Security for edgecut 0.1.1

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

Full provenance

Both files in this release have been uploaded with provenance metadata.

Select from 2 files

Attestation for edgecut-0.1.1.tar.gz

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Nov 13, 2026.

Transparency log

A note on package security

PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.

To learn more about protecting yourself from malicious actors, visit our package security documentation.

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page