Skip to content

WebGear

Abhishek Thakur edited this page Apr 24, 2020 · 90 revisions

VidGear Logo

WebGear API

WebGear is a powerful ASGI Video-streamer API, that is built upon Starlette - a lightweight ASGI framework/toolkit, which is ideal for building high-performance asyncio services.

WebGear API provides a highly extensible asyncio wrapper around Starlette ASGI application and easy access to its various components independently. Thereby implementing the ability to flexibly interact with the Starlette's ecosystem of shared middleware and mountable applications & seamless access to its various Response classes, Routing tables, Static Files, Templating engine(with Jinja2), etc.

In simple words, WebGear can acts as robust Live Video Streaming Server that transfers live video frames to any web browser on a network in real-time. It addition to this, WebGear provides a special internal wrapper around VideoGear API, which itself provides internal access to both CamGear and PiGear APIs thereby granting it exclusive power for streaming frames incoming from any device/source. On the plus side, this wrapper provides WebGear exclusive features like streaming stabilization enabled live video frames in real-time.

 


Important ⚠️

  • WebGear API is available for Python 3.6 and above versions only.

  • WebGear API as of now only available with the Testing Branch only.

  • It is advised to enable logging (logging = True) on the first run, to easily identify any runtime errors.


 

 

Table of Contents:

 

 

Data-Files Auto-Generation WorkFlow:

On initializing WebGear API, it automatically checks for three critical data-files i.e index.html, 404.html & 500.html in templates folder at the default location:

  • If data-files found: it will proceed normally for instantiating the Starlette application.
  • If data-files not found: it will trigger the Auto-Generation process

Default Location:

  • A default location is the path of the directory where data files/folders are downloaded/generated/saved.
  • By default, the .vidgear the folder at the home directory of your machine (for e.g /home/foo/.vidgear on Linux) serves as the default location.
  • But, You can also use WebGear's custom_data_location dictionary attribute to change/alter default location path to somewhere else.
  • Tip:bulb: You can set logging=True during initialization, for easily identifying the selected default location, which will be something like this (on a Linux machine):
    WebGear :: DEBUG :: `/home/foo/.vidgear` is the default location for saving WebGear data-files.

Auto-Generation process:

  • On triggering this process, WebGear API creates templates and static folders along with js, css, img sub-folders at the assigned default location.
  • Thereby at this default location, the necessary default data files will be downloaded from Github Server in respective folders in the following order:
	.vidgear
	├── static
	│   ├── css
	│   │   ├── bootstrap.min.css
	│   │   └── cover.css
	│   ├── img
	│   │   └── favicon-32x32.png
	│   └── js
	│       ├── bootstrap.min.js
	│       ├── jquery-3.4.1.slim.min.js
	│       └── popper.min.js
	└── templates
	    ├── 404.html
	    ├── 500.html
	    ├── base.html
	    └── index.html

	5 directories, 10 files
  • Finally these downloaded files thereby are verified for errors and API proceeds for instantiating the Starlette application normally.

  • Tip:bulb: You can also force trigger the Auto-generation process to overwrite existing data-files using overwrite_default_files dictionary attribute. Remember only downloaded default data files(given above) will be overwritten in this process, and any other file/folder will NOT be affected.

 

 

Importing

You can import WebGear as follows:

from vidgear.gears.asyncio import WebGear

 

 

Outputs

The WebGear API by default uses simple & elegant Bootstrap's Cover template, by @mdo:

Index.html:

Can be accessed by visiting WebGear APP server running at http://0.0.0.0:8000/:

VidGear Logo

404.html:

Appears when respective URL is not found, for example http://0.0.0.0:8000/ok:

VidGear Logo

500.html:

Appears when an API Error is encountered:

⚠️ Warning: If logging is enabled and an error occurs, then instead of displaying this 500 handler, WebGear will respond with a traceback response.

VidGear Logo

 

 

Usage:

Requirements

  • Python 3.6+ already installed.

  • Clone and install the testing branch as follows:

    git clone https://github.com/abhiTronix/vidgear.git
    cd vidgear
    git checkout testing
    sudo pip3 install .[asyncio] #install all necessary asyncio requirements
    cd
  • ASGI Server: You'll also need to install an ASGI Server to run following WebGear usage examples, and by default WebGear ships the state-of-the-art uvicorn Server. But you can also use other ASGI server such as daphne, or hypercorn with it.

 

Basic Usage: (Bare-Minimum)

⚠️ If you experience any performance-throttling/lag while running this bare-minimum example, then Kindly see Performance Tweaks ➶

A. Programmatically:

You can access and run WebGear VideoStreamer Server programmatically in your python script in just a few lines of code as follows:

#import libs
import uvicorn
from vidgear.gears.asyncio import WebGear

#initialize WebGear app  
web = WebGear(source = "test.mp4")

#run this app on Uvicorn server
uvicorn.run(web(), host='0.0.0.0', port=8000)

#close app safely
web.shutdown()

That's all. Now, just run that, and a live video stream can be accessed on any browser at http://0.0.0.0:8000/ address.

 

B. From Terminal command line:

You can access and run WebGear Server directly from the terminal command line, but make sure your PYTHON_PATH is set to python 3.6+ versions only.

  • Basic Command: The following command will run a WebGear VideoStreamer server at http://0.0.0.0:8000/:

    python3 -m vidgear.gears.asyncio --source test.avi 
    

    which can be accessed on any browser on the network.

  • Advanced: You can run help command to see all the advanced settings with python3 -m vidgear.gears -h command you'll see the following output:

    ⚠️ Warning: If you're using --options/-op flag then kindly wrap your dictionary value in single '' or double "" quotes as shown in this example.

usage: python -m vidgear.gears.asyncio [-h] [-s SOURCE] [-ep ENABLEPICAMERA] [-S STABILIZE]
				[-cn CAMERA_NUM] [-yt Y_TUBE] [-b BACKEND] [-cs COLORSPACE]
				[-r RESOLUTION] [-f FRAMERATE] [-td TIME_DELAY]
				[-ip IPADDRESS] [-pt PORT] [-l LOGGING] [-op OPTIONS]

Runs WebGear VideoStreaming Server through terminal.

optional arguments:
  -h, --help            show this help message and exit
  -s SOURCE, --source SOURCE
                        Path to input source for CamGear API.
  -ep ENABLEPICAMERA, --enablePiCamera ENABLEPICAMERA
                        Sets the flag to access PiGear(if True) or otherwise
                        CamGear API respectively.
  -S STABILIZE, --stabilize STABILIZE
                        Enables/disables real-time video stabilization.
  -cn CAMERA_NUM, --camera_num CAMERA_NUM
                        Sets the camera module index that will be used by
                        PiGear API.
  -yt Y_TUBE, --y_tube Y_TUBE
                        Enables YouTube Mode in CamGear API.
  -b BACKEND, --backend BACKEND
                        Sets the backend of the video source in CamGear API.
  -cs COLORSPACE, --colorspace COLORSPACE
                        Sets the colorspace of the output video stream.
  -r RESOLUTION, --resolution RESOLUTION
                        Sets the resolution (width,height) for camera module
                        in PiGear API.
  -f FRAMERATE, --framerate FRAMERATE
                        Sets the framerate for camera module in PiGear API.
  -td TIME_DELAY, --time_delay TIME_DELAY  
                        Sets the time delay(in seconds) before start reading
                        the frames.
  -ip IPADDRESS, --ipaddress IPADDRESS
                        Uvicorn binds the socket to this ipaddress.
  -pt PORT, --port PORT
                        Uvicorn binds the socket to this port.
  -l LOGGING, --logging LOGGING
                        Enables/disables error logging, essential for
                        debugging.
  -op OPTIONS, --options OPTIONS
                        Sets the parameters supported by APIs(whichever being
                        accessed) to the input videostream, But make sure to
                        wrap your dict value in single or double quotes.

 

 

Advanced Usage

Visit the following links:

 

 

Attributes and Parameters: 🔧

WebGear specific parameters:

  • ** options(dict) : can be used in addition, to pass user-defined parameter to WebGear API in the form of python dictionary. Supported WebGear dictionary attributes are:

    • custom_data_location (string) : Can be used to change/alter default location path to somewhere else. Its usage is as follows:

      options = {"custom_data_location": "/home/foo/foo1"} #setdefault location to '/home/foo/foo1'
    • overwrite_default_files (boolean) : Can be used to force trigger the Auto-generation process to overwrite existing data-files. Its usage is as follows:

      options = {"overwrite_default_files": True} #force trigger the Auto-generation process

      ⚠️ Remember only downloaded files will be overwritten in this process, and any other file/folder will NOT be affected/overwritten.

    • frame_size_reduction (int/float) : This attribute controls the size reduction (in percentage) of the frame to be streamed on Server._ The value defaults to 20, and must be no higher than 90 (fastest, max compression, Barely Visible frame-size) and no lower than 0 (slowest, no compression, Original frame-size). Its recommended value is between 40-60. Its usage is as follows:

      options = {"frame_size_reduction": 50} #frame-size will be reduced by 50%
    • JPEG Encoding Parameters:

      In WebGear, the input video frames are first encoded into Motion JPEG (M-JPEG or MJPEG) video compression format in which each video frame or interlaced field of a digital video sequence is compressed separately as a JPEG image, before sending onto a server. Therefore, WebGear API provides various attributes to have full control over JPEG encoding performance and quality, which are as follows:

      • frame_jpeg_quality (integer) : It controls the JPEG encoder quality and value varies from 0 to 100 (the higher is the better quality but performance will be lower). Its default value is 95. Its usage is as follows:

        options = {"frame_jpeg_quality": 80} #JPEG will be encoded at 80% quality.
      • frame_jpeg_optimize (boolean) : It enables various JPEG compression optimizations such as Chroma subsampling, Quantization table, etc. Its default value is False. Its usage is as follows:

        options = {"frame_jpeg_optimize": True} #JPEG optimizations are enabled.
      • frame_jpeg_progressive (boolean) : It enables Progressive JPEG encoding instead of the Baseline. Progressive Mode. Its default value is False means baseline mode. Its usage is as follows:

        options = {"frame_jpeg_progressive": True} #Progressive JPEG encoding enabled.
      • Usage: The usage of these dictionary attribute can be seen in [this example].(https://github.com/abhiTronix/vidgear/wiki/Advanced-WebGear-API-Usage#a1-bare-minimum-example-with-performance-tweaks)

  • logging (boolean) : set this flag to enable/disable logging, essential for debugging. Its default value is False.

 

Clone this wiki locally