-
-
Notifications
You must be signed in to change notification settings - Fork 1
feat(slicing): slice_video — cut clips by time range with optional square resize #6
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from 1 commit
Commits
Show all changes
5 commits
Select commit
Hold shift + click to select a range
1047ec2
feat(slicing): slice_video — cut clips by time range, optional square…
AmitMY 9ce4a47
Stream-copy when no resize; fix empty-slice contract
AmitMY e910cc2
Stream over slices; copy when already square; fix range/timeline bugs
AmitMY b69343a
Simplify slice_video: one metadata call, one loop, strict bounds
AmitMY b13c786
Simplify slice_video: drop codec knob, single empty-slice guard
AmitMY File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Some comments aren't visible on the classic Files Changed page.
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,73 @@ | ||
| """Cut a video into clips by time range, optionally transforming to a square size.""" | ||
|
|
||
| import io | ||
| from collections.abc import Sequence | ||
| from fractions import Fraction | ||
|
|
||
| import av | ||
| import numpy as np | ||
|
|
||
| from simple_video_utils.frames import read_frames_exact | ||
| from simple_video_utils.metadata import video_metadata | ||
|
|
||
|
|
||
| def _center_crop_square(frame: np.ndarray) -> np.ndarray: | ||
| height, width = frame.shape[:2] | ||
| side = min(height, width) | ||
| top = (height - side) // 2 | ||
| left = (width - side) // 2 | ||
| return frame[top : top + side, left : left + side] | ||
|
|
||
|
|
||
| def _encode_clip(frames: Sequence[np.ndarray], fps: float, size: int | None, codec: str) -> bytes: | ||
| if size is not None: | ||
| out_width = out_height = size | ||
| elif len(frames): | ||
| out_height, out_width = frames[0].shape[:2] | ||
| else: | ||
| return b"" | ||
|
coderabbitai[bot] marked this conversation as resolved.
Outdated
|
||
|
|
||
| buffer = io.BytesIO() | ||
| with av.open(buffer, mode="w", format="mp4") as container: | ||
| stream = container.add_stream(codec, rate=Fraction(fps).limit_denominator(1000)) | ||
| stream.width = out_width | ||
| stream.height = out_height | ||
| stream.pix_fmt = "yuv420p" | ||
| for frame in frames: | ||
| if size is not None: | ||
| frame = _center_crop_square(frame) | ||
| video_frame = av.VideoFrame.from_ndarray(frame, format="rgb24") | ||
| if size is not None: | ||
| video_frame = video_frame.reformat(width=size, height=size) | ||
| for packet in stream.encode(video_frame): | ||
| container.mux(packet) | ||
| for packet in stream.encode(): | ||
| container.mux(packet) | ||
| return buffer.getvalue() | ||
|
|
||
|
|
||
| def slice_video( | ||
| src: str, | ||
| slices: Sequence[tuple[float, float]], | ||
| size: int | None = None, | ||
| codec: str = "h264", | ||
| ) -> list[bytes]: | ||
| """Cut ``src`` into clips, one per (start, end) second range, as encoded MP4 bytes. | ||
|
|
||
| Args: | ||
| src: Path or URL to the source video. | ||
| slices: (start, end) second ranges; end is exclusive of the next frame. | ||
| size: If set, each frame is center-cropped to a square and resized to | ||
| ``size`` x ``size`` (e.g. 256 for models that expect square input). | ||
| If None, clips keep the source resolution. | ||
| codec: Output video codec. | ||
|
|
||
| Returns: | ||
| One ``bytes`` MP4 per slice, in the same order (empty ``bytes`` for a | ||
| slice that contains no frames). | ||
| """ | ||
| fps = video_metadata(src).fps | ||
| return [ | ||
| _encode_clip(list(read_frames_exact(src, start_time=start, end_time=end)), fps, size, codec) | ||
| for start, end in slices | ||
|
cursor[bot] marked this conversation as resolved.
Outdated
|
||
| ] | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,44 @@ | ||
| import io | ||
|
|
||
| import av | ||
| import numpy as np | ||
| import pytest | ||
|
|
||
| from simple_video_utils.slicing import slice_video | ||
|
|
||
|
|
||
| @pytest.fixture | ||
| def video(tmp_path): | ||
| path = tmp_path / "src.mp4" | ||
| with av.open(str(path), mode="w") as container: | ||
| stream = container.add_stream("h264", rate=30) | ||
| stream.width, stream.height, stream.pix_fmt = 320, 240, "yuv420p" | ||
| for i in range(30): | ||
| arr = np.full((240, 320, 3), i * 8 % 256, dtype=np.uint8) | ||
| for packet in stream.encode(av.VideoFrame.from_ndarray(arr, format="rgb24")): | ||
| container.mux(packet) | ||
| for packet in stream.encode(): | ||
| container.mux(packet) | ||
| return str(path) | ||
|
|
||
|
|
||
| def _dims(clip: bytes) -> tuple[int, int]: | ||
| with av.open(io.BytesIO(clip), mode="r") as container: | ||
| frame = next(container.decode(video=0)) | ||
| return frame.width, frame.height | ||
|
|
||
|
|
||
| def test_slice_returns_one_clip_per_range(video): | ||
| clips = slice_video(video, [(0.0, 0.3), (0.5, 0.8)]) | ||
| assert len(clips) == 2 | ||
| assert all(clip for clip in clips) | ||
|
|
||
|
|
||
| def test_slice_keeps_source_size_by_default(video): | ||
| [clip] = slice_video(video, [(0.0, 0.3)]) | ||
| assert _dims(clip) == (320, 240) | ||
|
|
||
|
|
||
| def test_slice_center_crops_and_resizes(video): | ||
| [clip] = slice_video(video, [(0.0, 0.3)], size=256) | ||
| assert _dims(clip) == (256, 256) |
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.