Skip to content

Commit

Permalink
refactor: get segment offset from segments
Browse files Browse the repository at this point in the history
  • Loading branch information
trueChazza committed Mar 20, 2024
1 parent cfb5ff1 commit b90b449
Show file tree
Hide file tree
Showing 2 changed files with 15 additions and 45 deletions.
22 changes: 4 additions & 18 deletions lib/hls_playlist.ex
Original file line number Diff line number Diff line change
Expand Up @@ -79,23 +79,9 @@ defmodule HlsPlaylist do
"""
end

def get_segment_offset(playlist, target_segment, current_duration \\ 0.0, total_duration \\ 0.0, index \\ 0) do
case playlist do
[line | rest] ->
case String.match?(line, ~r{^#EXTINF:(\d+\.\d+),}) do
true ->
[_, segment_duration] = Regex.run(~r{^#EXTINF:(\d+\.\d+),}, line, capture: :all)
segment_duration = String.to_float(segment_duration)

if index == target_segment do
{segment_duration, total_duration + current_duration} # Return both the duration of the target segment and total offset duration
else
get_segment_offset(rest, target_segment, current_duration + segment_duration, total_duration, index + 1)
end

false ->
get_segment_offset(rest, target_segment, current_duration, total_duration, index)
end
end
def get_segment_offset(segments, index) when is_list(segments) and is_integer(index) do
value = Enum.at(segments, index)
sum_previous = Enum.sum(Enum.take(segments, index))
{value, sum_previous}
end
end
38 changes: 11 additions & 27 deletions test/hls_playlist_test.exs
Original file line number Diff line number Diff line change
Expand Up @@ -65,33 +65,17 @@ defmodule HlsPlaylistTest do
end

test "get segment offset" do
playlist =
"""
#EXTM3U
#EXT-X-VERSION:3
#EXT-X-ALLOW-CACHE:NO
#EXT-X-TARGETDURATION:4
#EXT-X-MEDIA-SEQUENCE:0
#EXT-X-PLAYLIST-TYPE:VOD
#EXTINF:4.166667,
0
#EXTINF:4.166666,
1
#EXTINF:4.166667,
2
#EXTINF:3.766667,
3
#EXTINF:3.866666,
4
#EXTINF:4.166667,
5
#EXTINF:3.133333,
6
#EXTINF:2.582667,
7
#EXT-X-ENDLIST\
"""
segments = [
4.166667,
4.166666,
4.166667,
3.766667,
3.866666,
4.166667,
3.133333,
2.576667
]

assert {3.766667, 12.5} = HlsPlaylist.get_segment_offset(String.split(playlist), String.to_integer("3"))
assert {3.766667, 12.5} = HlsPlaylist.get_segment_offset(segments, String.to_integer("3"))
end
end

0 comments on commit b90b449

Please sign in to comment.