2019-04-03 15:40:03 +00:00
|
|
|
"""Provide functionality to stream HLS."""
|
2019-03-12 02:57:10 +00:00
|
|
|
from aiohttp import web
|
|
|
|
|
|
|
|
from homeassistant.core import callback
|
|
|
|
|
2021-02-23 02:37:19 +00:00
|
|
|
from .const import FORMAT_CONTENT_TYPE, MAX_SEGMENTS, NUM_PLAYLIST_SEGMENTS
|
|
|
|
from .core import PROVIDERS, HomeAssistant, IdleTimer, StreamOutput, StreamView
|
2021-05-26 08:19:09 +00:00
|
|
|
from .fmp4utils import get_codec_string
|
2019-03-12 02:57:10 +00:00
|
|
|
|
|
|
|
|
|
|
|
@callback
|
|
|
|
def async_setup_hls(hass):
|
|
|
|
"""Set up api endpoints."""
|
|
|
|
hass.http.register_view(HlsPlaylistView())
|
|
|
|
hass.http.register_view(HlsSegmentView())
|
2020-08-11 21:12:41 +00:00
|
|
|
hass.http.register_view(HlsInitView())
|
2020-09-27 20:38:14 +00:00
|
|
|
hass.http.register_view(HlsMasterPlaylistView())
|
|
|
|
return "/api/hls/{}/master_playlist.m3u8"
|
|
|
|
|
|
|
|
|
|
|
|
class HlsMasterPlaylistView(StreamView):
|
|
|
|
"""Stream view used only for Chromecast compatibility."""
|
|
|
|
|
|
|
|
url = r"/api/hls/{token:[a-f0-9]+}/master_playlist.m3u8"
|
|
|
|
name = "api:stream:hls:master_playlist"
|
|
|
|
cors_allowed = True
|
|
|
|
|
|
|
|
@staticmethod
|
|
|
|
def render(track):
|
|
|
|
"""Render M3U8 file."""
|
|
|
|
# Need to calculate max bandwidth as input_container.bit_rate doesn't seem to work
|
2020-10-15 20:37:27 +00:00
|
|
|
# Calculate file size / duration and use a small multiplier to account for variation
|
|
|
|
# hls spec already allows for 25% variation
|
2020-09-27 20:38:14 +00:00
|
|
|
segment = track.get_segment(track.segments[-1])
|
|
|
|
bandwidth = round(
|
2021-05-26 08:19:09 +00:00
|
|
|
(len(segment.init) + len(segment.moof_data)) * 8 / segment.duration * 1.2
|
2020-09-27 20:38:14 +00:00
|
|
|
)
|
2021-05-26 08:19:09 +00:00
|
|
|
codecs = get_codec_string(segment.init)
|
2020-09-27 20:38:14 +00:00
|
|
|
lines = [
|
|
|
|
"#EXTM3U",
|
|
|
|
f'#EXT-X-STREAM-INF:BANDWIDTH={bandwidth},CODECS="{codecs}"',
|
|
|
|
"playlist.m3u8",
|
|
|
|
]
|
|
|
|
return "\n".join(lines) + "\n"
|
|
|
|
|
|
|
|
async def handle(self, request, stream, sequence):
|
|
|
|
"""Return m3u8 playlist."""
|
2021-02-20 14:49:39 +00:00
|
|
|
track = stream.add_provider("hls")
|
|
|
|
stream.start()
|
2020-09-27 20:38:14 +00:00
|
|
|
# Wait for a segment to be ready
|
2021-03-27 09:54:59 +00:00
|
|
|
if not track.segments and not await track.recv():
|
|
|
|
return web.HTTPNotFound()
|
2020-09-27 20:38:14 +00:00
|
|
|
headers = {"Content-Type": FORMAT_CONTENT_TYPE["hls"]}
|
|
|
|
return web.Response(body=self.render(track).encode("utf-8"), headers=headers)
|
2019-03-12 02:57:10 +00:00
|
|
|
|
|
|
|
|
|
|
|
class HlsPlaylistView(StreamView):
|
|
|
|
"""Stream view to serve a M3U8 stream."""
|
|
|
|
|
2019-07-31 19:25:30 +00:00
|
|
|
url = r"/api/hls/{token:[a-f0-9]+}/playlist.m3u8"
|
|
|
|
name = "api:stream:hls:playlist"
|
2019-03-12 02:57:10 +00:00
|
|
|
cors_allowed = True
|
|
|
|
|
2020-09-27 20:38:14 +00:00
|
|
|
@staticmethod
|
|
|
|
def render_preamble(track):
|
|
|
|
"""Render preamble."""
|
|
|
|
return [
|
|
|
|
"#EXT-X-VERSION:7",
|
|
|
|
f"#EXT-X-TARGETDURATION:{track.target_duration}",
|
|
|
|
'#EXT-X-MAP:URI="init.mp4"',
|
|
|
|
]
|
|
|
|
|
|
|
|
@staticmethod
|
|
|
|
def render_playlist(track):
|
|
|
|
"""Render playlist."""
|
2021-05-13 21:26:11 +00:00
|
|
|
segments = list(track.get_segments())[-NUM_PLAYLIST_SEGMENTS:]
|
2020-09-27 20:38:14 +00:00
|
|
|
|
|
|
|
if not segments:
|
|
|
|
return []
|
|
|
|
|
2021-02-18 12:26:02 +00:00
|
|
|
playlist = [
|
2021-04-09 16:58:27 +00:00
|
|
|
f"#EXT-X-MEDIA-SEQUENCE:{segments[0].sequence}",
|
|
|
|
f"#EXT-X-DISCONTINUITY-SEQUENCE:{segments[0].stream_id}",
|
2021-02-18 12:26:02 +00:00
|
|
|
]
|
2020-09-27 20:38:14 +00:00
|
|
|
|
2021-02-18 12:26:02 +00:00
|
|
|
last_stream_id = segments[0].stream_id
|
|
|
|
for segment in segments:
|
|
|
|
if last_stream_id != segment.stream_id:
|
|
|
|
playlist.append("#EXT-X-DISCONTINUITY")
|
2020-09-27 20:38:14 +00:00
|
|
|
playlist.extend(
|
|
|
|
[
|
2021-04-09 16:58:27 +00:00
|
|
|
f"#EXTINF:{float(segment.duration):.04f},",
|
2020-09-27 20:38:14 +00:00
|
|
|
f"./segment/{segment.sequence}.m4s",
|
|
|
|
]
|
|
|
|
)
|
2021-02-18 12:26:02 +00:00
|
|
|
last_stream_id = segment.stream_id
|
2020-09-27 20:38:14 +00:00
|
|
|
|
|
|
|
return playlist
|
|
|
|
|
|
|
|
def render(self, track):
|
|
|
|
"""Render M3U8 file."""
|
|
|
|
lines = ["#EXTM3U"] + self.render_preamble(track) + self.render_playlist(track)
|
|
|
|
return "\n".join(lines) + "\n"
|
|
|
|
|
2019-03-12 02:57:10 +00:00
|
|
|
async def handle(self, request, stream, sequence):
|
|
|
|
"""Return m3u8 playlist."""
|
2021-02-20 14:49:39 +00:00
|
|
|
track = stream.add_provider("hls")
|
|
|
|
stream.start()
|
2019-03-12 02:57:10 +00:00
|
|
|
# Wait for a segment to be ready
|
2021-03-27 09:54:59 +00:00
|
|
|
if not track.segments and not await track.recv():
|
|
|
|
return web.HTTPNotFound()
|
2019-07-31 19:25:30 +00:00
|
|
|
headers = {"Content-Type": FORMAT_CONTENT_TYPE["hls"]}
|
2020-09-27 20:38:14 +00:00
|
|
|
return web.Response(body=self.render(track).encode("utf-8"), headers=headers)
|
2019-03-12 02:57:10 +00:00
|
|
|
|
|
|
|
|
2020-08-11 21:12:41 +00:00
|
|
|
class HlsInitView(StreamView):
|
|
|
|
"""Stream view to serve HLS init.mp4."""
|
|
|
|
|
|
|
|
url = r"/api/hls/{token:[a-f0-9]+}/init.mp4"
|
|
|
|
name = "api:stream:hls:init"
|
|
|
|
cors_allowed = True
|
|
|
|
|
|
|
|
async def handle(self, request, stream, sequence):
|
|
|
|
"""Return init.mp4."""
|
2021-02-20 14:49:39 +00:00
|
|
|
track = stream.add_provider("hls")
|
2021-05-13 21:26:11 +00:00
|
|
|
segments = track.get_segments()
|
2020-08-11 21:12:41 +00:00
|
|
|
if not segments:
|
|
|
|
return web.HTTPNotFound()
|
|
|
|
headers = {"Content-Type": "video/mp4"}
|
2021-05-26 08:19:09 +00:00
|
|
|
return web.Response(body=segments[0].init, headers=headers)
|
2020-08-11 21:12:41 +00:00
|
|
|
|
|
|
|
|
2019-03-12 02:57:10 +00:00
|
|
|
class HlsSegmentView(StreamView):
|
2020-08-11 21:12:41 +00:00
|
|
|
"""Stream view to serve a HLS fmp4 segment."""
|
2019-03-12 02:57:10 +00:00
|
|
|
|
2020-08-11 21:12:41 +00:00
|
|
|
url = r"/api/hls/{token:[a-f0-9]+}/segment/{sequence:\d+}.m4s"
|
2019-07-31 19:25:30 +00:00
|
|
|
name = "api:stream:hls:segment"
|
2019-03-12 02:57:10 +00:00
|
|
|
cors_allowed = True
|
|
|
|
|
|
|
|
async def handle(self, request, stream, sequence):
|
2020-08-11 21:12:41 +00:00
|
|
|
"""Return fmp4 segment."""
|
2021-02-20 14:49:39 +00:00
|
|
|
track = stream.add_provider("hls")
|
2019-03-12 02:57:10 +00:00
|
|
|
segment = track.get_segment(int(sequence))
|
|
|
|
if not segment:
|
|
|
|
return web.HTTPNotFound()
|
2020-08-11 21:12:41 +00:00
|
|
|
headers = {"Content-Type": "video/iso.segment"}
|
|
|
|
return web.Response(
|
2021-05-26 08:19:09 +00:00
|
|
|
body=segment.moof_data,
|
2020-08-27 11:56:20 +00:00
|
|
|
headers=headers,
|
2020-08-11 21:12:41 +00:00
|
|
|
)
|
2019-03-12 02:57:10 +00:00
|
|
|
|
|
|
|
|
2021-02-20 14:49:39 +00:00
|
|
|
@PROVIDERS.register("hls")
|
2019-03-12 02:57:10 +00:00
|
|
|
class HlsStreamOutput(StreamOutput):
|
|
|
|
"""Represents HLS Output formats."""
|
|
|
|
|
2021-02-23 02:37:19 +00:00
|
|
|
def __init__(self, hass: HomeAssistant, idle_timer: IdleTimer) -> None:
|
|
|
|
"""Initialize recorder output."""
|
|
|
|
super().__init__(hass, idle_timer, deque_maxlen=MAX_SEGMENTS)
|
|
|
|
|
2021-02-20 14:49:39 +00:00
|
|
|
@property
|
|
|
|
def name(self) -> str:
|
|
|
|
"""Return provider name."""
|
|
|
|
return "hls"
|