-
-
Save mjlbach/a4cbd2e5d2e08fec9962aa5052328fa9 to your computer and use it in GitHub Desktop.
FFMPEG Python LIvestream
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
import subprocess | |
import numpy as np | |
# Generate a dummy video frame using NumPy | |
# For example, a 60-frame video with resolution 1920x1080 and 3 color channels (RGB) | |
num_frames = 60 | |
height = 1080 | |
width = 1920 | |
video_data = np.random.randint(0, 255, (num_frames, height, width, 3), dtype=np.uint8) | |
# Define the FFmpeg command as a list of arguments | |
ffmpeg_command = [ | |
'ffmpeg', | |
'-y', # Overwrite output file if it exists | |
'-f', 'rawvideo', # Input format is raw video | |
'-vcodec', 'rawvideo', # Input video codec is raw video | |
'-s', f'{width}x{height}', # Size of one frame | |
'-pix_fmt', 'rgb24', # Input pixel format | |
'-r', '30', # Frame rate | |
'-i', '-', # Input from stdin | |
'-c:v', 'libx264', # Output video codec | |
'-pix_fmt', 'yuv420p', # Output pixel format | |
'-movflags', 'frag_keyframe+empty_moov', # MP4 faststart for web streaming | |
'-f', 'mp4', | |
'pipe:1' # Output file | |
] | |
# Open a subprocess with stdin as a pipe | |
process = subprocess.Popen(ffmpeg_command, | |
stdin=subprocess.PIPE, | |
stdout=subprocess.PIPE) | |
# Write the video data to FFmpeg's stdin | |
for frame in video_data: | |
process.stdin.write(frame.tobytes()) | |
process.stdout.read() | |
# Close stdin to signal that we're done | |
process.stdin.close() | |
# process.stdout.close() | |
for frame in video_data: | |
process.stdout.read() | |
# Wait for the FFmpeg process to finish | |
process.wait() | |
# Check if the process has exited successfully | |
if process.returncode != 0: | |
raise subprocess.CalledProcessError(process.returncode, ffmpeg_command) | |
print("Video processing complete.") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment