-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
Showing
7 changed files
with
229 additions
and
18 deletions.
There are no files selected for viewing
This file contains 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 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,8 @@ | ||
from jax_loop_utils.metric_writers._audio_video.audio_video import ( | ||
CODEC, | ||
CONTAINER_FORMAT, | ||
FPS, | ||
encode_video, | ||
) | ||
|
||
__all__ = ["encode_video", "CONTAINER_FORMAT", "CODEC", "FPS"] |
63 changes: 63 additions & 0 deletions
63
src/jax_loop_utils/metric_writers/_audio_video/audio_video.py
This file contains 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,63 @@ | ||
"""Utilities for audio and video. | ||
Requires additional dependencies, part of the `audio-video` extra. | ||
""" | ||
|
||
import io | ||
|
||
import av | ||
import numpy as np | ||
|
||
from jax_loop_utils.metric_writers.interface import ( | ||
Array, | ||
) | ||
|
||
CONTAINER_FORMAT = "mp4" | ||
CODEC = "h264" | ||
FPS = 10 | ||
|
||
|
||
def encode_video(video_array: Array, destination: io.IOBase): | ||
"""Encode a video array. | ||
Encodes using CODEC and writes using CONTAINER_FORMAT at FPS frames per second. | ||
Args: | ||
video_array: array to encode. Must have shape (T, H, W, 1) or (T, H, W, 3), | ||
where T is the number of frames, H is the height, W is the width, and the last | ||
dimension is the number of channels. Must have dtype uint8. | ||
destination: Destination to write the encoded video. | ||
""" | ||
video_array = np.array(video_array) | ||
if ( | ||
video_array.dtype != np.uint8 | ||
or video_array.ndim != 4 | ||
or video_array.shape[-1] not in (1, 3) | ||
): | ||
raise ValueError( | ||
"Expected a uint8 array with shape (T, H, W, 1) or (T, H, W, 3)." | ||
f"Got shape {video_array.shape} with dtype {video_array.dtype}." | ||
) | ||
|
||
T, H, W, C = video_array.shape | ||
is_grayscale = C == 1 | ||
if is_grayscale: | ||
video_array = np.squeeze(video_array, axis=-1) | ||
|
||
with av.open(destination, mode="w", format=CONTAINER_FORMAT) as container: | ||
stream = container.add_stream(CODEC, rate=FPS) | ||
stream.width = W | ||
stream.height = H | ||
stream.pix_fmt = "yuv420p" | ||
|
||
for t in range(T): | ||
frame_data = video_array[t] | ||
if is_grayscale: | ||
# For grayscale, use gray format and let av handle conversion to yuv420p | ||
frame = av.VideoFrame.from_ndarray(frame_data, format="gray") | ||
else: | ||
frame = av.VideoFrame.from_ndarray(frame_data, format="rgb24") | ||
frame.pts = t | ||
container.mux(stream.encode(frame)) | ||
|
||
container.mux(stream.encode(None)) | ||
74 changes: 74 additions & 0 deletions
74
src/jax_loop_utils/metric_writers/_audio_video/audio_video_test.py
This file contains 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,74 @@ | ||
"""Tests for video encoding utilities.""" | ||
|
||
import io | ||
|
||
import av | ||
import numpy as np | ||
from absl.testing import absltest | ||
|
||
from jax_loop_utils.metric_writers._audio_video import ( | ||
CONTAINER_FORMAT, | ||
FPS, | ||
encode_video, | ||
) | ||
|
||
|
||
class VideoTest(absltest.TestCase): | ||
"""Tests for video encoding utilities.""" | ||
|
||
def test_encode_video_invalid_args(self): | ||
"""Test that encode_video raises appropriate errors for invalid inputs.""" | ||
invalid_shape = np.zeros((10, 20, 30, 4), dtype=np.uint8) | ||
with self.assertRaisesRegex(ValueError, "Expected a uint8 array with shape"): | ||
encode_video(invalid_shape, io.BytesIO()) | ||
|
||
invalid_dtype = np.zeros((10, 20, 30, 3), dtype=np.float32) | ||
with self.assertRaisesRegex(ValueError, "Expected a uint8 array with shape"): | ||
encode_video(invalid_dtype, io.BytesIO()) | ||
|
||
def test_encode_video_success(self): | ||
"""Test successful video encoding.""" | ||
# Create a simple test video - red square moving diagonally | ||
T, H, W = 20, 64, 64 | ||
video = np.zeros((T, H, W, 3), dtype=np.uint8) | ||
for t in range(T): | ||
pos = t * 5 # Move 5 pixels each frame | ||
video[t, pos : pos + 10, pos : pos + 10, 0] = 255 # Red square | ||
|
||
output = io.BytesIO() | ||
encode_video(video, output) | ||
|
||
output.seek(0) | ||
with av.open(output, mode="r", format=CONTAINER_FORMAT) as container: | ||
stream = container.streams.video[0] | ||
self.assertEqual(stream.codec_context.width, W) | ||
self.assertEqual(stream.codec_context.height, H) | ||
self.assertEqual(stream.codec_context.framerate, FPS) | ||
# Check we can decode all frames | ||
frame_count = sum(1 for _ in container.decode(stream)) | ||
self.assertEqual(frame_count, T) | ||
|
||
def test_encode_video_grayscale(self): | ||
"""Test encoding grayscale video (1 channel).""" | ||
T, H, W = 5, 32, 32 | ||
video = np.zeros((T, H, W, 1), dtype=np.uint8) | ||
|
||
# Create pulsing pattern | ||
for t in range(T): | ||
video[t, :, :, 0] = (t * 50) % 256 # Increasing brightness | ||
|
||
output = io.BytesIO() | ||
encode_video(video, output) | ||
|
||
output.seek(0) | ||
with av.open(output, mode="r", format=CONTAINER_FORMAT) as container: | ||
stream = container.streams.video[0] | ||
self.assertEqual(stream.codec_context.width, W) | ||
self.assertEqual(stream.codec_context.height, H) | ||
# Check we can decode all frames | ||
frame_count = sum(1 for _ in container.decode(stream)) | ||
self.assertEqual(frame_count, T) | ||
|
||
|
||
if __name__ == "__main__": | ||
absltest.main() |
This file contains 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 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
Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.
Oops, something went wrong.