• Stars
    star
    668
  • Rank 67,542 (Top 2 %)
  • Language
    Python
  • License
    Apache License 2.0
  • Created over 7 years ago
  • Updated over 1 year ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

Pure Python FFmpeg-based live video / audio streaming to YouTube, Facebook, Periscope, Twitch, and more

Python scripted livestreaming using FFmpeg

DOI Actions Status pypi versions PyPi Download stats

Streams to one or multiple streaming sites simultaneously, using pure object-oriented Python (no extra packages) and FFmpeg. Tested with flake8, mypy type checking and pytest. visual_tests.py is a quick check of several command line scripting scenarios on your laptop. FFmpeg is used from Python subprocess to stream to sites including:

  • Facebook Live (requires FFmpeg >= 4.2 due to mandatory RTMPS)
  • YouTube Live
  • Twitch
  • also Ustream, Vimeo, Restream.io and more for streaming broadcasts.

PyLivestream diagram showing screen capture or camera simultaneously livestreaming to multiple services.

Troubleshooting

PyLivestream benefits

  • Python scripts compute good streaming parameters, and emit the command used to copy and paste if desired.
  • Works on any OS (Mac, Linux, Windows) and computing platform, including PC, Mac, and Raspberry Pi.
  • Uses single JSON file pylivestream.json to adjust parameters.

PyLivestream limitations

  • does not auto-restart if network connection glitches
  • is intended as a bare minimum command generator to run the FFmpeg program
  • is not intended for bidirectional robust streaming--consider a program/system based on Jitsi for that.

Design rationale

Why not do things without the command line, via linking libffmpeg, libgstreamer or libav?

  • the command-line approach does not require a compiler or OS-dependent libraries
  • once you get a setup working once, you don't even need Python anymore--just copy and paste the command line

Alternatives

Other projects using FFmpeg from Python include:

  • python-ffmpeg lower level use of FFmpeg with Python asyncio
  • asyncio-subprocess-ffpmeg simple asyncio subprocess example that could also be used as a template for general asyncio subprocess Python use.
  • ffmpy FFmpeg subprocess without asyncio

Install

Requires FFmpeg ≥ 3.0 (≥ 4.2 for Facebook Live RTMPS)

Latest release:

python3 -m pip install PyLivestream

Development version:

git clone https://github.com/scivision/PyLivestream

cd PyLivestream

python3 -m pip install -e .

Configuration: pylivestream.json

You can skip past this section to "stream start" if it's confusing. The defaults might work to get you started.

The pylivestream.json file you create has parameters relevant to the live stream. We suggest copying the example pylivestream.json and editing, then specify it for your streams.

  • screencap_origin: origin (upper left corner) of screen capture region in pixels.
  • screencap_size: resolution of screen capture (area to capture, starting from origin)
  • screencap_fps: frames/sec of screen capture
  • video_kbps: override automatic video bitrate in kbps
  • audio_rate: audio sampling frequency. Typically 44100 Hz (CD quality).
  • audio_bps: audio data rate--leave blank if you want no audio (usually used for "file", to make an animated GIF in post-processing)
  • preset: veryfast or ultrafast if CPU not able to keep up.
  • exe: override path to desired FFmpeg executable. In case you have multiple FFmpeg versions installed (say, from Anaconda Python).

Next are sys.platform specific parameters.

Seek help in FFmpeg documentation, try capturing to a file first and then update ~/pylivestream.json for sys.platform.

Deduce inputs

Each computer will need distinct pylivestream.json device input parameters:

  • audio_chan: audio device
  • camera_chan: camera device
  • screen_chan: desktop capture software port name

Loopback devices that let you "record what you hear" are operating system dependent. You may need to search documentation for your operating system to enable such a virtual loopback device.

Windows

ffmpeg -list_devices true -f dshow -i dummy

MacOS

ffmpeg -f avfoundation -list_devices true -i ""

Linux

v4l2-ctl --list-devices

API

There are two ways to start a stream (assuming you've configured as per following sections). Both do the same thing.

  • command line
    • python -m pylivestream.glob
    • python -m pylivestream.screen
    • python -m pylivestream.loopfile
    • python -m pylivestream.screen2disk
    • python -m pylivestream.camera
    • python -m pylivestream.microphone
  • import pylivestream.api as pls from within your Python script. For more information type help(pls) or help(pls.stream_microphone)
    • pls.stream_file()
    • pls.stream_microphone()
    • pls.stream_camera()

Authentication

The program loads a JSON file with the stream URL and hexadecimal stream key for the website(s) used. The user must specify this JSON file location.

YouTube Live

  1. configure YouTube Live.
  2. Edit "pylivestream.json" to have the YouTube streamid
  3. Run Python script and chosen input will stream on YouTube Live.
python -m pylivestream.screen youtube ./pylivestream.json

Facebook Live

Facebook Live requires FFmpeg >= 4.2 due to mandatory RTMPS

  1. configure your Facebook Live stream
  2. Put stream ID into the JSON file
  3. Run Python script for Facebook with chosen input
python -m pylivestream.screen facebook ./pylivestream.json

Twitter

TODO

Twitch

Create stream from Twitch Dashboard. Edit pylivestream.json file with "url" and "streamid" for Twitch. Run Python script for Twitch with chosen input:

python -m pylivestream.screen twitch ./pylivestream.json

Usage

Due to the complexity of streaming and the non-specific error codes FFmpeg emits, the default behavior is that if FFmpeg detects one stream has failed, ALL streams will stop streaming and the program ends.

Setup a pylivestream.json for computer and desired parameters. Copy the provided pylivestream.json and edit with values you determine.

File-Streaming

Camera

Note: your system may not have a camera, particularly if it's a virtual machine.

JSON:

  • camera_size: camera resolution -- find from v4l2-ctl --list-formats-ext or camera spec sheet.
  • camera_fps: camera fps -- found from command above or camera spec sheet

Stream to multiple sites, in this example Facebook Live and YouTube Live simultaneously:

python -m pylivestream.camera youtube facebook ./pylivestream.json

Screen Share Livestream

Stream to multiple sites, in this example Facebook Live and YouTube Live simultaneously:

python -m pylivestream.screen youtube facebook ./pylivestream.json

Image + Audio Livestream

Microphone audio + static image is accomplished by

python -m pylivestream.microphone youtube facebook ./pylivestream.json -image doc/logo.jpg

or wherever your image file is.

Audio-only Livestream

Audio-only streaming is not typically allowed by the Video streaming sites. It may fail to work altogether, or may fail when one file is done and another starts. That's not something we can fix within the scope of this project. You can test it to your own computer by:

python -m pylivestream.microphone localhost ./pylivestream.json

Screen capture to disk

This script saves your screen capture to a file on your disk:

python -m pylivestream.screen2disk myvid.avi ./pylivestream.json

Utilities

  • PyLivestream.get_framerate(vidfn) gives the frames/sec of a video file.
  • PyLivestream.get_resolution(vidfn) gives the resolution (width x height) of video file.

Notes

  • Linux requires X11, not Wayland (choose at login)
  • x11grab was deprecated in FFmpeg 3.3, was previously replaced by xcbgrab
  • Reference webpage

FFmpeg References

Windows

DirectShow didn't work for me on Windows 10, so I used gdigrab instead.

Stream References

Logo Credits

  • Owl PC: Creative Commons no attrib. commercial
  • YouTube: YouTube Brand Resources
  • Facebook: Wikimedia Commons

More Repositories

1

fortran2018-examples

Fortran 2018 standard examples with broad applications
Fortran
365
star
2

pyoptflow

Optical Flow estimation in pure Python
Python
74
star
3

mumps

MUMPS via CMake
CMake
73
star
4

pybluez-examples

Example Bluetooth tasks using the Python PyBluez module
Python
68
star
5

f2py-examples

Examples of using f2py to get high-speed Fortran integrated with Python easily
Fortran
46
star
6

pyimagevideo

write animated GIF, multipage append TIFF, AVI OGV video in Python
Python
39
star
7

findssh

Asyncio concurrent Python finds SSH servers (or other services with open ports) on an IPv4 subnet, WITHOUT NMAP
Python
37
star
8

Cpp23-examples

Example C++23 and C++20 syntax and tests of compilers and CMake
C++
35
star
9

fortran-filesystem

Object-oriented Fortran filesystem path manipulation library, based on C++17 filesystem.
Fortran
32
star
10

fortran-cpp-interface

Examples of Fortran 2003 C / C++ interfacing with Fortran
Fortran
29
star
11

python-performance

Performance benchmarks of Python, Numpy, etc. vs. other languages such as Matlab, Julia, Fortran.
Python
27
star
12

soothing-sounds

Demo several ways of making sound from Numpy arrays in Python, white noise
Python
27
star
13

fortran-submodule

Examples of modern Fortran 2008 submodule
Fortran
26
star
14

pybashutils

Collection of Bash and Python scripts I've made that may be generally useful
Shell
26
star
15

rpn-calc-fortran

Fortran 2018 Reverse Polish Notation (RPN) calculator. Over 100 functions not in standard Fortran
Fortran
23
star
16

linkchecker-markdown

Python asyncio + aiohttp Markdown *.md URL link checker: 10,000 files/second
Python
22
star
17

signal_subspace

vector and ensemble signal analysis w/ subspace methods such as Esprit and RootMusic
Python
22
star
18

sparse-fortran

Sparse array examples using MUMPS, Scalapack, BLACS, PARDISO with CMake
CMake
20
star
19

pibayer

Acquire RAW Bayer-masked images with Raspberry Pi camera (before demosaicking) in Python
Python
17
star
20

nrl-radar-sea-clutter

NRL Radar sea clutter model (2012) by Mital & Gregers-Hansen
MATLAB
17
star
21

cmakeutils

Helpful scripts and modules for CMake, especially for scientific computing, HPC, and Fortran
CMake
16
star
22

lapack-cmake-meson

CMake FindLAPACK.cmake that works with Intel MKL, Atlas, OpenBLAS, Netlib, LAPACK95 for C / C++ / Fortran
CMake
14
star
23

fortran-coarray-mpi-examples

Examples of Fortran Coarrays, MPI 3.0 / mpi_f08
CMake
14
star
24

em-sfm

Lorenzo Torresani's Structure from Motion Matlab code
MATLAB
13
star
25

bistatic-radar-sea-reflectivity

NRL model of bistatic sea surface radar reflectivity (2014) by Mital & Gregers-Hansen
MATLAB
12
star
26

Andor-sCMOS-examples

Andor sCMOS (Neo and Zyla) SDK3: focus on simplicity and speed.
C++
11
star
27

LAPACK95

CMake enhanced Netlib LAPACK95
CMake
11
star
28

mozilla-location-wifi

airport, netsh, nmcli: Mozilla Location Services with Wifi from Python on Windows, MacOS, Linux
Python
11
star
29

gitMC

concurrent, pure Python asyncio + Git: manage large (100+) numbers of Git repos
Python
11
star
30

scalapack

Netlib Scalapack with robust CMake
CMake
10
star
31

cmake-build-gcc

Build GCC and prereqs driven by CMake
CMake
10
star
32

office-headless

Headless document conversion and printing using LibreOffice or Microsoft Office
Python
9
star
33

cmake-cpu-detect

CMake detect CPU arch / model, useful for -mtune= on Intel oneAPI
CMake
9
star
34

linguist-python

Detect repo language(s) with thin Python wrapper of Github Linguist
Python
9
star
35

LCPFCT

NRL Flux-corrected Algorithm for Solving Generalized Continuity Equations LCPFCT from Python
Python
9
star
36

tincanradar

Utilities for designing, building, and using a $35 Tin Can Radar, from the original 2006 prototype
Python
9
star
37

lineclipping-python-fortran

Line clipping in clean, simple, modern Fortran and Python
Fortran
8
star
38

fortran-namelist

Python and Matlab readers for Fortran namelist => dict / struct
MATLAB
8
star
39

docker-fortran

coarray Fortran with Docker on Travis-CI
CMake
8
star
40

pypistats-plots

Plot Python package version support vs time via pypistats
Python
8
star
41

C23-examples

A few examples of C23 / C11 standards to check compilers and build systems
C
8
star
42

unlzw3

Pure Python unlzw to open .Z files on any platform running Python
Python
7
star
43

cmake-patch-file

Use GNU Patch from CMake to patch source/headers/etc.
CMake
7
star
44

hires_spectrum

High Resolution Spectrum Estimation
MATLAB
7
star
45

fortran-II-examples

Fortran II (year 1958) examples from IBM 704 manual, with modern Fortran equivalents
Fortran
7
star
46

pygit-bulk

manage large numbers (100+) Git users / teams using GitHub API v3 and PyGitHub
Python
7
star
47

basler-pypylon-examples

Examples for Basler cameras using Python PyPylon API
Python
7
star
48

radioutils-pascal

(Ham) radio utilities in Pascal by G4FGQ
Pascal
7
star
49

matlab-cmake-mex

CMake and Matlab MEX producing accelerated Matlab code
CMake
7
star
50

asyncio-subprocess-ffmpeg

Examples of Python asyncio.subprocess
Python
6
star
51

VehicleDetection-Python

Vehicle Detection using OpenCV in Python
Python
6
star
52

python-matlab-examples

Examples of neat Python and Matlab plotting and other tasks & hacks
Python
6
star
53

morecvutils

Python computer vision algorithms using OpenCV, including plots
Python
6
star
54

METIS

CMake enhanced Karypis METIS library 5.1.0
C
6
star
55

python-image-processing

2-D FFT and primitive filter example
Python
6
star
56

barron-optflow

Robert Barron optical flow code: slightest modifications for modern computers
C
5
star
57

mayavi-examples

3-D and 4-D plotting with Mayavi in Python
Python
5
star
58

wspr_txrx_simulator

Simulator for WSPR TX encoding and RX decoding.
MATLAB
5
star
59

robust-optical-flow

Python / Matlab interface to Michael Black's Robust optical flow
C
5
star
60

L-BFGS-B

Fortran code for L-BFGS-B, modernized
Fortran
5
star
61

GPSjamDetect

sub-$100 methods of finding GPS jammers via hobbyist & crowdsourced methods
Python
5
star
62

satcam

Identify what times a satellite should cross a camera pixel and triangulate satellites
MATLAB
5
star
63

harmonicradar

Code for modeling, simulating, processing harmonic radar data
Python
5
star
64

FClimDex

FClimDex climate data
Fortran
5
star
65

python_c_sockets

A demo of IPv6 UDP datagram on C and Python limited by interface speed (e.g. 1Gbps)
C
5
star
66

raspicam-spectra

Raspberry Pi camera spectral response OV5647
Python
4
star
67

radio-utils

Collection of scripts over the years simulating radio communications
Python
4
star
68

quindar-tones

Generate Quindar tones used by NASA for decades as in-band PTT signaling
Python
4
star
69

satkml

Plot satellite az/el, and make KML of satellites for visualization in Google Earth.
Python
4
star
70

asyncio-subprocess-examples

Examples of speedup from Python asyncio-subprocess
Python
4
star
71

hdf5-tester

Basic, easy, quick HDF5 recursive check for file errors with Python and h5py
Python
4
star
72

mpi_stubs

A dummy MPI-2 library for basic operations when actual MPI library not available.
C
3
star
73

cmake-macos-rosetta

Check MacOS CPU capabilities using CMake, C++, Python, ...
CMake
3
star
74

pyAndorNeo

Andor Neo drivers in Python
Python
3
star
75

nxp-nfc-pn7150

Makefiles for NXP NFC PN7150 USB board: MIKROE-2540
3
star
76

vallado-astrodynamics

Vallado Fundamentals of Astrodynamics and Applications code
Fortran
3
star
77

pyfindfiles

Concurrently find files containing text, or project language with codemeta.json
Python
3
star
78

github-actions-arm64

Example of ARM64 image with Github Actions
C
3
star
79

matlab-gnuradio-baseband

GNU Radio SDR raw .bin format into Matlab .bb baseband format
MATLAB
3
star
80

google-drive-public

DEPRECATED/DO NOT USE: Python no-login download of files from publicly-shared Google Drive folders
Python
3
star
81

hwloc-fortran

Simple Fortran binding for HWLOC to get CPU count, with fallback
CMake
3
star
82

lapack-cmake-fetchContent

LAPACK with enhanced CMake
CMake
3
star
83

scotch-cmake

Access / autobuild Scotch as CMake ExternalProject
CMake
3
star
84

physical-cpu-count

Single C++ function cpu_count() gives physical CPU count across OS and hardware.
C++
3
star
85

random-seed-examples

Examples of random seed initialization in: C, C++, Fortran, Julia, Matlab, Python
CMake
2
star
86

textutils3

Recursively spellcheck files using aspell or other backend
Python
2
star
87

mbta_salary

Boston MBTA transit salary analysis
Python
2
star
88

cmake-package-install

Example of minimal CMake package creation for relocatable install
CMake
2
star
89

wine-utils

Shortcuts to use Microsoft Office on Linux from WINE, and Echolink on WINE
Shell
2
star
90

latex-examples

Example of block diagrams, presentations, other practical STEM uses of LaTeX
TeX
2
star
91

skyfield-examples

Examples using Skyfield (replaces PyEphem)
Python
2
star
92

amtrak-connections

Using archival data from statusmaps.net to do simple analysis of transfer statistics (missed connections)
Python
2
star
93

gsuite-utils

Scripts handy for admining G Suite domains and organizations
Python
2
star
94

ts07d

Tsyganenko and Sitnov Empirical Magnetic Model TS07D
Fortran
2
star
95

cmake-gpg-sign

CMake / CPack sign binaries with GnuPG
CMake
2
star
96

matlab-stdin-pipe

Pipe stdin with Python or Java to run external processes from Matlab
MATLAB
2
star
97

appveyor-gfortran

Simple example of AppVeyor builds with Gfortran. Also CMake unit tests for stdout.
CMake
2
star
98

mumps-fetchcontent

Example of using MUMPS via CMake FetchContent
Fortran
2
star
99

hamlib-utils

bash/matlab scripts used with hamlib for remote control of amateur radio equipment
Shell
2
star
100

cmake-apple-silicon-count

Workarounds for Apple Silicon CPU detection with hwloc and CMake
C
2
star