├── .gitignore ├── LICENSE ├── README.md ├── dev-requirements.in ├── dev-requirements.txt ├── etc ├── ROBOTO_LICENSE ├── roboto.ttf └── screenshot.png ├── hlsstream ├── __init__.py ├── __main__.py ├── api.py ├── input.py ├── stream.py └── sync.py ├── requirements.in ├── requirements.txt └── static └── index.html /.gitignore: -------------------------------------------------------------------------------- 1 | # Byte-compiled / optimized / DLL files 2 | __pycache__/ 3 | *.py[cod] 4 | *$py.class 5 | 6 | # C extensions 7 | *.so 8 | 9 | # Distribution / packaging 10 | .Python 11 | build/ 12 | develop-eggs/ 13 | dist/ 14 | downloads/ 15 | eggs/ 16 | .eggs/ 17 | lib/ 18 | lib64/ 19 | parts/ 20 | sdist/ 21 | var/ 22 | wheels/ 23 | pip-wheel-metadata/ 24 | share/python-wheels/ 25 | *.egg-info/ 26 | .installed.cfg 27 | *.egg 28 | MANIFEST 29 | 30 | # PyInstaller 31 | # Usually these files are written by a python script from a template 32 | # before PyInstaller builds the exe, so as to inject date/other infos into it. 33 | *.manifest 34 | *.spec 35 | 36 | # Installer logs 37 | pip-log.txt 38 | pip-delete-this-directory.txt 39 | 40 | # Unit test / coverage reports 41 | htmlcov/ 42 | .tox/ 43 | .nox/ 44 | .coverage 45 | .coverage.* 46 | .cache 47 | nosetests.xml 48 | coverage.xml 49 | *.cover 50 | *.py,cover 51 | .hypothesis/ 52 | .pytest_cache/ 53 | 54 | # Translations 55 | *.mo 56 | *.pot 57 | 58 | # Django stuff: 59 | *.log 60 | local_settings.py 61 | db.sqlite3 62 | db.sqlite3-journal 63 | 64 | # Flask stuff: 65 | instance/ 66 | .webassets-cache 67 | 68 | # Scrapy stuff: 69 | .scrapy 70 | 71 | # Sphinx documentation 72 | docs/_build/ 73 | 74 | # PyBuilder 75 | target/ 76 | 77 | # Jupyter Notebook 78 | .ipynb_checkpoints 79 | 80 | # IPython 81 | profile_default/ 82 | ipython_config.py 83 | 84 | # pyenv 85 | .python-version 86 | 87 | # pipenv 88 | # According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control. 89 | # However, in case of collaboration, if having platform-specific dependencies or dependencies 90 | # having no cross-platform support, pipenv may install dependencies that don't work, or not 91 | # install all needed dependencies. 92 | #Pipfile.lock 93 | 94 | # PEP 582; used by e.g. github.com/David-OConnor/pyflow 95 | __pypackages__/ 96 | 97 | # Celery stuff 98 | celerybeat-schedule 99 | celerybeat.pid 100 | 101 | # SageMath parsed files 102 | *.sage.py 103 | 104 | # Environments 105 | .env 106 | .venv 107 | env/ 108 | venv/ 109 | ENV/ 110 | env.bak/ 111 | venv.bak/ 112 | 113 | # Spyder project settings 114 | .spyderproject 115 | .spyproject 116 | 117 | # Rope project settings 118 | .ropeproject 119 | 120 | # mkdocs documentation 121 | /site 122 | 123 | # mypy 124 | .mypy_cache/ 125 | .dmypy.json 126 | dmypy.json 127 | 128 | # Pyre type checker 129 | .pyre/ 130 | 131 | video/* 132 | !video/__keep__ -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2022 Christoph Heindl 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # python-hls-stream 2 | 3 | A minimal proof-of-concept to demonstrate real-time (seekable) HLS streaming from Python with dynamic timeline marker support. 4 | 5 | 6 |
7 |
8 | Front-end of HLS streaming demo. Click to view video. 9 |
10 | 11 | The video linked above shows a real-time HTTP Live Streaming (HLS) generated in Python using ffmpeg. Ocassionally, an event (mint squares) is emitted that leads to markers being added to the HTML5 client table and the timeline. Depending on the HLS configuration you can leave the live edge and seek backwards in time. 12 | 13 | ## Architecture 14 | The system combines multiple processes to generated the desired result 15 | - `hlsstream.sync` (Python) key/value cache for inter-process communication based on `multiprocessing.SyncManager`. 16 | - `hlsstream.stream` (Python) generates the checkerboard images and encodes them as HLS stream using `ffmpeg`. Additionally, events (mint squares) are randomly emitted and stored in the cache as time/text dict. 17 | - `hlsstream.api` (Python) a web-API that exposes the HLS stream plus a marker query API using `fastAPI`. Additionally it serves `index.html` that contains an embedded video-player along with business logic for handling markers. 18 | - `frontend` (HTML5) client frontend using `video-js`. 19 | 20 | ## Limitations 21 | Keep in mind, this is a proof-of-concept and thus expect glitches and other issues. 22 | - `hlsstream.sync` For production you should switch this for `redis` or `memcached`. 23 | - `hlsstream.stream` The event detections (mint-square) is not based on computer-vision but based on checkerboard generator knowledge. In reality, you will have separate detection services that read images and emit marker events. 24 | - `hlsstream.stream` HLS stream encoder expects `rawvideo` (images) input. Except for setting a target FPS, I did not find a way to provide a PTS per frame. Hence, `ffmpeg` assumes `1/FPS` between two frames, even if reality the FPS varies. To resolve, you should keep track of generator timestamps vs target timestamps and if an event needs to be generated, convert from generator timestamp to target timestamp. The demo currently employs a busy-waiting strategy to keep timestamps closest to target fps. This leads to high CPU usage. 25 | - `hlsstream.api` currently configures CORS very carelessly. In production you will need to restrict it accordingly. 26 | - `frontend` attempts to determine the endpoints of the timeline of the `video-js` player. The current method seems to work when live or when not tracking the live stream, but might fail when `hlsstream.stream` is terminated. A refresh should fix things. 27 | 28 | 29 | ## Clocks 30 | The system involves several clocks that need to be synchronized. 31 | - `GEN`: Generator clock in [sec]. This clock is usually built into capturing devices such as cameras. 32 | - `HLS`: HLS stream clock in [sec]. Frames from `GEN` are encoded for `HLS`. When `HLS` assumes a fixed encoding frame-rate, you need to keep track of `GEN` and `HLS` timestamps. While your system internal process will use `GEN` timestamps, the API should report `HLS` timestamps. 33 | - `CLIENT`: HMTL video-js clock in [sec]. When the client connects to the HLS stream, the client clock is reset. To seek the video correctly, we need to convert markers from `HLS <-> CLIENT`. If we assume this transformation takes only an offset and if we assume that the segment duration is constant, we can compute the offset as 34 | 35 | offset = HLS-sequence * HLS-duration 36 | 37 | ## Usage 38 | Python 3.9 is required. This should work on linux/windows. 39 | ```bash 40 | $ pip -m venv --upgrade-deps .venv 41 | $ source .venv/bin/activate 42 | (.venv) $ pip install pip-tools 43 | (.venv) $ pip-sync requirements.txt dev-requirements.txt 44 | (.venv) $ python -m hlsstream 45 | ``` 46 | 47 | Point your browser to `http://127.0.0.1:5000`. Same commands, except for how to activate the venv, apply to Windows. 48 | -------------------------------------------------------------------------------- /dev-requirements.in: -------------------------------------------------------------------------------- 1 | -c requirements.txt 2 | black 3 | flake8 4 | pytest 5 | matplotlib -------------------------------------------------------------------------------- /dev-requirements.txt: -------------------------------------------------------------------------------- 1 | # 2 | # This file is autogenerated by pip-compile with python 3.9 3 | # To update, run: 4 | # 5 | # pip-compile dev-requirements.in 6 | # 7 | atomicwrites==1.4.0 8 | # via pytest 9 | attrs==21.4.0 10 | # via pytest 11 | black==22.3.0 12 | # via -r dev-requirements.in 13 | click==8.1.3 14 | # via 15 | # -c requirements.txt 16 | # black 17 | colorama==0.4.4 18 | # via 19 | # -c requirements.txt 20 | # click 21 | # pytest 22 | cycler==0.11.0 23 | # via matplotlib 24 | flake8==4.0.1 25 | # via -r dev-requirements.in 26 | fonttools==4.33.3 27 | # via matplotlib 28 | iniconfig==1.1.1 29 | # via pytest 30 | kiwisolver==1.4.2 31 | # via matplotlib 32 | matplotlib==3.5.2 33 | # via -r dev-requirements.in 34 | mccabe==0.6.1 35 | # via flake8 36 | mypy-extensions==0.4.3 37 | # via black 38 | numpy==1.22.3 39 | # via 40 | # -c requirements.txt 41 | # matplotlib 42 | packaging==21.3 43 | # via 44 | # matplotlib 45 | # pytest 46 | pathspec==0.9.0 47 | # via black 48 | pillow==9.1.0 49 | # via matplotlib 50 | platformdirs==2.5.2 51 | # via black 52 | pluggy==1.0.0 53 | # via pytest 54 | py==1.11.0 55 | # via pytest 56 | pycodestyle==2.8.0 57 | # via flake8 58 | pyflakes==2.4.0 59 | # via flake8 60 | pyparsing==3.0.8 61 | # via 62 | # matplotlib 63 | # packaging 64 | pytest==7.1.2 65 | # via -r dev-requirements.in 66 | python-dateutil==2.8.2 67 | # via matplotlib 68 | six==1.16.0 69 | # via python-dateutil 70 | tomli==2.0.1 71 | # via 72 | # black 73 | # pytest 74 | typing-extensions==4.2.0 75 | # via 76 | # -c requirements.txt 77 | # black 78 | -------------------------------------------------------------------------------- /etc/ROBOTO_LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright [yyyy] [name of copyright owner] 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /etc/roboto.ttf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/cheind/python-hls-stream/92e8630cdfd877ea47b1c925873b31b8fc4fbe04/etc/roboto.ttf -------------------------------------------------------------------------------- /etc/screenshot.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/cheind/python-hls-stream/92e8630cdfd877ea47b1c925873b31b8fc4fbe04/etc/screenshot.png -------------------------------------------------------------------------------- /hlsstream/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/cheind/python-hls-stream/92e8630cdfd877ea47b1c925873b31b8fc4fbe04/hlsstream/__init__.py -------------------------------------------------------------------------------- /hlsstream/__main__.py: -------------------------------------------------------------------------------- 1 | # https://www.programmersought.com/article/54568977634/ 2 | # https://github.com/kkroening/ffmpeg-python/issues/154 3 | # https://github.com/kkroening/ffmpeg-python/tree/master/examples 4 | 5 | from subprocess import Popen 6 | import sys 7 | import time 8 | 9 | if __name__ == "__main__": 10 | 11 | processes: list[Popen] = [] 12 | try: 13 | processes.append( 14 | Popen([sys.executable, "-m", "hlsstream.sync"], start_new_session=True) 15 | ) 16 | processes.append( 17 | Popen([sys.executable, "-m", "hlsstream.api"], start_new_session=True) 18 | ) 19 | processes.append( 20 | Popen([sys.executable, "-m", "hlsstream.stream"], start_new_session=True) 21 | ) 22 | while True: 23 | time.sleep(1.0) 24 | except KeyboardInterrupt: 25 | print("Ctrl C") 26 | finally: 27 | for p in processes: 28 | p.terminate() 29 | p.wait() 30 | -------------------------------------------------------------------------------- /hlsstream/api.py: -------------------------------------------------------------------------------- 1 | import uvicorn 2 | import json 3 | from fastapi import FastAPI, Response 4 | from fastapi.staticfiles import StaticFiles 5 | from starlette.responses import FileResponse 6 | from fastapi.middleware.cors import CORSMiddleware 7 | from fastapi.responses import JSONResponse 8 | 9 | from .sync import Cache 10 | 11 | 12 | cache = Cache() 13 | 14 | 15 | app = FastAPI() 16 | app.add_middleware( 17 | CORSMiddleware, 18 | allow_origins=["*"], 19 | allow_credentials=True, 20 | allow_methods=["*"], 21 | allow_headers=["*"], 22 | ) 23 | 24 | 25 | @app.get("/video/{fileName}") 26 | async def video(response: Response, fileName: str): 27 | response.headers["Content-Type"] = "application/x-mpegURL" 28 | return FileResponse("video/" + fileName, filename=fileName) 29 | 30 | 31 | @app.get("/markers") 32 | async def markers(response: Response, ts_start: float = -1.0): 33 | markers = cache.get("markers", []) 34 | markers = [m for m in markers if m["time"] > ts_start] 35 | return JSONResponse(content=json.dumps({"markers": markers})) 36 | 37 | 38 | app.mount("/", StaticFiles(directory="static", html=True), name="static") 39 | 40 | 41 | def main(): 42 | uvicorn.run( 43 | "hlsstream.api:app", 44 | host="0.0.0.0", 45 | port=5000, 46 | log_level="debug", 47 | reload=True, 48 | debug=True, 49 | ) 50 | 51 | 52 | if __name__ == "__main__": 53 | main() 54 | -------------------------------------------------------------------------------- /hlsstream/input.py: -------------------------------------------------------------------------------- 1 | import dataclasses 2 | from typing import Iterator, Optional 3 | import numpy as np 4 | import time 5 | import logging 6 | import datetime 7 | 8 | _logger = logging.getLogger("input") 9 | 10 | 11 | def rate_limited_loop(fps: float) -> Iterator[float]: 12 | """Rate limited loop.""" 13 | 14 | def _busy_wait_until(tend: float): 15 | while tend - time.perf_counter() > 0.0: 16 | pass 17 | 18 | td = 1 / fps 19 | t_start = time.perf_counter() 20 | t_next = t_start + td 21 | rate_failed_emitted = False 22 | while True: 23 | t_cur = time.perf_counter() - t_start 24 | yield t_cur 25 | remain = max(t_next - time.perf_counter(), 0) 26 | if remain > 0.1: 27 | time.sleep(remain) 28 | elif remain > 0.0: 29 | _busy_wait_until(t_next) 30 | elif remain < 0.0 and not rate_failed_emitted: 31 | rate_failed_emitted = True 32 | _logger.warning(f"Too slow at {t_cur}") 33 | t_next += td 34 | 35 | 36 | @dataclasses.dataclass 37 | class Event: 38 | at: float 39 | until: float 40 | name: str 41 | 42 | @staticmethod 43 | def create_random(lambd: float = 20.0, dur: float = 2.0): 44 | event_at = time.time() + np.random.exponential(scale=20) 45 | event_name = datetime.datetime.fromtimestamp(event_at).strftime("%H:%M:%S") 46 | event_until = event_at + 2.0 47 | return Event(event_at, event_until, f"Event at {event_name}") 48 | 49 | 50 | def chessboard_generator( 51 | shape: tuple[int, int], 52 | roll: int, 53 | block_size: int = 100, 54 | fps: Optional[int] = 10000, 55 | noise_std: float = 0.0, 56 | ) -> Iterator[tuple[float, np.ndarray, bool]]: 57 | """Generates rolling chessboard images. 58 | 59 | Returns: 60 | timestamp: timestamp relative to start of generator [sec] 61 | image: rgb24 image 62 | ev: true if an event is currently active, false otherwise 63 | """ 64 | 65 | num_blocks = ( 66 | int(np.ceil(shape[0] / block_size)), 67 | int(np.ceil(shape[1] / block_size)), 68 | ) 69 | check = np.zeros(num_blocks) 70 | check[1::2, ::2] = 1 71 | check[::2, 1::2] = 1 72 | 73 | img = np.expand_dims(np.kron(check, np.ones((block_size, block_size))), -1) 74 | img = np.tile(img, (1, 1, 3)) 75 | img += np.random.randn(*img.shape) * noise_std 76 | img = np.clip(img, 0.0, 1.0).astype(np.uint8) * 255 77 | img = img[: shape[0], : shape[1]] 78 | 79 | ev = Event.create_random(lambd=10, dur=2) 80 | ev_active = False 81 | 82 | total_roll = 0 83 | for ts in rate_limited_loop(fps=fps): 84 | t_cur = time.time() 85 | if t_cur > ev.until: 86 | ev = Event.create_random(lambd=10, dur=2) 87 | img[:block_size, :block_size] = (0, 0, 0) 88 | ev_active = False 89 | elif t_cur > ev.at: 90 | img[:block_size, :block_size] = (0, 255, 255) 91 | ev_active = True 92 | rolled = np.roll(img, total_roll, 1) 93 | yield ts, rolled, ev_active 94 | total_roll += roll 95 | 96 | 97 | def test_chessboard_gen(): 98 | import matplotlib.pyplot as plt 99 | 100 | shape = (200, 320) 101 | fps = 30 102 | roll_over = 5 # roll over in 5 secs 103 | roll = int(np.ceil(shape[1] / (roll_over * fps))) 104 | gen = chessboard_generator(shape, roll=roll, block_size=20, fps=fps) 105 | 106 | fig, ax = plt.subplots() 107 | img_ = ax.imshow(next(gen)[1]) 108 | prev_ev = False 109 | while True: 110 | plt.pause(1e-5) 111 | ts, img, ev = next(gen) 112 | img_.set_data(img) 113 | if not prev_ev and ev: 114 | print("now") 115 | prev_ev = ev 116 | 117 | 118 | if __name__ == "__main__": 119 | test_chessboard_gen() 120 | -------------------------------------------------------------------------------- /hlsstream/stream.py: -------------------------------------------------------------------------------- 1 | from typing import Callable, Any 2 | from pathlib import Path 3 | import ffmpeg 4 | import enum 5 | import numpy as np 6 | import time 7 | import shutil 8 | 9 | 10 | class HLSPresets(enum.Enum): 11 | DEFAULT_CPU = { 12 | "vcodec": "libx264", 13 | "preset": "veryfast", 14 | "video_bitrate": "6M", 15 | "maxrate": "6M", 16 | "bufsize": "6M", 17 | } 18 | DEFAULT_GPU = { 19 | "vcodec": "h264_nvenc", 20 | "preset": "p3", # https://gist.github.com/nico-lab/e1ba48c33bf2c7e1d9ffdd9c1b8d0493 21 | "tune": "ll", 22 | "video_bitrate": "6M", 23 | "maxrate": "6M", 24 | "bufsize": "6M", 25 | } 26 | 27 | 28 | # For preset settings 29 | # https://obsproject.com/blog/streaming-with-x264#:~:text=x264%20has%20several%20CPU%20presets,%2C%20slower%2C%20veryslow%2C%20placebo. 30 | 31 | 32 | class HLSEncoder: 33 | def __init__( 34 | self, 35 | out_path: Path, 36 | shape: tuple[int, int] = (1080, 1920), 37 | input_fps: int = 30, 38 | use_wallclock_pts: bool = False, 39 | preset: HLSPresets = HLSPresets.DEFAULT_CPU, 40 | **hls_kwargs, 41 | ) -> None: 42 | self.out_path = out_path 43 | self.shape = shape 44 | 45 | self.inp_settings = { 46 | "format": "rawvideo", 47 | "pix_fmt": "rgb24", 48 | "s": "{}x{}".format(shape[1], shape[0]), 49 | "r": input_fps, 50 | "use_wallclock_as_timestamps": use_wallclock_pts, 51 | } 52 | self.enc_settings = { 53 | "format": "hls", 54 | "pix_fmt": "yuv420p", 55 | "hls_time": 2, 56 | "hls_list_size": 2 * 60 / 2, # 10 minutes keep 57 | "hls_flags": "delete_segments", # remove outdated segments from disk 58 | "start_number": 0, 59 | **preset.value, 60 | **hls_kwargs, 61 | } 62 | # Compute keyframe interval for most precise segment duration 63 | # Note, -g (GOP) and keyint_min is necessary to get exact duration segments. 64 | # https://sites.google.com/site/linuxencoding/x264-ffmpeg-mapping#:~:text=%2Dg%20(FFmpeg,Recommended%20default%3A%20250 65 | nkey = self.enc_settings["hls_time"] * self.inp_settings["r"] 66 | self.enc_settings["g"] = nkey 67 | self.enc_settings["keyint_min"] = nkey 68 | 69 | self.proc: Callable[[np.ndarray[np.uint8, Any]]] = None 70 | self.time: float = 0.0 71 | 72 | def __enter__(self) -> "HLSEncoder": 73 | self.time = 0.0 74 | self.proc = ( 75 | ffmpeg.input("pipe:", **self.inp_settings) 76 | .drawtext( 77 | start_number=0, 78 | fontsize="(h/10)", 79 | fontfile="etc/roboto.ttf", 80 | x="(w-text_w)/2", 81 | y="h*0.8", 82 | timecode="00:00:00:00", 83 | timecode_rate=self.inp_settings["r"], 84 | fontcolor="white", 85 | escape_text=True, 86 | box="1", 87 | boxcolor="black", 88 | ) 89 | .output(str(self.out_path), **self.enc_settings) 90 | .overwrite_output() 91 | .run_async(pipe_stdin=True) 92 | ) 93 | return self 94 | 95 | def __exit__(self, type, value, traceback): 96 | self.proc.stdin.close() 97 | self.proc = None 98 | 99 | def __call__(self, rgb24: np.ndarray[np.uint8, Any]) -> float: 100 | if self.inp_settings["use_wallclock_as_timestamps"]: 101 | start_time = time.time() # not very precise 102 | else: 103 | start_time = self.time 104 | self.time += 1 / self.inp_settings["r"] 105 | self.proc.stdin.write(rgb24.tobytes()) 106 | return start_time 107 | 108 | 109 | def main(): 110 | from .input import chessboard_generator 111 | from .sync import Cache 112 | from pathlib import Path 113 | 114 | outpath = Path("video").resolve() 115 | shutil.rmtree(str(outpath)) 116 | outpath.mkdir(parents=True, exist_ok=True) 117 | 118 | shape = (180, 320) 119 | fps = 30 120 | roll = int(np.ceil(shape[1] / (30 * fps))) 121 | gen = chessboard_generator(shape, roll, 20, fps=fps) 122 | enc = HLSEncoder( 123 | "video/chessboard.m3u8", 124 | shape=shape, 125 | input_fps=fps, 126 | use_wallclock_pts=False, 127 | preset=HLSPresets.DEFAULT_CPU, 128 | ) 129 | cache = Cache() 130 | 131 | markers = [] 132 | cache.set("markers", markers) 133 | virtual_ts = 0.0 134 | with enc: 135 | ev_prev = False 136 | while True: 137 | ts, img, ev = next(gen) 138 | enc(img) 139 | virtual_ts += 1 / fps 140 | if not ev_prev and ev: 141 | markers.append( 142 | { 143 | "time": virtual_ts, 144 | "text": f"Marker {len(markers)+1}", 145 | } 146 | ) 147 | cache.set("markers", markers) 148 | ev_prev = ev 149 | 150 | 151 | if __name__ == "__main__": 152 | main() 153 | -------------------------------------------------------------------------------- /hlsstream/sync.py: -------------------------------------------------------------------------------- 1 | from multiprocessing.managers import SyncManager 2 | from typing import Any 3 | 4 | SYNC_ADDR = "127.0.0.1" 5 | SYNC_PORT = 5001 6 | SYNC_PWD = b"password" 7 | 8 | 9 | class CacheSyncManager(SyncManager): 10 | ... 11 | 12 | 13 | _syncdict = {} 14 | 15 | 16 | def _get_dict(): 17 | return _syncdict 18 | 19 | 20 | class Cache: 21 | def __init__(self) -> None: 22 | self.manager = CacheSyncManager((SYNC_ADDR, SYNC_PORT), authkey=SYNC_PWD) 23 | self.manager.connect() 24 | CacheSyncManager.register("syncdict") 25 | self.syndict = self.manager.syncdict() 26 | 27 | def set(self, key: str, value: Any): 28 | self.syndict.update([(key, value)]) 29 | 30 | def get(self, key: str, default: Any = None) -> Any: 31 | return self.syndict.get(key, default) 32 | 33 | 34 | if __name__ == "__main__": 35 | 36 | CacheSyncManager.register("syncdict", _get_dict) 37 | manager = CacheSyncManager((SYNC_ADDR, SYNC_PORT), authkey=SYNC_PWD) 38 | manager.get_server().serve_forever() 39 | -------------------------------------------------------------------------------- /requirements.in: -------------------------------------------------------------------------------- 1 | ffmpeg-python 2 | numpy 3 | uvicorn 4 | fastapi 5 | schedule -------------------------------------------------------------------------------- /requirements.txt: -------------------------------------------------------------------------------- 1 | # 2 | # This file is autogenerated by pip-compile with python 3.9 3 | # To update, run: 4 | # 5 | # pip-compile requirements.in 6 | # 7 | anyio==3.5.0 8 | # via starlette 9 | asgiref==3.5.1 10 | # via uvicorn 11 | click==8.1.3 12 | # via uvicorn 13 | colorama==0.4.4 14 | # via click 15 | fastapi==0.76.0 16 | # via -r requirements.in 17 | ffmpeg-python==0.2.0 18 | # via -r requirements.in 19 | future==0.18.2 20 | # via ffmpeg-python 21 | h11==0.13.0 22 | # via uvicorn 23 | idna==3.3 24 | # via anyio 25 | numpy==1.22.3 26 | # via -r requirements.in 27 | pydantic==1.9.0 28 | # via fastapi 29 | schedule==1.1.0 30 | # via -r requirements.in 31 | sniffio==1.2.0 32 | # via anyio 33 | starlette==0.18.0 34 | # via fastapi 35 | typing-extensions==4.2.0 36 | # via 37 | # pydantic 38 | # starlette 39 | uvicorn==0.17.6 40 | # via -r requirements.in 41 | -------------------------------------------------------------------------------- /static/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | HLS Streaming Demo 7 | 8 | 9 | 10 | 11 | 12 | 74 | 75 | 76 | 77 |
78 |
79 |

HLS Streaming with timeline-markers.

80 |

Shown below, is a real-time generated HLS stream of a 81 | rolling checkerboard 82 | pattern. 83 | Ocassionally an event (mint square) is emitted that leads to markers being added 84 | to the table and the timeline. Depending on the HLS configuration you can leave the live edge 85 | and seek backwards in time.

86 |

87 | Christoph Heindl
88 | https://github.com/cheind/python-hls-stream 89 |

90 |
91 | 92 |
93 |
94 | 97 | 98 |
99 |
100 | 101 | 102 | 103 | 104 | 105 | 106 | 107 | 108 |
TimestampText
109 |
110 |
111 | 112 |
113 | 114 | 311 | 312 | --------------------------------------------------------------------------------