# Python scripted livestreaming using FFmpeg
[![DOI](https://zenodo.org/badge/91214767.svg)](https://zenodo.org/badge/latestdoi/91214767)
![Actions Status](https://github.com/scivision/pylivestream/workflows/ci/badge.svg)
[![pypi versions](https://img.shields.io/pypi/pyversions/PyLivestream.svg)](https://pypi.python.org/pypi/PyLivestream)
[![PyPi Download stats](https://static.pepy.tech/badge/pylivestream)](https://pepy.tech/project/pylivestream)
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.](./doc/logo.png)
[Troubleshooting](./Troubleshooting.md)
## 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](https://github.com/jonghwanhyeon/python-ffmpeg) lower level use of FFmpeg with Python asyncio
* [asyncio-subprocess-ffpmeg](https://github.com/scivision/asyncio-subprocess-ffmpeg) simple asyncio subprocess example that could also be used as a template for general asyncio subprocess Python use.
* [ffmpy](https://github.com/Ch00k/ffmpy) FFmpeg subprocess without asyncio
## Install
Requires FFmpeg ≥ 3.0 (≥ 4.2 for Facebook Live RTMPS)
Latest release:
```sh
python3 -m pip install PyLivestream
```
Development version:
```sh
git clone https://github.com/scivision/PyLivestream
cd PyLivestream
python3 -m pip install -e .
```
FFmpeg can be obtained like:
* Windows: `winget install ffmpeg`
* Linux: `sudo apt install ffmpeg`
* MacOS: `brew install ffmpeg`
If errors result from FFmpeg not in PATH environment variable, optionally set environment variable "FFMPEG_ROOT" to the directory containing FFmpeg executable.
## 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](./src/pylivestream/data/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
```sh
ffmpeg -list_devices true -f dshow -i dummy
```
#### MacOS
```sh
ffmpeg -f avfoundation -list_devices true -i ""
```
#### Linux
```sh
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.fglob
* 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](https://www.youtube.com/live_dashboard) YouTube Live.
2. Edit "pylivestream.json" to have the YouTube streamid
3. Run Python script and chosen input will stream on YouTube Live.
```sh
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](https://www.facebook.com/live/create) into the JSON file
3. Run Python script for Facebook with chosen input
```sh
python -m pylivestream.screen facebook ./pylivestream.json
```
### Twitter
TODO
### Twitch
Create stream from
[Twitch Dashboard](https://dashboard.twitch.tv/settings/channel#stream-preferences).
Edit pylivestream.json file with "url" and "streamid" for Twitch.
Run Python script for Twitch with chosen input:
```sh
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](./src/pylivestream/data/pylivestream.json)
and edit with values you determine.
[File-Streaming](./File-Streaming.md)
### 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:
```sh
python -m pylivestream.camera youtube facebook ./pylivestream.json
```
### Screen Share Livestream
Stream to multiple sites, in this example Facebook Live and YouTube Live simultaneously:
```sh
python -m pylivestream.screen youtube facebook ./pylivestream.json
```
### Image + Audio Livestream
Microphone audio + static image is accomplished by
```sh
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:
```sh
python -m pylivestream.microphone localhost ./pylivestream.json
```
### Screen capture to disk
This script saves your screen capture to a file on your disk:
```sh
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](https://www.scivision.dev/youtube-live-ffmpeg-livestream/)
### FFmpeg References
* [streaming](https://trac.ffmpeg.org/wiki/EncodingForStreamingSites)
* [camera](https://trac.ffmpeg.org/wiki/Capture/Webcam)
* Camera [overlay](https://trac.ffmpeg.org/wiki/EncodingForStreamingSites#Withwebcamoverlay)
### Windows
* [gdigrab](https://ffmpeg.org/ffmpeg-devices.html#gdigrab)
DirectShow didn't work for me on Windows 10, so I used gdigrab instead.
* [DirectShow](https://trac.ffmpeg.org/wiki/DirectShow) device selection
* DirectShow [examples](https://ffmpeg.org/ffmpeg-devices.html#Examples-4)
### Stream References
* [Twitch parameters](https://help.twitch.tv/customer/portal/articles/1253460-broadcast-requirements)
* Twitch [ingest servers](https://stream.twitch.tv/ingests/)
* Twitch [encoding](https://stream.twitch.tv/encoding/)
* [Twitter Live parameters](https://help.twitter.com/en/using-twitter/twitter-live)
* [YouTube Live parameters](https://support.google.com/youtube/answer/2853702)
* [Facebook Live parameters](https://www.facebook.com/facebookmedia/get-started/live)
* [Ustream parameters](https://support.ustream.tv/hc/en-us/articles/207852117-Internet-connection-and-recommended-encoding-settings)
* Vimeo [config](https://help.vimeo.com/hc/en-us/articles/115012811168)
* Vimeo [parameters](https://help.vimeo.com/hc/en-us/articles/115012811208-Encoder-guides)
### Logo Credits
* Owl PC: Creative Commons no attrib. commercial
* YouTube: YouTube Brand Resources
* Facebook: Wikimedia Commons
Raw data
{
"_id": null,
"home_page": null,
"name": "pylivestream",
"maintainer": null,
"docs_url": null,
"requires_python": ">=3.9",
"maintainer_email": null,
"keywords": "youtube, ffmpeg, twitch, twitter live, facebook live, restream.io",
"author": null,
"author_email": null,
"download_url": "https://files.pythonhosted.org/packages/b9/1a/bd4a9186c67ffdf2abbc3765f9a26148a2d203d63f13bcb27929a5c00ef2/pylivestream-2.1.0.tar.gz",
"platform": null,
"description": "# Python scripted livestreaming using FFmpeg\n\n[![DOI](https://zenodo.org/badge/91214767.svg)](https://zenodo.org/badge/latestdoi/91214767)\n![Actions Status](https://github.com/scivision/pylivestream/workflows/ci/badge.svg)\n[![pypi versions](https://img.shields.io/pypi/pyversions/PyLivestream.svg)](https://pypi.python.org/pypi/PyLivestream)\n[![PyPi Download stats](https://static.pepy.tech/badge/pylivestream)](https://pepy.tech/project/pylivestream)\n\nStreams to one or **multiple** streaming sites simultaneously, using pure object-oriented Python (no extra packages) and FFmpeg.\nTested with `flake8`, `mypy` type checking and `pytest`.\n`visual_tests.py` is a quick check of several command line scripting scenarios on your laptop.\nFFmpeg is used from Python `subprocess` to stream to sites including:\n\n* Facebook Live (requires FFmpeg >= 4.2 due to mandatory RTMPS)\n* YouTube Live\n* Twitch\n* also Ustream, Vimeo, Restream.io and more for streaming broadcasts.\n\n![PyLivestream diagram showing screen capture or camera simultaneously livestreaming to multiple services.](./doc/logo.png)\n\n[Troubleshooting](./Troubleshooting.md)\n\n## PyLivestream benefits\n\n* Python scripts compute good streaming parameters, and emit the command used to copy and paste if desired.\n* Works on any OS (Mac, Linux, Windows) and computing platform, including PC, Mac, and Raspberry Pi.\n* Uses single JSON file pylivestream.json to adjust parameters.\n\n### PyLivestream limitations\n\n* does *not* auto-restart if network connection glitches\n* is intended as a bare minimum command generator to run the FFmpeg program\n* is not intended for bidirectional robust streaming--consider a program/system based on Jitsi for that.\n\n### Design rationale\n\nWhy not do things without the command line, via linking libffmpeg, libgstreamer or libav?\n\n* the command-line approach does not require a compiler or OS-dependent libraries\n* once you get a setup working once, you don't even need Python anymore--just copy and paste the command line\n\n### Alternatives\n\nOther projects using FFmpeg from Python include:\n\n* [python-ffmpeg](https://github.com/jonghwanhyeon/python-ffmpeg) lower level use of FFmpeg with Python asyncio\n* [asyncio-subprocess-ffpmeg](https://github.com/scivision/asyncio-subprocess-ffmpeg) simple asyncio subprocess example that could also be used as a template for general asyncio subprocess Python use.\n* [ffmpy](https://github.com/Ch00k/ffmpy) FFmpeg subprocess without asyncio\n\n## Install\n\nRequires FFmpeg ≥ 3.0 (≥ 4.2 for Facebook Live RTMPS)\n\nLatest release:\n\n```sh\npython3 -m pip install PyLivestream\n```\n\nDevelopment version:\n\n```sh\ngit clone https://github.com/scivision/PyLivestream\n\ncd PyLivestream\n\npython3 -m pip install -e .\n```\n\nFFmpeg can be obtained like:\n\n* Windows: `winget install ffmpeg`\n* Linux: `sudo apt install ffmpeg`\n* MacOS: `brew install ffmpeg`\n\nIf errors result from FFmpeg not in PATH environment variable, optionally set environment variable \"FFMPEG_ROOT\" to the directory containing FFmpeg executable.\n\n## Configuration: pylivestream.json\n\nYou can skip past this section to \"stream start\" if it's confusing.\nThe defaults might work to get you started.\n\nThe pylivestream.json file you create has parameters relevant to the live stream.\nWe suggest copying the example\n[pylivestream.json](./src/pylivestream/data/pylivestream.json)\nand editing, then specify it for your streams.\n\n* `screencap_origin`: origin (upper left corner) of screen capture region in pixels.\n* `screencap_size`: resolution of screen capture (area to capture, starting from origin)\n* `screencap_fps`: frames/sec of screen capture\n* `video_kbps`: override automatic video bitrate in kbps\n* `audio_rate`: audio sampling frequency. Typically 44100 Hz (CD quality).\n* `audio_bps`: audio data rate--**leave blank if you want no audio** (usually used for \"file\", to make an animated GIF in post-processing)\n* `preset`: `veryfast` or `ultrafast` if CPU not able to keep up.\n* `exe`: override path to desired FFmpeg executable. In case you have multiple FFmpeg versions installed (say, from Anaconda Python).\n\nNext are `sys.platform` specific parameters.\n\nSeek help in FFmpeg documentation, try capturing to a file first and then update ~/pylivestream.json for `sys.platform`.\n\n### Deduce inputs\n\nEach computer will need distinct pylivestream.json device input parameters:\n\n* audio_chan: audio device\n* camera_chan: camera device\n* screen_chan: desktop capture software port name\n\nLoopback devices that let you \"record what you hear\" are operating system dependent.\nYou may need to search documentation for your operating system to enable such a virtual loopback device.\n\n#### Windows\n\n```sh\nffmpeg -list_devices true -f dshow -i dummy\n```\n\n#### MacOS\n\n```sh\nffmpeg -f avfoundation -list_devices true -i \"\"\n```\n\n#### Linux\n\n```sh\nv4l2-ctl --list-devices\n```\n\n## API\n\nThere are two ways to start a stream (assuming you've configured as per following sections).\nBoth do the same thing.\n\n* command line\n * python -m pylivestream.fglob\n * python -m pylivestream.screen\n * python -m pylivestream.loopfile\n * python -m pylivestream.screen2disk\n * python -m pylivestream.camera\n * python -m pylivestream.microphone\n* `import pylivestream.api as pls` from within your Python script. For more information type `help(pls)` or `help(pls.stream_microphone)`\n * pls.stream_file()\n * pls.stream_microphone()\n * pls.stream_camera()\n\n## Authentication\n\nThe program loads a JSON file with the stream URL and hexadecimal stream key for the website(s) used.\nThe user must specify this JSON file location.\n\n### YouTube Live\n\n1. [configure](https://www.youtube.com/live_dashboard) YouTube Live.\n2. Edit \"pylivestream.json\" to have the YouTube streamid\n3. Run Python script and chosen input will stream on YouTube Live.\n\n```sh\npython -m pylivestream.screen youtube ./pylivestream.json\n```\n\n### Facebook Live\n\nFacebook Live requires FFmpeg >= 4.2 due to mandatory RTMPS\n\n1. configure your Facebook Live stream\n2. Put [stream ID](https://www.facebook.com/live/create) into the JSON file\n3. Run Python script for Facebook with chosen input\n\n```sh\npython -m pylivestream.screen facebook ./pylivestream.json\n```\n\n### Twitter\n\nTODO\n\n### Twitch\n\nCreate stream from\n[Twitch Dashboard](https://dashboard.twitch.tv/settings/channel#stream-preferences).\nEdit pylivestream.json file with \"url\" and \"streamid\" for Twitch.\nRun Python script for Twitch with chosen input:\n\n```sh\npython -m pylivestream.screen twitch ./pylivestream.json\n```\n\n## Usage\n\nDue 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.\n\nSetup a pylivestream.json for computer and desired parameters.\nCopy the provided\n[pylivestream.json](./src/pylivestream/data/pylivestream.json)\nand edit with values you determine.\n\n[File-Streaming](./File-Streaming.md)\n\n### Camera\n\nNote: your system may not have a camera, particularly if it's a virtual machine.\n\nJSON:\n\n* `camera_size`: camera resolution -- find from `v4l2-ctl --list-formats-ext` or camera spec sheet.\n* `camera_fps`: camera fps -- found from command above or camera spec sheet\n\nStream to multiple sites, in this example Facebook Live and YouTube Live simultaneously:\n\n```sh\npython -m pylivestream.camera youtube facebook ./pylivestream.json\n```\n\n### Screen Share Livestream\n\nStream to multiple sites, in this example Facebook Live and YouTube Live simultaneously:\n\n```sh\npython -m pylivestream.screen youtube facebook ./pylivestream.json\n```\n\n### Image + Audio Livestream\n\nMicrophone audio + static image is accomplished by\n\n```sh\npython -m pylivestream.microphone youtube facebook ./pylivestream.json -image doc/logo.jpg\n```\n\nor wherever your image file is.\n\n### Audio-only Livestream\n\nAudio-only streaming is not typically allowed by the Video streaming sites.\nIt may fail to work altogether, or may fail when one file is done and another starts.\nThat's not something we can fix within the scope of this project.\nYou can test it to your own computer by:\n\n```sh\npython -m pylivestream.microphone localhost ./pylivestream.json\n```\n\n### Screen capture to disk\n\nThis script saves your screen capture to a file on your disk:\n\n```sh\npython -m pylivestream.screen2disk myvid.avi ./pylivestream.json\n```\n\n## Utilities\n\n* `PyLivestream.get_framerate(vidfn)` gives the frames/sec of a video file.\n* `PyLivestream.get_resolution(vidfn)` gives the resolution (width x height) of video file.\n\n## Notes\n\n* Linux requires X11, not Wayland (choose at login)\n* `x11grab` was deprecated in FFmpeg 3.3, was previously replaced by `xcbgrab`\n* Reference [webpage](https://www.scivision.dev/youtube-live-ffmpeg-livestream/)\n\n### FFmpeg References\n\n* [streaming](https://trac.ffmpeg.org/wiki/EncodingForStreamingSites)\n* [camera](https://trac.ffmpeg.org/wiki/Capture/Webcam)\n* Camera [overlay](https://trac.ffmpeg.org/wiki/EncodingForStreamingSites#Withwebcamoverlay)\n\n### Windows\n\n* [gdigrab](https://ffmpeg.org/ffmpeg-devices.html#gdigrab)\n\nDirectShow didn't work for me on Windows 10, so I used gdigrab instead.\n\n* [DirectShow](https://trac.ffmpeg.org/wiki/DirectShow) device selection\n* DirectShow [examples](https://ffmpeg.org/ffmpeg-devices.html#Examples-4)\n\n### Stream References\n\n* [Twitch parameters](https://help.twitch.tv/customer/portal/articles/1253460-broadcast-requirements)\n* Twitch [ingest servers](https://stream.twitch.tv/ingests/)\n* Twitch [encoding](https://stream.twitch.tv/encoding/)\n\n* [Twitter Live parameters](https://help.twitter.com/en/using-twitter/twitter-live)\n* [YouTube Live parameters](https://support.google.com/youtube/answer/2853702)\n* [Facebook Live parameters](https://www.facebook.com/facebookmedia/get-started/live)\n* [Ustream parameters](https://support.ustream.tv/hc/en-us/articles/207852117-Internet-connection-and-recommended-encoding-settings)\n* Vimeo [config](https://help.vimeo.com/hc/en-us/articles/115012811168)\n* Vimeo [parameters](https://help.vimeo.com/hc/en-us/articles/115012811208-Encoder-guides)\n\n### Logo Credits\n\n* Owl PC: Creative Commons no attrib. commercial\n* YouTube: YouTube Brand Resources\n* Facebook: Wikimedia Commons\n",
"bugtrack_url": null,
"license": null,
"summary": "Livestream using FFmpeg to YouTube Live, Twitter, Facebook Live, Twitch, and more",
"version": "2.1.0",
"project_urls": null,
"split_keywords": [
"youtube",
" ffmpeg",
" twitch",
" twitter live",
" facebook live",
" restream.io"
],
"urls": [
{
"comment_text": "",
"digests": {
"blake2b_256": "4d3ec7a36536bbd8304e0a0fefb72d7bf10c57986ce4c4d493b3306331d57794",
"md5": "5aa9f6d4e1a69179908501b5241740f8",
"sha256": "5106d4f8bbefdca95073f6e67899fa47b9ebb8cfa1794779e623d2bc08701013"
},
"downloads": -1,
"filename": "pylivestream-2.1.0-py3-none-any.whl",
"has_sig": false,
"md5_digest": "5aa9f6d4e1a69179908501b5241740f8",
"packagetype": "bdist_wheel",
"python_version": "py3",
"requires_python": ">=3.9",
"size": 787089,
"upload_time": "2024-05-07T03:13:03",
"upload_time_iso_8601": "2024-05-07T03:13:03.314342Z",
"url": "https://files.pythonhosted.org/packages/4d/3e/c7a36536bbd8304e0a0fefb72d7bf10c57986ce4c4d493b3306331d57794/pylivestream-2.1.0-py3-none-any.whl",
"yanked": false,
"yanked_reason": null
},
{
"comment_text": "",
"digests": {
"blake2b_256": "b91abd4a9186c67ffdf2abbc3765f9a26148a2d203d63f13bcb27929a5c00ef2",
"md5": "f35280abd33fb9f990c411724c82e733",
"sha256": "a6721e278bc232af13c0315acd3cbc48aec1bc4e36a7d3f40d45b0595efb5c6c"
},
"downloads": -1,
"filename": "pylivestream-2.1.0.tar.gz",
"has_sig": false,
"md5_digest": "f35280abd33fb9f990c411724c82e733",
"packagetype": "sdist",
"python_version": "source",
"requires_python": ">=3.9",
"size": 786044,
"upload_time": "2024-05-07T03:13:05",
"upload_time_iso_8601": "2024-05-07T03:13:05.431062Z",
"url": "https://files.pythonhosted.org/packages/b9/1a/bd4a9186c67ffdf2abbc3765f9a26148a2d203d63f13bcb27929a5c00ef2/pylivestream-2.1.0.tar.gz",
"yanked": false,
"yanked_reason": null
}
],
"upload_time": "2024-05-07 03:13:05",
"github": false,
"gitlab": false,
"bitbucket": false,
"codeberg": false,
"lcname": "pylivestream"
}