Livestreams locally

One of the more popular formats for web livestreaming (unidirectional/broadcast video) is HLS. This is the streaming format used by video services such as Twitch, Facebook Live and Twitter’s Periscope.

You can find URLs to the streams anytime your browser downloads an `x-mpeg-url` media time.

The x-mpeg-url file is a simple text format that only holds references to the media data.

A tool like ffmpeg can download these urls, resolve the media links and save them locally.

ffmpeg -i "https://.../playlist.m3u8" -c copy full_stream.mkv

This is usually okay for local playback, archiving in case the video is ever removed or expires, but if taken directly from a livestream, usually has extra content before and after the main event.

ffmpeg to the rescue again.

#!/bin/bash
INFILE="full_stream.mkv"
OUTFILE="saved_video.mkv"

# Find the start and end times by playing the video and taking a note of the timestamps
# This is in HH:MM:SS.ss format
START="00:20:30.0"
END="02:10:50.43"

ffmpeg -ss "$START" -to "$END" -i "$INFILE" -c copy -map 0 "$OUTFILE"

 

Note that here the order of arguments is important.

-ss (seek to this position to start) and -to (read up to here) need to be given before the -i (input file). -c copy (don’t reencode) and -map 0 (copy all input streams to the output stream) need to come after the input. The output files (or urls) are specified last.