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
Скрипт который выводит видео в консоль. Ничего лишнего)

video-to-ascii Скрипт который выводит видео в консоль. Ничего лишнего) Требования Минимальное разрешение экрана: 1280x720 Видео в качестве 360p 10-45f

Daniil Pisarev 155 Nov 28, 2022
A python youtube search module

A python youtube search module

Fayas Noushad 4 Dec 01, 2021
Stream deck using Arduino and Python

Stream deck using Arduino and Python This is a little project I started due to the fact that I wanted to stream and didn't want to spend lots on a sim

Tal Cherniavsky 2 Feb 11, 2022
This plugin generates json files used by deovr allowing you to play 2d and 3d video's using the player

deovr-plugin This plugin generates json files used by deovr allowing you to play 2d and 3d video's using the player. Deovr looks for an index file /de

10 Sep 29, 2022
video streaming userbot (vsu) based on pytgcalls for streaming video trought the telegram video chat group.

VIDEO STREAM USERBOT ✨ an another telegram userbot for streaming video trought the telegram video chat. Environmental Variables 📌 API_ID : Get this v

levina 6 Oct 17, 2021
Code for the manim-generated scenes used in 3blue1brown videos

Code for the manim-generated scenes used in 3blue1brown videos

Grant Sanderson 4.1k Jan 09, 2023
Video-stream - A telegram video stream bot repo

This is a Telegram Video stream Bot. Binary Tech 💫 Features stream videos downl

silentz lk 1 Feb 02, 2022
Repository to create Ascii art in CMD based on video file.

Made to take any file format, and transform it into ascii art, displayed as a video in the cmd. If the cmd formatting is wrong, try zooming a little and remember to make cmd fullscreen. I made my cmd

60 Dec 17, 2022
Video Chat Streamer With Python

Voice Chat Streamer This bot can stream audio or video files and urls in telegram voice chats :) 🎯 Follow me and star this repo for more telegram bot

WiskeyWorm 4 Oct 09, 2022
Webcam Indicator is an application to recieve and send messages from your own Webcam Server.

Welcome to Webcam Indicator 👋 Webcam Indicator is an application to recieve and send messages from your own Webcam Server. 🏠 Homepage Prerequisites

Lorenzo Carbonell 2 Apr 04, 2022
Simple background blur for your webcam

backgroundblur Simple background blur for your webcam. This script will capture your webcams output, add a blur effect to the background and output th

Stefan Wagner 4 Dec 07, 2021
Text2Video's purpose is to help people create videos quickly and easily by simply typing out the video’s script and a description of images to include in the video.

Text2Video Text2Video's purpose is to help people create videos quickly and easily by simply typing out the video’s script and a description of images

Josh Chen 19 Nov 22, 2022
Streams video from raspberry pi to desktop T1 - Recognizes Faces on client T2

VideoStreamingServer Completed: Streams video from raspberry pi to desktop T1 - Recognizes Faces on client T2 In progress: Change the transmission Pro

1 Dec 06, 2021
Stream music with ffmpeg and python

youtube-stream Stream music with ffmpeg and python original Usage set the KEY in stream.sh run server.py run stream.sh (You can use Git bash or WSL in

Giyoung Ryu 14 Nov 17, 2021
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
Automatically segment in-video YouTube sponsorships.

SponsorBlock Auto Segment [Model Download] Automatically segment in-video YouTube sponsorships. Trained on a large dataset of YouTube sponsor transcri

Akmal 7 Aug 22, 2022
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
A python generator that converts youtube videos to ascii art in your console.

Video To ASCII A python generator that converts youtube videos to ascii art in your console. This has not been tested for windows! Example Normal mode

Julian Jones 24 Nov 02, 2022
Youtube as covert-channel - Control systems remotely and execute commands by uploading videos to Youtube

covert-tube A program to control systems remotely by uploading videos to Youtube using Python to create the videos and the listener, emulating some ma

Ricardo Ruiz 101 Nov 01, 2022