Skip to content

Instantly share code, notes, and snippets.

@marklit
Last active June 3, 2023 15:40
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save marklit/458904e26d4d5eb54e9104fe5a56adbd to your computer and use it in GitHub Desktop.
Save marklit/458904e26d4d5eb54e9104fe5a56adbd to your computer and use it in GitHub Desktop.
Video Stream Generator
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
'''
Please see https://tech.marksblogg.com/streaming-video-hls.html for more details on this script.
MIT License
Copyright (c) 2023 Mark Litwintschik
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
'''
import json
from glob import glob
from os import chdir, getcwd
from os.path import splitext
from pathlib import Path
from shutil import move
from tempfile import TemporaryDirectory
from urllib.parse import quote
from rich.progress import Progress, track
from shpyx import run as execute
import typer
app = typer.Typer(rich_markup_mode='rich')
def get_length(filename: str, ffprobe: str):
cmd = '%(ffprobe)s ' \
'-v error ' \
'-hide_banner ' \
'-print_format json ' \
'-show_streams ' \
'"%(filename)s"'
return float(json.loads(execute(cmd % {'filename': filename,
'ffprobe': ffprobe}).stdout)
['streams']
[0]
.get('duration', 0.0))
remove_ext = lambda filename: splitext(filename)[0]
def build_thumbnail(filename: str,
ffmpeg: str,
fps: int,
height: int,
n_seconds: int,
secs_per_clip: int,
qscale: int,
compression_level: int):
filename = remove_ext(filename)
cmd = '%(ffmpeg)s ' \
'-loglevel error ' \
'-hide_banner ' \
'-y '\
'-i "%(filename)s.mp4" ' \
'-vf "fps=%(fps)d,' \
'scale=-1:%(height)d:flags=lanczos,' \
'select=\'lt(mod(t,%(n_seconds)d),%(secs_per_clip)d)\',' \
'setpts=N/FRAME_RATE/TB" ' \
'-loop 0 ' \
'-qscale %(qscale)d ' \
'-compression_level %(compression_level)d ' \
'"%(filename)s.webp"'
if not Path(filename + '.webp').is_file():
execute(cmd % {'filename': filename,
'ffmpeg': ffmpeg,
'fps': fps,
'height': height,
'n_seconds': n_seconds,
'secs_per_clip': secs_per_clip,
'qscale': qscale,
'compression_level': compression_level})
def ffmpeg_convert(filename: str,
ffmpeg: str,
mp42hls: str,
rate: int,
bufsize: int):
cmd = '%(ffmpeg)s ' \
'-i "%(filename)s" ' \
'-loglevel error ' \
'-hide_banner ' \
'-y ' \
'-c:v libx264 ' \
'-preset ultrafast ' \
'-b:v %(rate)dk ' \
'-maxrate %(rate)dk ' \
'-bufsize %(bufsize)dk ' \
'-vf scale=-1:720 ' \
'out.mp4'
cmd2 = '%s out.mp4 --output-single-file' % mp42hls
start_folder = getcwd()
with TemporaryDirectory() as folder:
chdir(folder)
execute(cmd % {'filename': start_folder + '/' + filename,
'ffmpeg': ffmpeg,
'rate': rate,
'bufsize': bufsize})
execute(cmd2)
filename = remove_ext(filename)
iframes_m3u8 = open('iframes.m3u8', 'r')\
.read()\
.replace('stream.ts', '%s.ts' % filename)
stream_m3u8 = open('stream.m3u8', 'r')\
.read()\
.replace('stream.ts', '%s.ts' % filename)
chdir(start_folder)
move("%s/stream.ts" % folder, "./%s.ts" % filename)
open('%s.iframes.m3u8' % filename, 'w').write(iframes_m3u8)
open('%s.stream.m3u8' % filename, 'w').write(stream_m3u8)
def generate_index():
# Generate an index.html listing all .m3u8 files
# and their .webp thumbnails.
vid_html = '''
<video controls
preload="auto"
video
poster="%(filename)s.webp"
data-setup='{"fluid":true,
"controls": true,
"autoplay": false,
"preload": "auto"}'
width="100%%">
<source src="%(filename)s.stream.m3u8"
type="application/x-mpegURL">
</video>
'''
open('index.html', 'w')\
.write('<hr/>'.join([vid_html % {'filename': quote(remove_ext(x))}
for x in sorted(glob('*.ts'))]))
alt_bin = {'rich_help_panel': 'Alternative Binaries'}
vid_qual = {'rich_help_panel': 'Video Quality'}
thumb_set = {'rich_help_panel': 'Thumbnail Settings'}
job_track = {'rich_help_panel': 'Job Tracking'}
@app.command()
def build(ffmpeg: str = typer.Option('ffmpeg', **alt_bin),
ffprobe: str = typer.Option('ffprobe', **alt_bin),
mp42hls: str = typer.Option('mp42hls', **alt_bin),
rate: int = typer.Option(4000, **vid_qual),
bufsize: int = typer.Option(8000, **vid_qual),
thumb_fps: int = typer.Option(10, **thumb_set),
thumb_height: int = typer.Option(360, **thumb_set),
thumb_n_seconds: int = typer.Option(145, **thumb_set),
thumb_secs_per_clip: int = typer.Option(1, **thumb_set),
thumb_qscale: int = typer.Option(50, **thumb_set),
thumb_compression_level: int = typer.Option(3, **thumb_set)):
# Find all MP4 files in folder without a corresponding .ts file.
# This will skip videos already generated.
workload = set([remove_ext(x)
for x in glob('*.mp4')]) - \
set([remove_ext(x)
for x in glob('*.ts')])
workload = set([x + '.mp4' for x in workload])
workload2 = {}
# Get length of videos.
for filename in track(workload,
description='Fetching video lengths...'):
workload2[filename] = get_length(filename, ffprobe)
total_duration = sum(workload2.values())
# Generate .ts and .m3u8 files starting with the shortest videos first
with Progress() as progress:
task = progress.add_task('Converting videos to HLS...',
total=total_duration)
for filename, duration in sorted(workload2.items(),
key=lambda x: x[1]):
build_thumbnail(filename=filename,
ffmpeg=ffmpeg,
fps=thumb_fps,
height=thumb_height,
n_seconds=thumb_n_seconds,
secs_per_clip=thumb_secs_per_clip,
qscale=thumb_qscale,
compression_level=thumb_compression_level)
ffmpeg_convert(filename, ffmpeg, mp42hls, rate, bufsize)
generate_index()
progress.update(task, advance=duration)
if __name__ == "__main__":
app()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment