Skip to content

StreamGear API Parameters¶

 

output¶

This parameter sets the valid filename/path for storing the StreamGear assets, including Manifest file (such as MPD in case of DASH) or a Master Playlist (such as M3U8 in case of Apple HLS) and generated sequence of chunks/segments.

StreamGear API will throw ValueError if the provided output is empty or invalid.

Make sure to provide a valid filename with a valid file extension for the selected format value (such as .mpd for MPEG-DASH and .m3u8 for APPLE-HLS), otherwise StreamGear will throw ValueError.

You can easily delete all previous assets at the output location by using the -clear_prev_assets attribute of the stream_params dictionary parameter.

Data-Type: String

Usage:

Its valid input can be one of the following:

  • Path to directory: Valid path of the directory. In this case, StreamGear API will automatically assign a unique filename for the Manifest file. This can be defined as follows:

    # Define streamer with output directory path for saving DASH assets 
    streamer = StreamGear(output = "/home/foo/bar") 
    
    # Define streamer with output directory path for saving HLS assets
    streamer = StreamGear(output = "/home/foo/bar", format="hls")  
    
  • Filename (with/without path): Valid filename (with a valid extension) of the output Manifest or Playlist file. If the filename is provided without a path, the current working directory will be used. Its parent directory must already exist (StreamGear doesn't create it), and existing assets with the same names are overwritten (FFmpeg's -y). This can be defined as follows:

    # Define streamer with output manifest filename
    streamer = StreamGear(output = "output_dash.mpd") 
    
    # Define streamer with output playlist filename
    streamer = StreamGear(output = "output_hls.m3u8", format="hls") 
    
  • URL: Valid URL of a network stream with a protocol supported by the installed FFmpeg (verify with the ffmpeg -protocols command). This is useful for directly storing assets to a network server. For example, you can use an HTTP protocol URL as follows:

    # Define streamer with output manifest URL
    streamer = StreamGear(output = "http://some_dummy_serverip/live/output_dash.mpd") 
    
    # Define streamer with output playlist URL
    streamer = StreamGear(output = "http://some_dummy_serverip/live/output_hls.m3u8", format="hls")
    

 

format¶

This parameter enables the adaptive HTTP streaming format. This parameter currently supported these formats: dash (i.e MPEG-DASH) and hls (i.e Apple HLS).

Make sure to provide a valid filename with a valid file extension in the output parameter for the selected format value (i.e., .mpd for MPEG-DASH and .m3u8 for APPLE-HLS), otherwise StreamGear will throw a ValueError.

Any improper value assigned to format parameter will result in a ValueError!

Data-Type: String

Default Value: Its default value is dash

Usage:

# Define streamer with DASH format
StreamGear(output = "output_dash.mpd", format="dash")
# Define streamer with HLS format
StreamGear(output = "output_hls.m3u8", format="hls")

 

custom_ffmpeg¶

This parameter assigns the custom path/directory where the custom/downloaded FFmpeg executables are located.

Behavior on Windows Systems

On Windows, if a custom FFmpeg executable's path/directory is not provided through this custom_ffmpeg parameter, the StreamGear API will automatically attempt to download and extract suitable Static FFmpeg binaries at a suitable location on your Windows machine. More information can be found here âž¶.

Data-Type: String

Default Value: Its default value is "" (empty string).

StreamGear checks the FFmpeg in use has the dash muxer (with -seg_duration) or hls muxer (with -var_stream_map), and throws RuntimeError otherwise. FFmpeg 6.0 or newer is recommended.

Usage:

# Define streamer with custom ffmpeg binary
StreamGear(output = 'output_foo.mpd', custom_ffmpeg="C://foo//bar//ffmpeg.exe")

 

stream_params¶

This parameter allows developers to leverage nearly all FFmpeg options, providing effortless and flexible control over its internal settings for transcoding and generating high-quality streams. All supported parameters can be formatted as attributes within this dictionary parameter.

Please read the FFmpeg Documentation carefully before passing any additional values to the stream_params parameter. Incorrect values may cause errors or result in no output.

Data-Type: Dictionary

Default Value: Its default value is {}.

Supported Parameters¶

A. Exclusive Parameters¶

StreamGear API provides some exclusive internal parameters to easily generate Streaming Assets and effortlessly tweak its internal properties. These parameters are discussed below:

  • -streams (list of dicts): This important attribute makes it simple and pretty straight-forward to define additional multiple streams as list of dictionaries of different quality levels (i.e. different bitrate or spatial resolutions) for streaming.

    Important Information about -streams attribute
    • In addition to the user-defined Secondary Streams, StreamGear automatically generates a Primary Stream (at index 0) with the same resolution as the input frames and at default framerate1, at the index 0. Its resolution and bitrates can be overridden with the -s:v:0, -b:v:0 and -b:a:0 FFmpeg parameters (e.g. {"-s:v:0": "1280x720", "-b:v:0": "2500k"}).
    • You MUST define the -resolution value for each stream; otherwise, the stream will be discarded.
    • You only need to define either the -video_bitrate or the -framerate for a valid stream.
      • If you specify only the -framerate, the video bitrate will be calculated automatically (see -bpp).
      • If you define both, the -video_bitrate is used as is, and the -framerate only sets the stream's framerate.
    • Every stream is encoded at its bitrate (capped with -maxrate/-bufsize), so the bandwidth declared in the Manifest/Playlist is what clients actually get. StreamGear sets no -crf by default; a user-defined -crf is still capped by each stream's bitrate.
    • Every stream maps only the first video stream of the source (cover art and other video tracks are skipped) and its first audio stream (or the -audio source), so subtitles, data tracks and extra audio tracks are left out.
    • The given -streams dictionaries are not modified, so they can be reused.

    To construct the additional stream dictionaries, you will need the following sub-attributes::

    • -resolution (string): It is compulsory to define the required resolution/dimension/size for the stream, otherwise, the given stream will be rejected. Its value should be in the format "{width}x{height}" (odd values are rounded up to even, as encoders require; a warning is logged when it doesn't match the source's display aspect ratio), as shown below:

      # produce a 1280x720 resolution/scale stream
      "-streams" = [{"-resolution": "1280x720"}]  
      
    • -video_bitrate (string): This is an optional sub-attribute (can be ignored if the -framerate parameter is defined) that generally determines the bandwidth and quality of the stream. The higher the bitrate, the better the quality and the larger the bandwidth, which can place more strain on the network. Its value is typically in k (kilobits per second) or M (Megabits per second). Define this attribute as follows:

      # produce a 1280x720 resolution and 2000 kbps bitrate stream
      "-streams" : [{"-resolution": "1280x720", "-video_bitrate": "2000k"}] 
      
    • -framerate (float/int): This is another optional sub-attribute (can be ignored if the -video_bitrate parameter is defined) that sets the framerate of the stream (FFmpeg's -r for this stream), and is used to calculate its bitrate when -video_bitrate is not given. It can't exceed the source framerate (higher values are ignored with a warning); keyframes then follow time, so segments of all streams stay aligned. Its value can be a float or integer, as shown below:

      # produce a 1280x720 resolution and 15fps framerate stream
      "-streams" : [{"-resolution": "1280x720", "-framerate": 15.0}] 
      
      New in v0.3.8

      The framerate is applied to the stream since v0.3.8 (it was only used for the bitrate before).

    Usage: You can easily define any number of streams using -streams attribute as follows:

    stream_params = 
        {"-streams": 
            [
            {"-resolution": "1920x1080", "-video_bitrate": "4000k"}, # Stream1: 1920x1080 at 4000kbs bitrate
            {"-resolution": "1280x720", "-framerate": 30}, # Stream2: 1280x720 at 30fps (if source is >= 30fps)
            {"-resolution": "640x360", "-framerate": 15.0},  # Stream3: 640x360 at 15fps 
            ]
        }
    

    Its usage example can be found here âž¶

 

  • -video_source (string): This attribute takes a valid video path as input and activates Single-Source Mode, for transcoding it into multiple smaller chunks/segments for streaming after successful validation. Its value can be one of the following:

    StreamGear throws ValueError if the given -video_source is neither an existing file nor a supported URL, or has no readable video stream (it silently switched to Real-time Frames Mode before v0.3.8).

    Source audio, rotation and HDR
    • Source audio is copied when it is AAC (which every DASH/HLS client plays), and otherwise encoded to AAC (e.g. PCM, Opus). With -streams, it is always encoded at each stream's -audio_bitrate.
    • Rotated sources (e.g. portrait phone videos) keep their display orientation: the Primary Stream gets the rotated dimensions (e.g. 720x1280).
    • HDR sources (PQ/HLG) are encoded as 8-bit SDR without tone-mapping and may look washed out, so StreamGear logs a warning. Add a tone-mapping filter yourself, e.g. {"-vf": "zscale=t=linear,tonemap=hable,zscale=p=bt709:t=bt709:m=bt709,format=yuv420p"} (needs FFmpeg built with --enable-libzimg).
    • Video Filename: Valid path to a video file as follows:

      # set video source as `/home/foo/bar.mp4`
      stream_params = {"-video_source": "/home/foo/bar.mp4"}
      
    • Video URL: Valid URL of a network video stream as follows:

      Ensure the given video URL uses a protocol supported by the installed FFmpeg (verify with ffmpeg -protocols terminal command).

      # set video source as `http://livefeed.com:5050`
      stream_params = {"-video_source": "http://livefeed.com:5050"} 
      

    Its usage example can be found here âž¶

 

  • -audio (string/list): This attribute takes an external custom audio path (as a string) or an audio device name followed by a suitable demuxer (as a list) as the audio source input for all StreamGear streams. Its value can be one of the following:

    Ensure the provided -audio audio source is compatible with the input video source. Incompatibility can cause multiple errors or result in no output at all.

    StreamGear throws ValueError if the given -audio is neither an existing file nor a supported URL, or has no readable audio stream (it was silently dropped before v0.3.8).

    The -audio source replaces any audio of the -video_source (in both DASH and HLS), is encoded with aac by default, and ends with the video: shorter audio is padded with silence (-af apad, unless you set an audio filter) and -shortest is added. So infinite sources (live microphone, lavfi) end with your frames on close(). With copied audio (-acodec copy), neither is added.

    • Audio Filename (string): Valid path to an audio file as follows:

      # set audio source as `/home/foo/foo1.aac`
      stream_params = {"-audio": "/home/foo/foo1.aac"} 
      

      Its usage examples can be found here âž¶ and here âž¶

    • Audio URL (string): Valid URL of a network audio stream as follows:

      Ensure the given audio URL uses a protocol supported by the installed FFmpeg (verify with ffmpeg -protocols terminal command).

      # set input audio source as `https://exampleaudio.org/example-160.mp3`
      stream_params = {"-audio": "https://exampleaudio.org/example-160.mp3"} 
      
    • Device name and Demuxer (list): Valid audio device name followed by a suitable demuxer as follows:

      # Assign appropriate input audio-source device (compatible with video source) and its demuxer
      stream_params = {"-audio":  [
          "-f",
          "dshow",
          "-i",
          "audio=Microphone (USB2.0 Camera)",
      ]} 
      

      Its usage example can be found here âž¶

 

  • -livestream (bool): (optional) specifies whether to enable Live-Streaming , where chunks will contain information for new frames only and forget previous ones, or not. The default value is False. It can be used as follows:

    New in v0.3.8

    -livestream also works in Single-Source mode since v0.3.8, e.g. for restreaming a live RTSP/RTMP source. Local video files are then read at their native speed (FFmpeg's -re).

    Live defaults: 4-second segments in both formats (DASH -seg_duration 4, -window_size 5, -extra_window_size 5; HLS -hls_time 4, -hls_list_size 6, -hls_flags delete_segments+independent_segments+temp_file). Durations can be fractional (e.g. {"-seg_duration": 2.5}). For lower latency, lower them and see FFmpeg's DASH -ldash, -streaming, -target_latency and HLS -lhls options, which can be passed in stream_params.

    stream_params = {"-livestream": True} # enable live-streaming
    

    Its usage example can be found here âž¶

 

  • -input_framerate (float/int) : (optional) This parameter specifies the framerate of the incoming frames (i.e. how many frames make one second of video) and only works in Real-time Frames Mode. Its default value is 25.0 fps (also used when the value is invalid). Its value can be a float, integer or numeric string, as shown below:

    # set input video source framerate to 60fps
    stream_params = {"-input_framerate": 60.0} 
    

    Its usage example can be found here âž¶

 

  • -bpp (float/int): (optional) This attribute controls the constant BPP (Bits-Per-Pixel) value, which helps ensure good quality in high motion scenes by determining the desired video bitrate for streams. A higher BPP value improves motion quality. The default value is 0.1. Increasing the BPP value helps fill the gaps between the current bitrate and the upload limit/ingest cap. Its value can be anything above 0.001 and can be used as follows:

    Important points while tweaking BPP

    • The resulting bitrate is width × height × framerate × BPP, e.g. 0.1 gives ~2304 kbps for 1280x720 at 25fps.
    • If your desired resolution/fps/audio combination is below the maximum service bitrate, raise BPP to match it for extra quality.
    • It is generally better to lower resolution (and/or fps) and raise BPP than to raise resolution and lose BPP.
    # sets BPP to 0.05
    stream_params = {"-bpp": 0.05} 
    

 

  • -gop (float/int) : (optional) This parameter specifies the number of frames between two I-frames for accurate GOP (Group of Pictures) length. Increasing the GOP length reduces the number of I-frames per time frame, minimizing bandwidth consumption. For example, with complex subjects such as water sports or action scenes, a shorter GOP length (e.g., 15 or below) results in excellent video quality. For more static video, such as talking heads, much longer GOP sizes are not only sufficient but also more efficient. It can be used as follows:

    The larger the GOP size, the more efficient the compression and the less bandwidth you will need.

    By default, StreamGear automatically sets a recommended fixed GOP value (i.e., every two seconds) based on the input framerate and selected encoder. Values below 1 are invalid. For libx265, the GOP is merged into your -x265-params (e.g. crf=28:keyint=50:min-keyint=50).

    # set GOP length to 70
    stream_params = {"-gop": 70} 
    

 

  • -clones (list): (optional) This parameter sets special FFmpeg options that need to be repeated more than once in the command. For more information, see this issue. It accepts values as a list only. Usage is as follows:

    # sets special FFmpeg options repeated multiple times
    stream_params = {"-clones": ['-map', '0:v:0', '-map', '1:a?']}
    

 

  • -ffmpeg_download_path (string): (optional) This parameter sets a custom directory for downloading FFmpeg static binaries in Compression Mode during the Auto-Installation step on Windows machines only. If this parameter is not altered, the binaries will be saved to the default temporary directory (e.g., C:/User/foo/temp) on your Windows machine. It can be used as follows:

    # download FFmpeg static binaries to `C:/User/foo/bar`
    stream_params = {"-ffmpeg_download_path": "C:/User/foo/bar"} 
    

 

  • -clear_prev_assets (bool): (optional) This parameter specifies whether to remove/delete previous StreamGear assets in the directory of the output parameter before transcoding. The default value is False. It can be enabled as follows:

    It deletes the output manifest/playlist itself, plus every file named like StreamGear's assets: chunk-stream*, init-stream* (DASH segments), stream_*.m3u8 (HLS variant playlists) and init*.mp4 (HLS fMP4 init segments). Other files (including other .mpd/.m3u8) are kept. Don't store your own files with these names there.

    # delete all previous assets
    stream_params = {"-clear_prev_assets": True} 
    

 

  • -enable_force_termination (bool): sets a special flag to enable the forced termination of the FFmpeg process, required only if StreamGear is getting frozen when terminated. Its usage is as follows:

    The -enable_force_termination flag can potentially cause unexpected behavior or corrupted output in certain scenarios. It is recommended to use this flag with caution.

    # enables forced termination of FFmpeg process
    stream_params = {"-enable_force_termination": True} 
    
  • -progress_callback (callable): (optional) This parameter sets a function called as callback(done_s, total_s) while Single-Source Mode transcodes, alongside the built-in progress bar, where done_s is seconds of source transcoded so far and total_s is the source duration (0 when unknown). If it raises, the error is logged and the callback is disabled for that run (transcoding continues). The default value is None. Its usage is as follows:

    New in v0.3.7

    This feature was added in v0.3.7.

    # print transcoding progress
    stream_params = {"-progress_callback": lambda done, total: print(f"{done:.1f}/{total:.1f}s")} 
    
  • -capture_stderr (bool): Deprecated, has no effect. FFmpeg's stderr is now always captured in Real-time Frames Mode: its last 50 lines (still mirrored to console when logging=True) are exposed via StreamGear's stderr_tail property and appended to the ValueError raised by stream() when FFmpeg dies early. FFmpeg's exit code is available via the returncode attribute after close() (or after transcode_source() in Single-Source Mode).

    Deprecated in v0.3.8

    Added in v0.3.7, always on since v0.3.8.

 

B. FFmpeg Parameters¶

Almost all FFmpeg parameters can be passed as dictionary attributes in stream_params. For example, to use the libx264 encoder with a quality target (capped by each stream's bitrate), you can pass the required FFmpeg parameters as dictionary attributes as follows:

Defaults: libx264 with -preset veryfast, -vf format=yuv420p, GOP of 2 seconds (-g, -keyint_min, -sc_threshold 0, -bf 1) and -tune zerolatency (Real-time Frames Mode and live-streaming only). VOD segments are 5 seconds in DASH (-seg_duration) and 2 seconds in HLS (FFmpeg's -hls_time default). No -crf is set by default.

Set a parameter's value to None to pass it as a valueless flag (e.g. {"-shortest": None}).

Please check the H.264 documentation âž¶ and FFmpeg Documentation âž¶ for more information on following parameters.

All FFmpeg parameters are case-sensitive. Double-check each parameter if any errors occur.

In addition to these parameters, almost any FFmpeg parameter (supported by the installed FFmpeg) is also supported. Be sure to read the FFmpeg Documentation carefully first.

# libx264 encoder and its supported parameters
stream_params = {"-vcodec":"libx264", "-crf": 20, "-preset": "fast", "-tune": "zerolatency"} 

 

Supported Encoders and Decoders¶

All encoders and decoders compiled with the FFmpeg in use are supported by the StreamGear API. You can check the compiled encoders by running the following command in your terminal:

Faster Transcoding with Stream Copy in Single Source Mode

For faster transcoding of input video, utilize Stream copy (-vcodec copy) as the input video encoder in the Single-Source Mode for creating HLS/DASH chunks of the primary stream efficiently. However, consider the following points:

  • âš  Stream copy is NOT compatible with Real-time Frames Mode, as this mode necessitates re-encoding of incoming frames. Therefore, the -vcodec copy parameter will be ignored.
  • âš  Stream copying NOT compatible with Custom Streams (-streams), which also require re-encoding for each additional stream. Consequently, the -vcodec copy parameter will be ignored.
  • When using the AAC audio stream from the input video, the Audio Stream copy (-acodec copy) encoder will be automatically applied (other audio codecs are encoded to aac).
# for checking encoder
ffmpeg -encoders           # use `ffmpeg.exe -encoders` on windows
# for checking decoders
ffmpeg -decoders           # use `ffmpeg.exe -decoders` on windows

Similarly, supported audio/video demuxers and filters depend on the FFmpeg binaries in use.

 

logging¶

This parameter enables logging (if True), essential for debugging.

Data-Type: Boolean

Default Value: Its default value is False.

Usage:

StreamGear(logging=True)

 


  1. 💡 In Real-time Frames Mode, the Primary Stream's framerate defaults to -input_framerate attribute value, if defined, else it will be 25fps. ↩