dacorvo's picture
download
raw
2.43 kB
"""Writes LEFT and RIGHT, two mp4s at 24 fps, side by side for as long as the shorter one, each scaled to WIDTH x WIDTH/2
with its label drawn in its top left corner, with the audio of RIGHT.
Usage: compare.py LEFT RIGHT OUT WIDTH LABEL_LEFT LABEL_RIGHT"""
import sys
import av
import numpy as np
from PIL import Image, ImageDraw, ImageFont
left, right, out, width, label_left, label_right = sys.argv[1:7]
width = int(width)
height = width // 2
def frames(path):
with av.open(path) as c:
return [f.to_image().resize((width, height), Image.LANCZOS) for f in c.decode(c.streams.video[0])]
def label(im, text):
draw = ImageDraw.Draw(im)
font = ImageFont.load_default(size=height // 18)
draw.text((height // 30, height // 40), text, "white", font, stroke_width=max(2, height // 200), stroke_fill="black")
return im
a, b = frames(left), frames(right)
count = min(len(a), len(b))
print(f"{left}: {len(a)} frames, {right}: {len(b)} frames, writing {count}")
with av.open(right) as c:
sample_rate = c.streams.audio[0].rate
audio = np.concatenate([f.to_ndarray() for f in c.decode(c.streams.audio[0])], axis=1)
# The sound of RIGHT, cut to the frames written, as LEFT can be the shorter one.
audio = audio[:, : round(count * sample_rate / 24)]
# The index goes first, so that a player can start before it has the whole file.
with av.open(out, mode="w", options={"movflags": "faststart"}) as container:
video = container.add_stream("libx264", rate=24, options={"crf": "18", "preset": "medium"})
video.width, video.height, video.pix_fmt = 2 * width, height, "yuv420p"
sound = container.add_stream("libmp3lame", rate=sample_rate)
sound.codec_context.layout = "stereo"
for k in range(count):
frame = Image.new("RGB", (2 * width, height))
frame.paste(label(a[k].copy(), label_left), (0, 0))
frame.paste(label(b[k].copy(), label_right), (width, 0))
for packet in video.encode(av.VideoFrame.from_ndarray(np.asarray(frame), format="rgb24")):
container.mux(packet)
for packet in video.encode():
container.mux(packet)
planar = av.AudioFrame.from_ndarray(np.ascontiguousarray(audio.astype(np.float32)), format="fltp", layout="stereo")
planar.sample_rate = sample_rate
for packet in sound.encode(planar):
container.mux(packet)
for packet in sound.encode():
container.mux(packet)
print(f"wrote {out}")

Xet Storage Details

Size:
2.43 kB
·
Xet hash:
3c19b845f0e4fc63d467a090b02dec4ebecef6bcaed26a21abe6a41557797f81

Xet efficiently stores files, intelligently splitting them into unique chunks and accelerating uploads and downloads. More info.