Skip to content

Instantly share code, notes, and snippets.

@hisui
Created February 6, 2019 04:07
Show Gist options
  • Save hisui/bbeb765397a7d6fd1208341fe40260d4 to your computer and use it in GitHub Desktop.
Save hisui/bbeb765397a7d6fd1208341fe40260d4 to your computer and use it in GitHub Desktop.
require "open-uri"
require "uri"
playlist_uri = "http://127.0.0.1:9001/broadcasts/1/hls/index.m3u8"
Segment = Struct.new :uri, :duration
Playlist = Struct.new :seq_no, :segments
def parse_m3u8(src, uri = "")
seq_no = src.lines.grep(/^#EXT-X-MEDIA-SEQUENCE:(\d+)/) { $1 }[0].to_i
Playlist.new(seq_no,
src.lines.each_cons(2).flat_map { |tag, seg|
tag !~/^#EXTINF:(\d+),/ ? []: Segment.new(URI.join(uri, seg.chomp), $1.to_f)
}
)
end
def load_playlist(uri)
seq_no = 0
loop {
playlist = open(uri) {|io| parse_m3u8(io.read, uri) }
skip_num = [0, seq_no - playlist.seq_no].max
segments = playlist.segments[skip_num..-1]
segments.each_with_index {|e, i| yield [e, playlist.seq_no + skip_num + i] }
seq_no = playlist.seq_no + playlist.segments.size
sleep [0.1, segments.reduce(0) { |acc, e| acc + e.duration }].max
}
end
load_playlist(playlist_uri) { |seg, seq_no|
hash = `curl -s '#{seg.uri}' | openssl dgst -sha256`.chomp
p [seq_no, hash]
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment