Ffmpeg videostream - High speed video frame access in Python, using FFmpeg and FFshow

Overview

FFmpeg VideoStream

High speed video frame access in Python, using FFmpeg and FFshow

This script requires:

Basic Usage

from ffmpeg_videostream import VideoStream

video = VideoStream("my_video.mp4")
video.open_stream()
while True:
    eof, frame = video.read()
    if eof: break

Methods

VideoStream (path, color, bytes_per_pixel)

  • path : The path to your video file as a string : '/videos/my_video.mp4'
  • color : The pixel format you are requesting from FFmpeg : By default 'yuv420p' (recommended)
  • bytes_per_pixel : The number of bytes (not bits) that your pixel format uses to store a pixel : By default 1.5 (as per 'yuv420p')

Note: By setting color and bytes_per_pixel you can ingest video into any pixel format ffmpeg supports. However, most source files and use cases will benefit by using the default configuration and converting the pixel data to other formats as needed. (See 'Examples')


.config (start_hms, end_hms, crop_rect, output_resolution)

  • start_hms : Read frames starting from this time* in the video : ("seek" equivalent)
  • end_hms : Stop reading frames at this time* in the video
  • crop_rect : Accepts a list / tuple as [x, y, width, height] for cropping the video's input
  • output_resolution : Accepts a list / tuple as [width, height] declaring the final scaling of the video, forcing the output to match this resolution

Note: When crop_rect is set, it overrides the .shape() of the final output resolution. This is only important to note if you were to request the crop in a separate call to .config(), AFTER requesting the output_resolution be changed in a previous call. For example...

video.config(output_resolution=(1280, 720))
video.config(crop_rect=(0,0,720,480))
# Hey, just don't do it that way... huh?

.open_stream (showinfo, loglevel, hide_banner, silence_even_test)

  • showinfo : When True invokes ffmpeg's 'showinfo' filter providing details about each frame as it is read.
  • loglevel : Sets ffmpeg's 'stderr' output to include/exclude certain data being printed to console.
  • hide_banner : Shows/hides ffmpeg's startup banner.
    • Note: Various 'loglevel' settings implicitly silence this banner. When 'showinfo' is invoked no 'loglevel' output will be printed to console.
  • silence_even_test : When True suppresses console warnings that an invalid resolution has been requested.

Note: Invoking 'showinfo' reduces the maximum speed raw frame data can ingest. In most rendering instances the speed reduction is immeasurable due to other blocking processes. But for the raw acquisition of frames it can be significant.


.read ()

Returns an end-of-file boolean flag, followed by a single frame's worth of the raw bytestream from the video. The bytestream data returned is in no way prepared, decoded, or shaped into an array structure. A simple example for converting YUV420p to BGR using numpy and OpenCV is provided:

    eof, frame = video.read()
    arr = np.frombuffer(frame, np.uint8).reshape(video.shape[1] * 1.5, video.shape[0])
    bgr = cv2.cvtColor(arr, cv2.COLOR_YUV2BGR_I420)

Note: The VideoStream class can be initialized to request BGR output directly from ffmpeg, but it is slower to acquire a 24-bit RGB / BGR encoded frame than to acquire the 12-bit YUV pixels and convert them.


.shape () : Returns the final output resolution of the video in a list : [width, height]


.eof () : Boolean indicating whether the end of the file has been reached


.close () : Closes the open stream


.showinfo (key)

current_frame_number = video.showinfo("n")

Note: All requests return None if showinfo=True was not set during open_stream()


.inspect (attrib)

  • Returns a dict() containing all data found in the 'video' stream of ffprobe if no attrib declared.
  • .inspect("something") returns the value of "something" from the dict() or None if not found.

Examples

Timing raw frame access speed

from ffmpeg_videostream import VideoStream
from time import time

video = VideoStream("my_video.mp4")
video.open_stream()
frames = 0

print("\r\nReading VideoStream...")
timer = time()
while True:
    eof, frame = video.read()
    if eof: break
    frames += 1
timer = time() - timer

print(f"\r\nRead {frames} frames at {video.shape()} resolution from '{video.path}' in {round(timer, 3)} seconds.")
print(f"Effective read rate of {round(frames / timer)} frames per second.")

Rendering output to PyGame

from ffmpeg_videostream import VideoStream
import numpy as np
import cv2
import pygame

path = 'my_video.mp4'

video = VideoStream(path)
video.open_stream()

pygame.init()
screen = pygame.display.set_mode(video.shape())

while True:
    eof, frame = video.read()
    # Shape bytestream into YUV 4:2:0 numpy array, then use OpenCV to convert from YUV to BGR.
    arr = np.frombuffer(frame, np.uint8).reshape(video.shape()[1] * 3//2, video.shape()[0])
    img = cv2.cvtColor(arr, cv2.COLOR_YUV2BGR_I420)

    img = pygame.image.frombuffer(img, video.shape(), "BGR")
    screen.blit(img, (0, 0))    # Copy img onto the screen at coordinates: x=0, y=0
    pygame.display.update()
    pygame.event.pump()     # Makes pygame's window draggable / non-blocking.
    if eof:
        break
Lightweight, zero-dependency proxy and storage RTSP server

python-rtsp-server Python-rtsp-server is a lightweight, zero-dependency proxy and storage server for several IP-cameras and multiple clients. Features

Vlad 39 Nov 23, 2022
Splat a video into a mosaic by sampling a frame at regular intervals

Splat a video into a mosaic by sampling a frame at regular intervals. Useful for seeing the changes over time of an entire video or movie.

Ryan Fox 4 Oct 16, 2022
Video processing routines for SciPy

scikit-video Video Processing SciKit BETA Video processing algorithms, including I/O, quality metrics, temporal filtering, motion/object detection, mo

Alex Izvorski 119 Dec 27, 2022
FLIR/DJI IR Camera Data Parser, Python Version

FLIR/DJI IR Camera Data Parser, Python Version Parser infrared camera data as NumPy data. Usage Clone this respository and cd thermal_parser. Run pip

14 Dec 23, 2022
plumi video sharing

December 2017 update We are moving tickets from the Plumi tracker (trac.plumi.org) here, for historical reasons. Plumi video sharing system Plumi is a

Plumi 111 Dec 15, 2022
Play Video & Music on Telegram Group Video Chat

🖤 DEMONGIRL 🖤 ʜᴇʟʟᴏ ❤️ 🇱🇰 Join us ᴠɪᴅᴇᴏ sᴛʀᴇᴀᴍ ɪs ᴀɴ ᴀᴅᴠᴀɴᴄᴇᴅ ᴛᴇʟᴇʀᴀᴍ ʙᴏᴛ ᴛʜᴀᴛ's ᴀʟʟᴏᴡ ʏᴏᴜ ᴛᴏ ᴘʟᴀʏ ᴠɪᴅᴇᴏ & ᴍᴜsɪᴄ ᴏɴ ᴛᴇʟᴇɢʀᴀᴍ ɢʀᴏᴜᴘ ᴠɪᴅᴇᴏ ᴄʜᴀᴛ 🧪 ɢ

Jonathan 5 Dec 31, 2021
Extracting frames from video and create video using frames

Extracting frames from video and create video using frames This program uses opencv library to extract the frames from video and create video from ext

1 Nov 19, 2021
Your own movie streaming service. Easy to install, easy to use. Download, manage and watch your favorite movies conveniently from your browser or phone. Install it on your server, access it anywhere and enjoy.

Vigilio Your own movie streaming service. Easy to install, easy to use. Download, manage and watch your favorite movies conveniently from your browser

Tugcan Olgun 141 Jan 06, 2023
Telegram Video Stream

Video Stream An Advanced VC Video Player created for playing video in the voice chats of Telegram Groups And Channel Configs TOKEN - Get bot token fro

mr_lokaman 46 Dec 25, 2022
Adblocker for movie subtitles.

SubAdBlock Adblocker for movie subtitles. Usage Place "main.py" and "config.conf" in directory with subtitles and run "main.py". It will automatically

Marko Živić 1 Jan 09, 2022
OpenShot Video Editor is an award-winning free and open-source video editor for Linux, Mac, and Windows, and is dedicated to delivering high quality video editing and animation solutions to the world.

OpenShot Video Editor is an award-winning free and open-source video editor for Linux, Mac, and Windows, and is dedicated to delivering high quality v

OpenShot Studios, LLC 3.1k Jan 01, 2023
Video Editor for Linux

Project on break until late March. NEW RELEASE 2.8 IS OUT NOW. INSTALLING: see here. RELEASE NOTES AVAILABLE here. Introduction Features Releases Inst

1.9k Jan 07, 2023
A wrapper around ffmpeg to make it work in a concurrent and memory-buffered fashion.

Media Fixer Have you ever had a film or TV show that your TV wasn't able to play its audio? Well this program is for you. Media Fixer is a program whi

Halit Şimşek 3 May 04, 2022
Youtube-dislikes-adder - Add dislikes to the description of your YouTube videos.

Add number of dislikes to the description of your YouTube videos. Number of dislikes are updated if you let this function as a bot.

fluks 1 Aug 23, 2022
Script simples para baixar vídeos/áudios/playlist do YouTube

🔗 VilelaTube ▶️ Script simples para baixar vídeos/áudios/playlist do YouTube Requisitos • Como usar • Melhorias futuras ⚠️ Atenção! ⚠️ Lembre-se de a

João Victor Vilela dos Santos 2 Nov 03, 2021
Takes a video as an input and creates a video which is suitable to upload on Youtube Shorts and Tik Tok (1080x1920 resolution).

Shorts-Tik-Tok-Creator Takes a video as an input and creates a video which is suitable to upload on Youtube Shorts and Tik Tok (1080x1920 resolution).

Arber Hakaj 5 Nov 09, 2022
Autocut the Twitch VODs based on Marker

Markut Given the VOD of the stream and the markers that are exported as a CSV file, generate a video using ffmpeg that cuts out part of the VOD accord

Tsoding 18 Dec 19, 2022
A platform which give you info about the newest video on a channel

youtube A platform which give you info about the newest video on a channel. This uses web scraping, a better implementation will be to use the API. BR

Custom components for Home Assistant 36 Sep 29, 2022
获取斗鱼&虎牙&哔哩哔哩&抖音&快手等 48 个直播平台的真实流媒体地址(直播源)和弹幕,直播源可在 PotPlayer、flv.js 等播放器中播放。

获取斗鱼&虎牙&哔哩哔哩&抖音&快手等 48 个直播平台的真实流媒体地址(直播源)和弹幕,直播源可在 PotPlayer、flv.js 等播放器中播放。

乌帮图 5.6k Jan 06, 2023
Playing videos through S3 buckets (Wasabi, AWS, etc.) through client-side VideoJS player

Playing videos through S3 buckets (Wasabi, AWS, etc.) through client-side VideoJS player without incurring ingress/egree traffic on EC2 Instance.

Syed Umar Arfeen 8 Mar 28, 2022