From 57830b1e5bb2fe3c4c05ed06b238e569f2e9b48c Mon Sep 17 00:00:00 2001 From: trueChazza Date: Wed, 20 Mar 2024 15:45:12 +1300 Subject: [PATCH] feat: add segments generate --- lib/hls_playlist_segments.ex | 17 +++++++++++++++++ test/hls_playlist_segments_test.exs | 19 +++++++++++++++++++ 2 files changed, 36 insertions(+) create mode 100644 lib/hls_playlist_segments.ex create mode 100644 test/hls_playlist_segments_test.exs diff --git a/lib/hls_playlist_segments.ex b/lib/hls_playlist_segments.ex new file mode 100644 index 0000000..d21ca2f --- /dev/null +++ b/lib/hls_playlist_segments.ex @@ -0,0 +1,17 @@ +defmodule HlsPlaylist.Segments do + + def generate(duration, segment_length \\ 3) when duration > 0 and segment_length > 0 do + spread_duration(duration, segment_length, []) + end + + defp spread_duration(duration, _segment_length, acc) when duration <= 0 do + Enum.map(acc, fn x -> Float.round((x * 1.0), 2) end) + |> Enum.reverse() + end + + defp spread_duration(duration, segment_length, acc) do + next_duration = min(duration, segment_length) + + spread_duration(duration - next_duration, segment_length, [next_duration | acc]) + end +end diff --git a/test/hls_playlist_segments_test.exs b/test/hls_playlist_segments_test.exs new file mode 100644 index 0000000..9994619 --- /dev/null +++ b/test/hls_playlist_segments_test.exs @@ -0,0 +1,19 @@ +defmodule HlsPlaylist.Segments.Test do + use ExUnit.Case + + test "it should generate" do + assert HlsPlaylist.Segments.generate(32.21, 3) == [ + 3.0, + 3.0, + 3.0, + 3.0, + 3.0, + 3.0, + 3.0, + 3.0, + 3.0, + 3.0, + 2.21 + ] + end +end