diff --git a/lib/hls_playlist.ex b/lib/hls_playlist.ex index 39ebec6..794af83 100644 --- a/lib/hls_playlist.ex +++ b/lib/hls_playlist.ex @@ -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 diff --git a/test/hls_playlist_test.exs b/test/hls_playlist_test.exs index 3affc94..1be31ce 100644 --- a/test/hls_playlist_test.exs +++ b/test/hls_playlist_test.exs @@ -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