init home-assistant

This commit is contained in:
2026-11-19 15:15:32 -05:00
parent 2e81d9d300
commit feec6ef9fb
19230 changed files with 3335526 additions and 0 deletions

View File

@@ -0,0 +1 @@
"""The tests for stream platforms."""

View File

@@ -0,0 +1,177 @@
"""Collection of test helpers."""
from fractions import Fraction
import functools
from functools import partial
import io
import av
import numpy as np
from homeassistant.components.camera import DynamicStreamSettings
from homeassistant.components.stream.core import Orientation, Segment
from homeassistant.components.stream.fmp4utils import (
TRANSFORM_MATRIX_TOP,
XYW_ROW,
find_box,
)
from homeassistant.util import dt as dt_util
FAKE_TIME = dt_util.utcnow()
# Segment with defaults filled in for use in tests
DefaultSegment = partial(
Segment,
init=None,
stream_id=0,
start_time=FAKE_TIME,
_stream_outputs=[],
)
AUDIO_SAMPLE_RATE = 8000
def stream_teardown():
"""Perform test teardown."""
frame_image_data.cache_clear()
def generate_audio_frame(pcm_mulaw=False):
"""Generate a blank audio frame."""
if pcm_mulaw:
audio_frame = av.AudioFrame(format="s16", layout="mono", samples=1)
audio_bytes = b"\x00\x00"
else:
audio_frame = av.AudioFrame(format="dbl", layout="mono", samples=1024)
audio_bytes = b"\x00\x00\x00\x00\x00\x00\x00\x00" * 1024
audio_frame.planes[0].update(audio_bytes)
audio_frame.sample_rate = AUDIO_SAMPLE_RATE
audio_frame.time_base = Fraction(1, AUDIO_SAMPLE_RATE)
return audio_frame
@functools.lru_cache(maxsize=1024)
def frame_image_data(frame_i, total_frames):
"""Generate image content for a frame of a video."""
img = np.empty((480, 320, 3))
img[:, :, 0] = 0.5 + 0.5 * np.sin(2 * np.pi * (0 / 3 + frame_i / total_frames))
img[:, :, 1] = 0.5 + 0.5 * np.sin(2 * np.pi * (1 / 3 + frame_i / total_frames))
img[:, :, 2] = 0.5 + 0.5 * np.sin(2 * np.pi * (2 / 3 + frame_i / total_frames))
img = np.round(255 * img).astype(np.uint8)
return np.clip(img, 0, 255)
def generate_video(encoder, container_format, duration):
"""Generate a test video.
See: http://docs.mikeboers.com/pyav/develop/cookbook/numpy.html
"""
fps = 24
total_frames = duration * fps
output = io.BytesIO()
output.name = "test.mov" if container_format == "mov" else "test.mp4"
container = av.open(output, mode="w", format=container_format)
stream = container.add_stream(encoder, rate=fps)
stream.width = 480
stream.height = 320
stream.pix_fmt = "yuv420p"
stream.options.update({"g": str(fps), "keyint_min": str(fps)})
for frame_i in range(total_frames):
img = frame_image_data(frame_i, total_frames)
frame = av.VideoFrame.from_ndarray(img, format="rgb24")
for packet in stream.encode(frame):
container.mux(packet)
# Flush stream
for packet in stream.encode():
container.mux(packet)
# Close the file
container.close()
output.seek(0)
return output
def generate_h264_video(container_format="mp4", duration=5):
"""Generate a test video with libx264."""
return generate_video("libx264", container_format, duration)
def generate_h265_video(container_format="mp4", duration=5):
"""Generate a test video with libx265."""
return generate_video("libx265", container_format, duration)
def remux_with_audio(source, container_format, audio_codec):
"""Remux an existing source with new audio."""
av_source = av.open(source, mode="r")
output = io.BytesIO()
output.name = "test.mov" if container_format == "mov" else "test.mp4"
container = av.open(output, mode="w", format=container_format)
container.add_stream(template=av_source.streams.video[0])
a_packet = None
last_a_dts = -1
if audio_codec is not None:
if audio_codec == "empty": # empty we add a stream but don't mux any audio
astream = container.add_stream("aac", AUDIO_SAMPLE_RATE)
else:
astream = container.add_stream(audio_codec, AUDIO_SAMPLE_RATE)
# Need to do it multiple times for some reason
while not a_packet:
a_packets = astream.encode(
generate_audio_frame(pcm_mulaw=audio_codec == "pcm_mulaw")
)
if a_packets:
a_packet = a_packets[0]
# open original source and iterate through video packets
for packet in av_source.demux(video=0):
if not packet.dts:
continue
container.mux(packet)
if a_packet is not None:
a_packet.pts = int(packet.dts * packet.time_base / a_packet.time_base)
while (
a_packet.pts * a_packet.time_base
< (packet.dts + packet.duration) * packet.time_base
):
a_packet.dts = a_packet.pts
if (
a_packet.dts > last_a_dts
): # avoid writing same dts twice in case of rounding
container.mux(a_packet)
last_a_dts = a_packet.dts
a_packet.pts += a_packet.duration
# Close the file
container.close()
output.seek(0)
return output
def assert_mp4_has_transform_matrix(mp4: bytes, orientation: Orientation):
"""Assert that the mp4 (or init) has the proper transformation matrix."""
# Find moov
moov_location = next(find_box(mp4, b"moov"))
mvhd_location = next(find_box(mp4, b"trak", moov_location))
tkhd_location = next(find_box(mp4, b"tkhd", mvhd_location))
tkhd_length = int.from_bytes(
mp4[tkhd_location : tkhd_location + 4], byteorder="big"
)
assert (
mp4[tkhd_location + tkhd_length - 44 : tkhd_location + tkhd_length - 8]
== TRANSFORM_MATRIX_TOP[orientation] + XYW_ROW
)
def dynamic_stream_settings():
"""Create new dynamic stream settings."""
return DynamicStreamSettings()

View File

@@ -0,0 +1,197 @@
"""Test fixtures for the stream component.
The tests encode stream (as an h264 video), then load the stream and verify
that it is decoded properly. The background worker thread responsible for
decoding will decode the stream as fast as possible, and when completed
clears all output buffers. This can be a problem for the test that wishes
to retrieve and verify decoded segments. If the worker finishes first, there is
nothing for the test to verify. The solution is the WorkerSync class that
allows the tests to pause the worker thread before finalizing the stream
so that it can inspect the output.
"""
from __future__ import annotations
import asyncio
from collections.abc import Generator
import logging
import threading
from typing import Any
from unittest.mock import Mock, patch
from aiohttp import web
import pytest
from homeassistant.components.stream.core import StreamOutput
from homeassistant.components.stream.worker import StreamState
from .common import generate_h264_video, stream_teardown
TEST_TIMEOUT = 7.0 # Lower than 9s home assistant timeout
class WorkerSync:
"""Test fixture that intercepts stream worker calls to StreamOutput."""
def __init__(self) -> None:
"""Initialize WorkerSync."""
self._event = None
self._original = StreamState.discontinuity
def pause(self):
"""Pause the worker before it finalizes the stream."""
self._event = threading.Event()
def resume(self):
"""Allow the worker thread to finalize the stream."""
logging.debug("waking blocked worker")
self._event.set()
def blocking_discontinuity(self, stream_state: StreamState):
"""Intercept call to pause stream worker."""
# Worker is ending the stream, which clears all output buffers.
# Block the worker thread until the test has a chance to verify
# the segments under test.
logging.debug("blocking worker")
if self._event:
self._event.wait()
# Forward to actual implementation
self._original(stream_state)
@pytest.fixture
def stream_worker_sync() -> Generator[WorkerSync]:
"""Patch StreamOutput to allow test to synchronize worker stream end."""
sync = WorkerSync()
with patch(
"homeassistant.components.stream.worker.StreamState.discontinuity",
side_effect=sync.blocking_discontinuity,
autospec=True,
):
yield sync
class HLSSync:
"""Test fixture that intercepts stream worker calls to StreamOutput."""
def __init__(self) -> None:
"""Initialize HLSSync."""
self._request_event = asyncio.Event()
self._original_recv = StreamOutput.recv
self._original_part_recv = StreamOutput.part_recv
self._original_bad_request = web.HTTPBadRequest
self._original_not_found = web.HTTPNotFound
self._original_response = web.Response
self._num_requests = 0
self._num_recvs = 0
self._num_finished = 0
def on_resp():
self._num_finished += 1
self.check_requests_ready()
class SyncResponse(web.Response):
def __init__(self, *args: Any, **kwargs: Any) -> None:
super().__init__(*args, **kwargs)
on_resp()
self.response = SyncResponse
def reset_request_pool(self, num_requests: int, reset_finished=True):
"""Use to reset the request counter between segments."""
self._num_recvs = 0
if reset_finished:
self._num_finished = 0
self._num_requests = num_requests
async def wait_for_handler(self):
"""Set up HLSSync to block calls to put until requests are set up."""
if not self.check_requests_ready():
await self._request_event.wait()
self.reset_request_pool(num_requests=self._num_requests, reset_finished=False)
def check_requests_ready(self):
"""Unblock the pending put call if the requests are all finished or blocking."""
if self._num_recvs + self._num_finished == self._num_requests:
self._request_event.set()
self._request_event.clear()
return True
return False
def bad_request(self):
"""Intercept the HTTPBadRequest call so we know when the web handler is finished."""
self._num_finished += 1
self.check_requests_ready()
return self._original_bad_request()
def not_found(self):
"""Intercept the HTTPNotFound call so we know when the web handler is finished."""
self._num_finished += 1
self.check_requests_ready()
return self._original_not_found()
async def recv(self, output: StreamOutput, **kw):
"""Intercept the recv call so we know when the response is blocking on recv."""
self._num_recvs += 1
self.check_requests_ready()
return await self._original_recv(output)
async def part_recv(self, output: StreamOutput, **kw):
"""Intercept the recv call so we know when the response is blocking on recv."""
self._num_recvs += 1
self.check_requests_ready()
return await self._original_part_recv(output)
@pytest.fixture
def hls_sync():
"""Patch HLSOutput to allow test to synchronize playlist requests and responses."""
sync = HLSSync()
with (
patch(
"homeassistant.components.stream.core.StreamOutput.recv",
side_effect=sync.recv,
autospec=True,
),
patch(
"homeassistant.components.stream.core.StreamOutput.part_recv",
side_effect=sync.part_recv,
autospec=True,
),
patch(
"homeassistant.components.stream.hls.web.HTTPBadRequest",
side_effect=sync.bad_request,
),
patch(
"homeassistant.components.stream.hls.web.HTTPNotFound",
side_effect=sync.not_found,
),
patch(
"homeassistant.components.stream.hls.web.Response",
new=sync.response,
),
):
yield sync
@pytest.fixture(autouse=True)
def should_retry() -> Generator[Mock]:
"""Fixture to disable stream worker retries in tests by default."""
with patch(
"homeassistant.components.stream._should_retry", return_value=False
) as mock_should_retry:
yield mock_should_retry
@pytest.fixture(scope="package")
def h264_video():
"""Generate a video, shared across tests."""
return generate_h264_video()
@pytest.fixture(scope="package", autouse=True)
def fixture_teardown():
"""Destroy package level test state."""
yield
stream_teardown()

View File

@@ -0,0 +1,581 @@
"""The tests for hls streams."""
from datetime import timedelta
from http import HTTPStatus
from unittest.mock import patch
from urllib.parse import urlparse
import av
import pytest
from homeassistant.components.stream import Stream, create_stream
from homeassistant.components.stream.const import (
EXT_X_START_LL_HLS,
EXT_X_START_NON_LL_HLS,
HLS_PROVIDER,
MAX_SEGMENTS,
NUM_PLAYLIST_SEGMENTS,
)
from homeassistant.components.stream.core import Orientation, Part
from homeassistant.core import HomeAssistant
from homeassistant.setup import async_setup_component
import homeassistant.util.dt as dt_util
from .common import (
FAKE_TIME,
DefaultSegment as Segment,
assert_mp4_has_transform_matrix,
dynamic_stream_settings,
)
from tests.common import async_fire_time_changed
from tests.typing import ClientSessionGenerator
STREAM_SOURCE = "some-stream-source"
INIT_BYTES = b"\x00\x00\x00\x08moov"
FAKE_PAYLOAD = b"fake-payload"
SEGMENT_DURATION = 10
TEST_TIMEOUT = 5.0 # Lower than 9s home assistant timeout
MAX_ABORT_SEGMENTS = 20 # Abort test to avoid looping forever
HLS_CONFIG = {
"stream": {
"ll_hls": False,
}
}
@pytest.fixture
async def setup_component(hass: HomeAssistant) -> None:
"""Test fixture to setup the stream component."""
await async_setup_component(hass, "stream", HLS_CONFIG)
class HlsClient:
"""Test fixture for fetching the hls stream."""
def __init__(self, http_client, parsed_url) -> None:
"""Initialize HlsClient."""
self.http_client = http_client
self.parsed_url = parsed_url
async def get(self, path=None, headers=None):
"""Fetch the hls stream for the specified path."""
url = self.parsed_url.path
if path:
# Strip off the master playlist suffix and replace with path
url = "/".join(self.parsed_url.path.split("/")[:-1]) + path
return await self.http_client.get(url, headers=headers)
@pytest.fixture
def hls_stream(hass: HomeAssistant, hass_client: ClientSessionGenerator):
"""Create test fixture for creating an HLS client for a stream."""
async def create_client_for_stream(stream):
http_client = await hass_client()
parsed_url = urlparse(stream.endpoint_url(HLS_PROVIDER))
return HlsClient(http_client, parsed_url)
return create_client_for_stream
def make_segment(segment, discontinuity=False):
"""Create a playlist response for a segment."""
response = ["#EXT-X-DISCONTINUITY"] if discontinuity else []
response.extend(
[
"#EXT-X-PROGRAM-DATE-TIME:"
+ FAKE_TIME.strftime("%Y-%m-%dT%H:%M:%S.%f")[:-3]
+ "Z",
f"#EXTINF:{SEGMENT_DURATION:.3f},",
f"./segment/{segment}.m4s",
]
)
return "\n".join(response)
def make_playlist(
sequence,
discontinuity_sequence=0,
segments=None,
hint=None,
segment_duration=None,
part_target_duration=None,
):
"""Create a an hls playlist response for tests to assert on."""
if not segment_duration:
segment_duration = SEGMENT_DURATION
response = [
"#EXTM3U",
"#EXT-X-VERSION:6",
"#EXT-X-INDEPENDENT-SEGMENTS",
'#EXT-X-MAP:URI="init.mp4"',
f"#EXT-X-TARGETDURATION:{segment_duration}",
f"#EXT-X-MEDIA-SEQUENCE:{sequence}",
f"#EXT-X-DISCONTINUITY-SEQUENCE:{discontinuity_sequence}",
]
if hint:
response.extend(
[
f"#EXT-X-PART-INF:PART-TARGET={part_target_duration:.3f}",
f"#EXT-X-SERVER-CONTROL:CAN-BLOCK-RELOAD=YES,PART-HOLD-BACK={2*part_target_duration:.3f}",
f"#EXT-X-START:TIME-OFFSET=-{EXT_X_START_LL_HLS*part_target_duration:.3f},PRECISE=YES",
]
)
else:
response.append(
f"#EXT-X-START:TIME-OFFSET=-{EXT_X_START_NON_LL_HLS*segment_duration:.3f},PRECISE=YES",
)
if segments:
response.extend(segments)
if hint:
response.append(hint)
response.append("")
return "\n".join(response)
async def test_hls_stream(
hass: HomeAssistant, setup_component, hls_stream, stream_worker_sync, h264_video
) -> None:
"""Test hls stream.
Purposefully not mocking anything here to test full
integration with the stream component.
"""
stream_worker_sync.pause()
# Setup demo HLS track
stream = create_stream(hass, h264_video, {}, dynamic_stream_settings())
# Request stream
stream.add_provider(HLS_PROVIDER)
await stream.start()
hls_client = await hls_stream(stream)
# Fetch master playlist
master_playlist_response = await hls_client.get()
assert master_playlist_response.status == HTTPStatus.OK
# Fetch init
master_playlist = await master_playlist_response.text()
init_response = await hls_client.get("/init.mp4")
assert init_response.status == HTTPStatus.OK
# Fetch playlist
playlist_url = "/" + master_playlist.splitlines()[-1]
playlist_response = await hls_client.get(playlist_url)
assert playlist_response.status == HTTPStatus.OK
# Fetch segment
playlist = await playlist_response.text()
segment_url = "/" + [line for line in playlist.splitlines() if line][-1]
segment_response = await hls_client.get(segment_url)
assert segment_response.status == HTTPStatus.OK
stream_worker_sync.resume()
# Stop stream, if it hasn't quit already
await stream.stop()
# Ensure playlist not accessible after stream ends
fail_response = await hls_client.get()
assert fail_response.status == HTTPStatus.NOT_FOUND
assert stream.get_diagnostics() == {
"container_format": "mov,mp4,m4a,3gp,3g2,mj2",
"keepalive": False,
"orientation": Orientation.NO_TRANSFORM,
"start_worker": 1,
"video_codec": "h264",
"worker_error": 1,
}
async def test_stream_timeout(
hass: HomeAssistant,
hass_client: ClientSessionGenerator,
setup_component,
stream_worker_sync,
h264_video,
) -> None:
"""Test hls stream timeout."""
stream_worker_sync.pause()
# Setup demo HLS track
stream = create_stream(hass, h264_video, {}, dynamic_stream_settings())
available_states = []
def update_callback() -> None:
nonlocal available_states
available_states.append(stream.available)
stream.set_update_callback(update_callback)
# Request stream
stream.add_provider(HLS_PROVIDER)
await stream.start()
url = stream.endpoint_url(HLS_PROVIDER)
http_client = await hass_client()
# Fetch playlist
parsed_url = urlparse(url)
playlist_response = await http_client.get(parsed_url.path)
assert playlist_response.status == HTTPStatus.OK
# Wait a minute
future = dt_util.utcnow() + timedelta(minutes=1)
async_fire_time_changed(hass, future)
await hass.async_block_till_done()
# Fetch again to reset timer
playlist_response = await http_client.get(parsed_url.path)
assert playlist_response.status == HTTPStatus.OK
stream_worker_sync.resume()
# Wait 5 minutes
future = dt_util.utcnow() + timedelta(minutes=5)
async_fire_time_changed(hass, future)
await hass.async_block_till_done()
# Ensure playlist not accessible
fail_response = await http_client.get(parsed_url.path)
assert fail_response.status == HTTPStatus.NOT_FOUND
# Streams only marked as failure when keepalive is true
assert available_states == [True]
async def test_stream_timeout_after_stop(
hass: HomeAssistant,
hass_client: ClientSessionGenerator,
setup_component,
stream_worker_sync,
h264_video,
) -> None:
"""Test hls stream timeout after the stream has been stopped already."""
stream_worker_sync.pause()
# Setup demo HLS track
stream = create_stream(hass, h264_video, {}, dynamic_stream_settings())
# Request stream
stream.add_provider(HLS_PROVIDER)
await stream.start()
stream_worker_sync.resume()
await stream.stop()
# Wait 5 minutes and fire callback. Stream should already have been
# stopped so this is a no-op.
future = dt_util.utcnow() + timedelta(minutes=5)
async_fire_time_changed(hass, future)
await hass.async_block_till_done()
async def test_stream_retries(
hass: HomeAssistant, setup_component, should_retry
) -> None:
"""Test hls stream is retried on failure."""
# Setup demo HLS track
source = "test_stream_keepalive_source"
stream = create_stream(hass, source, {}, dynamic_stream_settings())
track = stream.add_provider(HLS_PROVIDER)
track.num_segments = 2
available_states = []
def update_callback() -> None:
nonlocal available_states
available_states.append(stream.available)
stream.set_update_callback(update_callback)
open_future1 = hass.loop.create_future()
open_future2 = hass.loop.create_future()
futures = [open_future2, open_future1]
original_set_state = Stream._set_state
def set_state_wrapper(self, state: bool) -> None:
if state is False:
should_retry.return_value = False # Thread should exit and be joinable.
original_set_state(self, state)
def av_open_side_effect(*args, **kwargs):
hass.loop.call_soon_threadsafe(futures.pop().set_result, None)
# pylint: disable-next=c-extension-no-member
raise av.error.InvalidDataError(-2, "error")
with (
patch("av.open") as av_open,
patch("homeassistant.components.stream.Stream._set_state", set_state_wrapper),
patch("homeassistant.components.stream.STREAM_RESTART_INCREMENT", 0),
):
av_open.side_effect = av_open_side_effect
# Request stream. Enable retries which are disabled by default in tests.
should_retry.return_value = True
await stream.start()
await open_future1
await open_future2
await hass.async_add_executor_job(stream._thread.join)
stream._thread = None
assert av_open.call_count == 2
await hass.async_block_till_done()
# Stop stream, if it hasn't quit already
await stream.stop()
# Stream marked initially available, then marked as failed, then marked available
# before the final failure that exits the stream.
assert available_states == [True, False, True]
async def test_hls_playlist_view_no_output(
hass: HomeAssistant, setup_component, hls_stream
) -> None:
"""Test rendering the hls playlist with no output segments."""
stream = create_stream(hass, STREAM_SOURCE, {}, dynamic_stream_settings())
stream.add_provider(HLS_PROVIDER)
hls_client = await hls_stream(stream)
# Fetch playlist
resp = await hls_client.get("/playlist.m3u8")
assert resp.status == HTTPStatus.NOT_FOUND
async def test_hls_playlist_view(
hass: HomeAssistant, setup_component, hls_stream, stream_worker_sync
) -> None:
"""Test rendering the hls playlist with 1 and 2 output segments."""
stream = create_stream(hass, STREAM_SOURCE, {}, dynamic_stream_settings())
stream_worker_sync.pause()
hls = stream.add_provider(HLS_PROVIDER)
for i in range(2):
segment = Segment(sequence=i, duration=SEGMENT_DURATION)
hls.put(segment)
await hass.async_block_till_done()
hls_client = await hls_stream(stream)
resp = await hls_client.get("/playlist.m3u8")
assert resp.status == HTTPStatus.OK
assert await resp.text() == make_playlist(
sequence=0, segments=[make_segment(0), make_segment(1)]
)
segment = Segment(sequence=2, duration=SEGMENT_DURATION)
hls.put(segment)
await hass.async_block_till_done()
resp = await hls_client.get("/playlist.m3u8")
assert resp.status == HTTPStatus.OK
assert await resp.text() == make_playlist(
sequence=0, segments=[make_segment(0), make_segment(1), make_segment(2)]
)
stream_worker_sync.resume()
await stream.stop()
async def test_hls_max_segments(
hass: HomeAssistant, setup_component, hls_stream, stream_worker_sync
) -> None:
"""Test rendering the hls playlist with more segments than the segment deque can hold."""
stream = create_stream(hass, STREAM_SOURCE, {}, dynamic_stream_settings())
stream_worker_sync.pause()
hls = stream.add_provider(HLS_PROVIDER)
hls_client = await hls_stream(stream)
# Produce enough segments to overfill the output buffer by one
for sequence in range(MAX_SEGMENTS + 1):
segment = Segment(sequence=sequence, duration=SEGMENT_DURATION)
hls.put(segment)
await hass.async_block_till_done()
resp = await hls_client.get("/playlist.m3u8")
assert resp.status == HTTPStatus.OK
# Only NUM_PLAYLIST_SEGMENTS are returned in the playlist.
start = MAX_SEGMENTS + 1 - NUM_PLAYLIST_SEGMENTS
segments = [make_segment(sequence) for sequence in range(start, MAX_SEGMENTS + 1)]
assert await resp.text() == make_playlist(sequence=start, segments=segments)
# Fetch the actual segments with a fake byte payload
for segment in hls.get_segments():
segment.init = INIT_BYTES
segment.parts = [
Part(
duration=SEGMENT_DURATION,
has_keyframe=True,
data=FAKE_PAYLOAD,
)
]
# The segment that fell off the buffer is not accessible
with patch.object(hls.stream_settings, "hls_part_timeout", 0.1):
segment_response = await hls_client.get("/segment/0.m4s")
assert segment_response.status == HTTPStatus.NOT_FOUND
# However all segments in the buffer are accessible, even those that were not in the playlist.
for sequence in range(1, MAX_SEGMENTS + 1):
segment_response = await hls_client.get(f"/segment/{sequence}.m4s")
assert segment_response.status == HTTPStatus.OK
stream_worker_sync.resume()
await stream.stop()
async def test_hls_playlist_view_discontinuity(
hass: HomeAssistant, setup_component, hls_stream, stream_worker_sync
) -> None:
"""Test a discontinuity across segments in the stream with 3 segments."""
stream = create_stream(hass, STREAM_SOURCE, {}, dynamic_stream_settings())
stream_worker_sync.pause()
hls = stream.add_provider(HLS_PROVIDER)
segment = Segment(sequence=0, stream_id=0, duration=SEGMENT_DURATION)
hls.put(segment)
segment = Segment(sequence=1, stream_id=0, duration=SEGMENT_DURATION)
hls.put(segment)
segment = Segment(
sequence=2,
stream_id=1,
duration=SEGMENT_DURATION,
)
hls.put(segment)
await hass.async_block_till_done()
hls_client = await hls_stream(stream)
resp = await hls_client.get("/playlist.m3u8")
assert resp.status == HTTPStatus.OK
assert await resp.text() == make_playlist(
sequence=0,
segments=[
make_segment(0),
make_segment(1),
make_segment(2, discontinuity=True),
],
)
stream_worker_sync.resume()
await stream.stop()
async def test_hls_max_segments_discontinuity(
hass: HomeAssistant, setup_component, hls_stream, stream_worker_sync
) -> None:
"""Test a discontinuity with more segments than the segment deque can hold."""
stream = create_stream(hass, STREAM_SOURCE, {}, dynamic_stream_settings())
stream_worker_sync.pause()
hls = stream.add_provider(HLS_PROVIDER)
hls_client = await hls_stream(stream)
segment = Segment(sequence=0, stream_id=0, duration=SEGMENT_DURATION)
hls.put(segment)
# Produce enough segments to overfill the output buffer by one
for sequence in range(MAX_SEGMENTS + 1):
segment = Segment(
sequence=sequence,
stream_id=1,
duration=SEGMENT_DURATION,
)
hls.put(segment)
await hass.async_block_till_done()
resp = await hls_client.get("/playlist.m3u8")
assert resp.status == HTTPStatus.OK
# Only NUM_PLAYLIST_SEGMENTS are returned in the playlist causing the
# EXT-X-DISCONTINUITY tag to be omitted and EXT-X-DISCONTINUITY-SEQUENCE
# returned instead.
start = MAX_SEGMENTS + 1 - NUM_PLAYLIST_SEGMENTS
segments = [make_segment(sequence) for sequence in range(start, MAX_SEGMENTS + 1)]
assert await resp.text() == make_playlist(
sequence=start,
discontinuity_sequence=1,
segments=segments,
)
stream_worker_sync.resume()
await stream.stop()
async def test_remove_incomplete_segment_on_exit(
hass: HomeAssistant, setup_component, stream_worker_sync
) -> None:
"""Test that the incomplete segment gets removed when the worker thread quits."""
stream = create_stream(hass, STREAM_SOURCE, {}, dynamic_stream_settings())
stream_worker_sync.pause()
await stream.start()
hls = stream.add_provider(HLS_PROVIDER)
segment = Segment(sequence=0, stream_id=0, duration=SEGMENT_DURATION)
hls.put(segment)
segment = Segment(sequence=1, stream_id=0, duration=SEGMENT_DURATION)
hls.put(segment)
segment = Segment(sequence=2, stream_id=0, duration=0)
hls.put(segment)
await hass.async_block_till_done()
segments = hls._segments
assert len(segments) == 3
assert not segments[-1].complete
stream_worker_sync.resume()
with patch("homeassistant.components.stream.Stream.remove_provider"):
# Patch remove_provider so the deque is not cleared
stream._thread_quit.set()
stream._thread.join()
stream._thread = None
await hass.async_block_till_done()
assert segments[-1].complete
assert len(segments) == 2
await stream.stop()
async def test_hls_stream_rotate(
hass: HomeAssistant, setup_component, hls_stream, stream_worker_sync, h264_video
) -> None:
"""Test hls stream with rotation applied.
Purposefully not mocking anything here to test full
integration with the stream component.
"""
stream_worker_sync.pause()
# Setup demo HLS track
stream = create_stream(hass, h264_video, {}, dynamic_stream_settings())
# Request stream
stream.add_provider(HLS_PROVIDER)
await stream.start()
hls_client = await hls_stream(stream)
# Fetch master playlist
master_playlist_response = await hls_client.get()
assert master_playlist_response.status == HTTPStatus.OK
# Fetch rotated init
stream.dynamic_stream_settings.orientation = Orientation.ROTATE_LEFT
init_response = await hls_client.get("/init.mp4")
assert init_response.status == HTTPStatus.OK
init = await init_response.read()
stream_worker_sync.resume()
assert_mp4_has_transform_matrix(init, stream.dynamic_stream_settings.orientation)
# Stop stream, if it hasn't quit already
await stream.stop()

View File

@@ -0,0 +1,133 @@
"""Test stream init."""
import logging
from unittest.mock import MagicMock, patch
import av
import pytest
from homeassistant.components.stream import (
CONF_PREFER_TCP,
SOURCE_TIMEOUT,
StreamClientError,
StreamOpenClientError,
__name__ as stream_name,
_async_try_open_stream,
async_check_stream_client_error,
)
from homeassistant.const import EVENT_LOGGING_CHANGED
from homeassistant.core import HomeAssistant
from homeassistant.setup import async_setup_component
async def test_log_levels(
hass: HomeAssistant, caplog: pytest.LogCaptureFixture
) -> None:
"""Test that the worker logs the url without username and password."""
await async_setup_component(hass, "stream", {"stream": {}})
# These namespaces should only pass log messages when the stream logger
# is at logging.DEBUG or below
namespaces_to_toggle = (
"mp4",
"h264",
"hevc",
"rtsp",
"tcp",
"tls",
"mpegts",
"NULL",
)
logging.getLogger(stream_name).setLevel(logging.INFO)
hass.bus.async_fire(EVENT_LOGGING_CHANGED)
await hass.async_block_till_done()
# Since logging is at INFO, these should not pass
for namespace in namespaces_to_toggle:
av.logging.log(av.logging.ERROR, namespace, "SHOULD NOT PASS")
logging.getLogger(stream_name).setLevel(logging.DEBUG)
hass.bus.async_fire(EVENT_LOGGING_CHANGED)
await hass.async_block_till_done()
# Since logging is now at DEBUG, these should now pass
for namespace in namespaces_to_toggle:
av.logging.log(av.logging.ERROR, namespace, "SHOULD PASS")
# Even though logging is at DEBUG, these should not pass
av.logging.log(av.logging.WARNING, "mp4", "SHOULD NOT PASS")
av.logging.log(av.logging.WARNING, "swscaler", "SHOULD NOT PASS")
assert "SHOULD PASS" in caplog.text
assert "SHOULD NOT PASS" not in caplog.text
async def test_check_open_stream_params(hass: HomeAssistant) -> None:
"""Test check open stream params."""
container_mock = MagicMock()
source = "rtsp://foobar"
with patch("av.open", return_value=container_mock) as open_mock:
await async_check_stream_client_error(hass, source)
options = {
"rtsp_flags": CONF_PREFER_TCP,
"timeout": str(SOURCE_TIMEOUT),
}
open_mock.assert_called_once_with(source, options=options, timeout=5)
container_mock.close.assert_called_once()
container_mock.reset_mock()
with patch("av.open", return_value=container_mock) as open_mock:
await async_check_stream_client_error(hass, source, {"foo": "bar"})
options = {
"rtsp_flags": CONF_PREFER_TCP,
"timeout": str(SOURCE_TIMEOUT),
"foo": "bar",
}
open_mock.assert_called_once_with(source, options=options, timeout=5)
container_mock.close.assert_called_once()
@pytest.mark.parametrize(
("error", "enum_result"),
[
pytest.param(
av.HTTPBadRequestError(400, ""),
StreamClientError.BadRequest,
id="BadRequest",
),
pytest.param(
av.HTTPUnauthorizedError(401, ""),
StreamClientError.Unauthorized,
id="Unauthorized",
),
pytest.param(
av.HTTPForbiddenError(403, ""), StreamClientError.Forbidden, id="Forbidden"
),
pytest.param(
av.HTTPNotFoundError(404, ""), StreamClientError.NotFound, id="NotFound"
),
pytest.param(
av.HTTPOtherClientError(408, ""), StreamClientError.Other, id="Other"
),
],
)
async def test_try_open_stream_error(
hass: HomeAssistant, error: av.HTTPClientError, enum_result: StreamClientError
) -> None:
"""Test trying to open a stream."""
oc_error: StreamOpenClientError | None = None
with patch("av.open", side_effect=error):
try:
await _async_try_open_stream(hass, "rtsp://foobar")
except StreamOpenClientError as ex:
oc_error = ex
assert oc_error
assert oc_error.stream_client_error is enum_result

View File

@@ -0,0 +1,718 @@
"""The tests for hls streams."""
import asyncio
from collections import deque
from http import HTTPStatus
import itertools
import math
import re
from urllib.parse import urlparse
from aiohttp import web
from dateutil import parser
import pytest
from homeassistant.components.stream import create_stream
from homeassistant.components.stream.const import (
ATTR_SETTINGS,
CONF_LL_HLS,
CONF_PART_DURATION,
CONF_SEGMENT_DURATION,
DOMAIN,
HLS_PROVIDER,
)
from homeassistant.components.stream.core import Part
from homeassistant.core import HomeAssistant
from homeassistant.setup import async_setup_component
from .common import (
FAKE_TIME,
DefaultSegment as Segment,
dynamic_stream_settings,
generate_h264_video,
)
from .test_hls import STREAM_SOURCE, HlsClient, make_playlist
from tests.typing import ClientSessionGenerator
SEGMENT_DURATION = 6
TEST_PART_DURATION = 0.75
NUM_PART_SEGMENTS = int(-(-SEGMENT_DURATION // TEST_PART_DURATION))
PART_INDEPENDENT_PERIOD = int(1 / TEST_PART_DURATION) or 1
BYTERANGE_LENGTH = 1
INIT_BYTES = b"\x00\x00\x00\x08moov"
SEQUENCE_BYTES = bytearray(range(NUM_PART_SEGMENTS * BYTERANGE_LENGTH))
ALT_SEQUENCE_BYTES = bytearray(range(20, 20 + NUM_PART_SEGMENTS * BYTERANGE_LENGTH))
VERY_LARGE_LAST_BYTE_POS = 9007199254740991
@pytest.fixture
def hls_stream(hass: HomeAssistant, hass_client: ClientSessionGenerator):
"""Create test fixture for creating an HLS client for a stream."""
async def create_client_for_stream(stream):
stream.ll_hls = True
http_client = await hass_client()
parsed_url = urlparse(stream.endpoint_url(HLS_PROVIDER))
return HlsClient(http_client, parsed_url)
return create_client_for_stream
def create_segment(sequence):
"""Create an empty segment."""
segment = Segment(sequence=sequence)
segment.init = INIT_BYTES
return segment
def complete_segment(segment):
"""Completes a segment by setting its duration."""
segment.duration = sum(part.duration for part in segment.parts)
def create_parts(source):
"""Create parts from a source."""
independent_cycle = itertools.cycle(
[True] + [False] * (PART_INDEPENDENT_PERIOD - 1)
)
return [
Part(
duration=TEST_PART_DURATION,
has_keyframe=next(independent_cycle),
data=bytes(source[i * BYTERANGE_LENGTH : (i + 1) * BYTERANGE_LENGTH]),
)
for i in range(NUM_PART_SEGMENTS)
]
def http_range_from_part(part):
"""Return dummy byterange (length, start) given part number."""
return BYTERANGE_LENGTH, part * BYTERANGE_LENGTH
def make_segment_with_parts(
segment, num_parts, independent_period, discontinuity=False
):
"""Create a playlist response for a segment including part segments."""
response = []
if discontinuity:
response.append("#EXT-X-DISCONTINUITY")
response.extend(
f'#EXT-X-PART:DURATION={TEST_PART_DURATION:.3f},URI="./segment/{segment}.{i}.m4s"{",INDEPENDENT=YES" if i%independent_period==0 else ""}'
for i in range(num_parts)
)
response.extend(
[
"#EXT-X-PROGRAM-DATE-TIME:"
+ FAKE_TIME.strftime("%Y-%m-%dT%H:%M:%S.%f")[:-3]
+ "Z",
f"#EXTINF:{math.ceil(SEGMENT_DURATION/TEST_PART_DURATION)*TEST_PART_DURATION:.3f},",
f"./segment/{segment}.m4s",
]
)
return "\n".join(response)
def make_hint(segment, part):
"""Create a playlist response for the preload hint."""
return f'#EXT-X-PRELOAD-HINT:TYPE=PART,URI="./segment/{segment}.{part}.m4s"'
async def test_ll_hls_stream(
hass: HomeAssistant, hls_stream, stream_worker_sync
) -> None:
"""Test hls stream.
Purposefully not mocking anything here to test full
integration with the stream component.
"""
await async_setup_component(
hass,
"stream",
{
"stream": {
CONF_LL_HLS: True,
CONF_SEGMENT_DURATION: SEGMENT_DURATION,
# Use a slight mismatch in PART_DURATION to mimic
# misalignments with source DTSs
CONF_PART_DURATION: TEST_PART_DURATION - 0.01,
}
},
)
stream_worker_sync.pause()
num_playlist_segments = 3
# Setup demo HLS track
source = generate_h264_video(duration=num_playlist_segments * SEGMENT_DURATION + 2)
stream = create_stream(hass, source, {}, dynamic_stream_settings())
# Request stream
stream.add_provider(HLS_PROVIDER)
await stream.start()
hls_client = await hls_stream(stream)
# Fetch playlist
master_playlist_response = await hls_client.get()
assert master_playlist_response.status == HTTPStatus.OK
# Fetch init
master_playlist = await master_playlist_response.text()
init_response = await hls_client.get("/init.mp4")
assert init_response.status == HTTPStatus.OK
# Fetch playlist
playlist_url = "/" + master_playlist.splitlines()[-1]
playlist_response = await hls_client.get(
playlist_url + f"?_HLS_msn={num_playlist_segments-1}"
)
assert playlist_response.status == HTTPStatus.OK
# Fetch segments
playlist = await playlist_response.text()
segment_re = re.compile(r"^(?P<segment_url>./segment/\d+\.m4s)")
for line in playlist.splitlines():
match = segment_re.match(line)
if match:
segment_url = "/" + match.group("segment_url")
segment_response = await hls_client.get(segment_url)
assert segment_response.status == HTTPStatus.OK
def check_part_is_moof_mdat(data: bytes):
if len(data) < 8 or data[4:8] != b"moof":
return False
moof_length = int.from_bytes(data[0:4], byteorder="big")
if (
len(data) < moof_length + 8
or data[moof_length + 4 : moof_length + 8] != b"mdat"
):
return False
mdat_length = int.from_bytes(
data[moof_length : moof_length + 4], byteorder="big"
)
if mdat_length + moof_length != len(data):
return False
return True
# Parse playlist
part_re = re.compile(
r'#EXT-X-PART:DURATION=(?P<part_duration>[0-9]{1,}.[0-9]{3,}),URI="(?P<part_url>.+?)"(,INDEPENDENT=YES)?'
)
datetime_re = re.compile(r"#EXT-X-PROGRAM-DATE-TIME:(?P<datetime>.+)")
inf_re = re.compile(r"#EXTINF:(?P<segment_duration>[0-9]{1,}.[0-9]{3,}),")
# keep track of which tests were done (indexed by re)
tested = {regex: False for regex in (part_re, datetime_re, inf_re)}
# keep track of times and durations along playlist for checking consistency
part_durations = []
segment_duration = 0
datetimes = deque()
for line in playlist.splitlines():
match = part_re.match(line)
if match:
# Fetch all completed part segments
part_durations.append(float(match.group("part_duration")))
part_segment_url = "/" + match.group("part_url")
part_segment_response = await hls_client.get(
part_segment_url,
)
assert part_segment_response.status == HTTPStatus.OK
assert check_part_is_moof_mdat(await part_segment_response.read())
tested[part_re] = True
continue
match = datetime_re.match(line)
if match:
datetimes.append(parser.parse(match.group("datetime")))
# Check that segment durations are consistent with PROGRAM-DATE-TIME
if len(datetimes) > 1:
datetime_duration = (
datetimes[-1] - datetimes.popleft()
).total_seconds()
if segment_duration:
assert math.isclose(
datetime_duration, segment_duration, rel_tol=1e-3
)
tested[datetime_re] = True
continue
match = inf_re.match(line)
if match:
segment_duration = float(match.group("segment_duration"))
# Check that segment durations are consistent with part durations
if len(part_durations) > 1:
assert math.isclose(sum(part_durations), segment_duration, rel_tol=1e-3)
tested[inf_re] = True
part_durations.clear()
# make sure all playlist tests were performed
assert all(tested.values())
stream_worker_sync.resume()
# Stop stream, if it hasn't quit already
await stream.stop()
# Ensure playlist not accessible after stream ends
fail_response = await hls_client.get()
assert fail_response.status == HTTPStatus.NOT_FOUND
async def test_ll_hls_playlist_view(
hass: HomeAssistant, hls_stream, stream_worker_sync
) -> None:
"""Test rendering the hls playlist with 1 and 2 output segments."""
await async_setup_component(
hass,
"stream",
{
"stream": {
CONF_LL_HLS: True,
CONF_SEGMENT_DURATION: SEGMENT_DURATION,
CONF_PART_DURATION: TEST_PART_DURATION,
}
},
)
stream = create_stream(hass, STREAM_SOURCE, {}, dynamic_stream_settings())
stream_worker_sync.pause()
hls = stream.add_provider(HLS_PROVIDER)
# Add 2 complete segments to output
for sequence in range(2):
segment = create_segment(sequence=sequence)
hls.put(segment)
for part in create_parts(SEQUENCE_BYTES):
segment.async_add_part(part, 0)
hls.part_put()
complete_segment(segment)
await hass.async_block_till_done()
hls_client = await hls_stream(stream)
resp = await hls_client.get("/playlist.m3u8")
assert resp.status == HTTPStatus.OK
assert await resp.text() == make_playlist(
sequence=0,
segments=[
make_segment_with_parts(i, len(segment.parts), PART_INDEPENDENT_PERIOD)
for i in range(2)
],
hint=make_hint(2, 0),
segment_duration=SEGMENT_DURATION,
part_target_duration=hls.stream_settings.part_target_duration,
)
# add one more segment
segment = create_segment(sequence=2)
hls.put(segment)
for part in create_parts(SEQUENCE_BYTES):
segment.async_add_part(part, 0)
hls.part_put()
complete_segment(segment)
await hass.async_block_till_done()
resp = await hls_client.get("/playlist.m3u8")
assert resp.status == HTTPStatus.OK
assert await resp.text() == make_playlist(
sequence=0,
segments=[
make_segment_with_parts(i, len(segment.parts), PART_INDEPENDENT_PERIOD)
for i in range(3)
],
hint=make_hint(3, 0),
segment_duration=SEGMENT_DURATION,
part_target_duration=hls.stream_settings.part_target_duration,
)
stream_worker_sync.resume()
await stream.stop()
async def test_ll_hls_msn(
hass: HomeAssistant, hls_stream, stream_worker_sync, hls_sync
) -> None:
"""Test that requests using _HLS_msn get held and returned or rejected."""
await async_setup_component(
hass,
"stream",
{
"stream": {
CONF_LL_HLS: True,
CONF_SEGMENT_DURATION: SEGMENT_DURATION,
CONF_PART_DURATION: TEST_PART_DURATION,
}
},
)
stream = create_stream(hass, STREAM_SOURCE, {}, dynamic_stream_settings())
stream_worker_sync.pause()
hls = stream.add_provider(HLS_PROVIDER)
hls_client = await hls_stream(stream)
# Create 4 requests for sequences 0 through 3
# 0 and 1 should hold then go through and 2 and 3 should fail immediately.
hls_sync.reset_request_pool(4)
msn_requests = asyncio.gather(
*(hls_client.get(f"/playlist.m3u8?_HLS_msn={i}") for i in range(4))
)
for sequence in range(3):
await hls_sync.wait_for_handler()
segment = Segment(sequence=sequence, duration=SEGMENT_DURATION)
hls.put(segment)
msn_responses = await msn_requests
assert msn_responses[0].status == HTTPStatus.OK
assert msn_responses[1].status == HTTPStatus.OK
assert msn_responses[2].status == HTTPStatus.BAD_REQUEST
assert msn_responses[3].status == HTTPStatus.BAD_REQUEST
# Sequence number is now 2. Create six more requests for sequences 0 through 5.
# Calls for msn 0 through 4 should work, 5 should fail.
hls_sync.reset_request_pool(6)
msn_requests = asyncio.gather(
*(hls_client.get(f"/playlist.m3u8?_HLS_msn={i}") for i in range(6))
)
for sequence in range(3, 6):
await hls_sync.wait_for_handler()
segment = Segment(sequence=sequence, duration=SEGMENT_DURATION)
hls.put(segment)
msn_responses = await msn_requests
assert msn_responses[0].status == HTTPStatus.OK
assert msn_responses[1].status == HTTPStatus.OK
assert msn_responses[2].status == HTTPStatus.OK
assert msn_responses[3].status == HTTPStatus.OK
assert msn_responses[4].status == HTTPStatus.OK
assert msn_responses[5].status == HTTPStatus.BAD_REQUEST
stream_worker_sync.resume()
async def test_ll_hls_playlist_bad_msn_part(
hass: HomeAssistant, hls_stream, stream_worker_sync
) -> None:
"""Test some playlist requests with invalid _HLS_msn/_HLS_part."""
async def _handler_bad_request(request):
raise web.HTTPBadRequest
await async_setup_component(
hass,
"stream",
{
"stream": {
CONF_LL_HLS: True,
CONF_SEGMENT_DURATION: SEGMENT_DURATION,
CONF_PART_DURATION: TEST_PART_DURATION,
}
},
)
stream = create_stream(hass, STREAM_SOURCE, {}, dynamic_stream_settings())
stream_worker_sync.pause()
hls = stream.add_provider(HLS_PROVIDER)
hls_client = await hls_stream(stream)
# All GET calls to '/.../playlist.m3u8' should raise a HTTPBadRequest exception
hls_client.http_client.app.router._frozen = False
parsed_url = urlparse(stream.endpoint_url(HLS_PROVIDER))
url = "/".join(parsed_url.path.split("/")[:-1]) + "/playlist.m3u8"
hls_client.http_client.app.router.add_route("GET", url, _handler_bad_request)
# If the Playlist URI contains an _HLS_part directive but no _HLS_msn
# directive, the Server MUST return Bad Request, such as HTTP 400.
assert (
await hls_client.get("/playlist.m3u8?_HLS_part=1")
).status == HTTPStatus.BAD_REQUEST
# Seed hls with 1 complete segment and 1 in process segment
segment = create_segment(sequence=0)
hls.put(segment)
for part in create_parts(SEQUENCE_BYTES):
segment.async_add_part(part, 0)
hls.part_put()
complete_segment(segment)
segment = create_segment(sequence=1)
hls.put(segment)
remaining_parts = create_parts(SEQUENCE_BYTES)
num_completed_parts = len(remaining_parts) // 2
for part in remaining_parts[:num_completed_parts]:
segment.async_add_part(part, 0)
# If the _HLS_msn is greater than the Media Sequence Number of the last
# Media Segment in the current Playlist plus two, or if the _HLS_part
# exceeds the last Partial Segment in the current Playlist by the
# Advance Part Limit, then the server SHOULD immediately return Bad
# Request, such as HTTP 400. The Advance Part Limit is three divided
# by the Part Target Duration if the Part Target Duration is less than
# one second, or three otherwise.
# Current sequence number is 1 and part number is num_completed_parts-1
# The following two tests should fail immediately:
# - request with a _HLS_msn of 4
# - request with a _HLS_msn of 1 and a _HLS_part of num_completed_parts-1+advance_part_limit
assert (
await hls_client.get("/playlist.m3u8?_HLS_msn=4")
).status == HTTPStatus.BAD_REQUEST
assert (
await hls_client.get(
f"/playlist.m3u8?_HLS_msn=1&_HLS_part={num_completed_parts-1+hass.data[DOMAIN][ATTR_SETTINGS].hls_advance_part_limit}"
)
).status == HTTPStatus.BAD_REQUEST
stream_worker_sync.resume()
async def test_ll_hls_playlist_rollover_part(
hass: HomeAssistant, hls_stream, stream_worker_sync, hls_sync
) -> None:
"""Test playlist request rollover."""
await async_setup_component(
hass,
"stream",
{
"stream": {
CONF_LL_HLS: True,
CONF_SEGMENT_DURATION: SEGMENT_DURATION,
CONF_PART_DURATION: TEST_PART_DURATION,
}
},
)
stream = create_stream(hass, STREAM_SOURCE, {}, dynamic_stream_settings())
stream_worker_sync.pause()
hls = stream.add_provider(HLS_PROVIDER)
hls_client = await hls_stream(stream)
# Seed hls with 1 complete segment and 1 in process segment
for sequence in range(2):
segment = create_segment(sequence=sequence)
hls.put(segment)
for part in create_parts(SEQUENCE_BYTES):
segment.async_add_part(part, 0)
hls.part_put()
complete_segment(segment)
await hass.async_block_till_done()
hls_sync.reset_request_pool(4)
segment = hls.get_segment(1)
# the first request corresponds to the last part of segment 1
# the remaining requests correspond to part 0 of segment 2
requests = asyncio.gather(
*(
[
hls_client.get(
f"/playlist.m3u8?_HLS_msn=1&_HLS_part={len(segment.parts)-1}"
),
hls_client.get(
f"/playlist.m3u8?_HLS_msn=1&_HLS_part={len(segment.parts)}"
),
hls_client.get(
f"/playlist.m3u8?_HLS_msn=1&_HLS_part={len(segment.parts)+1}"
),
hls_client.get("/playlist.m3u8?_HLS_msn=2&_HLS_part=0"),
]
)
)
await hls_sync.wait_for_handler()
segment = create_segment(sequence=2)
hls.put(segment)
await hass.async_block_till_done()
remaining_parts = create_parts(SEQUENCE_BYTES)
segment.async_add_part(remaining_parts.pop(0), 0)
hls.part_put()
await hls_sync.wait_for_handler()
different_response, *same_responses = await requests
assert different_response.status == HTTPStatus.OK
assert all(response.status == HTTPStatus.OK for response in same_responses)
different_playlist = await different_response.read()
same_playlists = [await response.read() for response in same_responses]
assert different_playlist != same_playlists[0]
assert all(playlist == same_playlists[0] for playlist in same_playlists[1:])
stream_worker_sync.resume()
async def test_ll_hls_playlist_msn_part(
hass: HomeAssistant, hls_stream, stream_worker_sync, hls_sync
) -> None:
"""Test that requests using _HLS_msn and _HLS_part get held and returned."""
await async_setup_component(
hass,
"stream",
{
"stream": {
CONF_LL_HLS: True,
CONF_SEGMENT_DURATION: SEGMENT_DURATION,
CONF_PART_DURATION: TEST_PART_DURATION,
}
},
)
stream = create_stream(hass, STREAM_SOURCE, {}, dynamic_stream_settings())
stream_worker_sync.pause()
hls = stream.add_provider(HLS_PROVIDER)
hls_client = await hls_stream(stream)
# Seed hls with 1 complete segment and 1 in process segment
segment = create_segment(sequence=0)
hls.put(segment)
for part in create_parts(SEQUENCE_BYTES):
segment.async_add_part(part, 0)
hls.part_put()
complete_segment(segment)
segment = create_segment(sequence=1)
hls.put(segment)
remaining_parts = create_parts(SEQUENCE_BYTES)
num_completed_parts = len(remaining_parts) // 2
for part in remaining_parts[:num_completed_parts]:
segment.async_add_part(part, 0)
del remaining_parts[:num_completed_parts]
# Make requests for all the part segments up to n+ADVANCE_PART_LIMIT
hls_sync.reset_request_pool(
num_completed_parts
+ int(-(-hass.data[DOMAIN][ATTR_SETTINGS].hls_advance_part_limit // 1))
)
msn_requests = asyncio.gather(
*(
hls_client.get(f"/playlist.m3u8?_HLS_msn=1&_HLS_part={i}")
for i in range(
num_completed_parts
+ int(-(-hass.data[DOMAIN][ATTR_SETTINGS].hls_advance_part_limit // 1))
)
)
)
while remaining_parts:
await hls_sync.wait_for_handler()
segment.async_add_part(remaining_parts.pop(0), 0)
hls.part_put()
msn_responses = await msn_requests
# All the responses should succeed except the last one which fails
assert all(response.status == HTTPStatus.OK for response in msn_responses[:-1])
assert msn_responses[-1].status == HTTPStatus.BAD_REQUEST
stream_worker_sync.resume()
async def test_get_part_segments(
hass: HomeAssistant, hls_stream, stream_worker_sync, hls_sync
) -> None:
"""Test requests for part segments and hinted parts."""
await async_setup_component(
hass,
"stream",
{
"stream": {
CONF_LL_HLS: True,
CONF_SEGMENT_DURATION: SEGMENT_DURATION,
CONF_PART_DURATION: TEST_PART_DURATION,
}
},
)
stream = create_stream(hass, STREAM_SOURCE, {}, dynamic_stream_settings())
stream_worker_sync.pause()
hls = stream.add_provider(HLS_PROVIDER)
hls_client = await hls_stream(stream)
# Seed hls with 1 complete segment and 1 in process segment
segment = create_segment(sequence=0)
hls.put(segment)
for part in create_parts(SEQUENCE_BYTES):
segment.async_add_part(part, 0)
hls.part_put()
complete_segment(segment)
segment = create_segment(sequence=1)
hls.put(segment)
remaining_parts = create_parts(SEQUENCE_BYTES)
num_completed_parts = len(remaining_parts) // 2
for _ in range(num_completed_parts):
segment.async_add_part(remaining_parts.pop(0), 0)
# Make requests for all the existing part segments
# These should succeed
requests = asyncio.gather(
*(
hls_client.get(f"/segment/1.{part}.m4s")
for part in range(num_completed_parts)
)
)
responses = await requests
assert all(response.status == HTTPStatus.OK for response in responses)
assert all(
[
await responses[i].read() == segment.parts[i].data
for i in range(len(responses))
]
)
# Request for next segment which has not yet been hinted (we will only hint
# for this segment after segment 1 is complete).
# This should fail, but it will hold for one more part_put before failing.
hls_sync.reset_request_pool(1)
request = asyncio.create_task(hls_client.get("/segment/2.0.m4s"))
await hls_sync.wait_for_handler()
hls.part_put()
response = await request
assert response.status == HTTPStatus.NOT_FOUND
# Put the remaining parts and complete the segment
while remaining_parts:
await hls_sync.wait_for_handler()
# Put one more part segment
segment.async_add_part(remaining_parts.pop(0), 0)
hls.part_put()
complete_segment(segment)
# Now the hint should have moved to segment 2
# The request for segment 2 which failed before should work now
hls_sync.reset_request_pool(1)
request = asyncio.create_task(hls_client.get("/segment/2.0.m4s"))
# Put an entire segment and its parts.
segment = create_segment(sequence=2)
hls.put(segment)
remaining_parts = create_parts(ALT_SEQUENCE_BYTES)
for part in remaining_parts:
await hls_sync.wait_for_handler()
segment.async_add_part(part, 0)
hls.part_put()
complete_segment(segment)
# Check the response
response = await request
assert response.status == HTTPStatus.OK
assert (
await response.read()
== ALT_SEQUENCE_BYTES[: len(hls.get_segment(2).parts[0].data)]
)
stream_worker_sync.resume()

View File

@@ -0,0 +1,309 @@
"""The tests for recording streams."""
import asyncio
from datetime import timedelta
from io import BytesIO
import os
from pathlib import Path
from unittest.mock import patch
import av
import pytest
from homeassistant.components.stream import Stream, create_stream
from homeassistant.components.stream.const import (
HLS_PROVIDER,
OUTPUT_IDLE_TIMEOUT,
RECORDER_PROVIDER,
)
from homeassistant.components.stream.core import Orientation, Part
from homeassistant.components.stream.fmp4utils import find_box
from homeassistant.core import HomeAssistant
from homeassistant.exceptions import HomeAssistantError
from homeassistant.setup import async_setup_component
import homeassistant.util.dt as dt_util
from .common import (
DefaultSegment as Segment,
assert_mp4_has_transform_matrix,
dynamic_stream_settings,
generate_h264_video,
remux_with_audio,
)
from tests.common import async_fire_time_changed
@pytest.fixture(autouse=True)
async def stream_component(hass: HomeAssistant) -> None:
"""Set up the component before each test."""
await async_setup_component(hass, "stream", {"stream": {}})
@pytest.fixture
def filename(tmp_path: Path) -> str:
"""Use this filename for the tests."""
return str(tmp_path / "test.mp4")
async def test_record_stream(hass: HomeAssistant, filename, h264_video) -> None:
"""Test record stream."""
worker_finished = asyncio.Event()
class MockStream(Stream):
"""Mock Stream so we can patch remove_provider."""
async def remove_provider(self, provider):
"""Add a finished event to Stream.remove_provider."""
await Stream.remove_provider(self, provider)
worker_finished.set()
with patch("homeassistant.components.stream.Stream", wraps=MockStream):
stream = create_stream(hass, h264_video, {}, dynamic_stream_settings())
with patch.object(hass.config, "is_allowed_path", return_value=True):
make_recording = hass.async_create_task(stream.async_record(filename))
# In general usage the recorder will only include what has already been
# processed by the worker. To guarantee we have some output for the test,
# wait until the worker has finished before firing
await worker_finished.wait()
# Fire the IdleTimer
future = dt_util.utcnow() + timedelta(seconds=30)
async_fire_time_changed(hass, future)
await make_recording
# Assert
assert os.path.exists(filename)
async def test_record_lookback(hass: HomeAssistant, filename, h264_video) -> None:
"""Exercise record with lookback."""
stream = create_stream(hass, h264_video, {}, dynamic_stream_settings())
# Start an HLS feed to enable lookback
stream.add_provider(HLS_PROVIDER)
await stream.start()
with patch.object(hass.config, "is_allowed_path", return_value=True):
await stream.async_record(filename, lookback=4)
# This test does not need recorder cleanup since it is not fully exercised
await stream.stop()
async def test_record_path_not_allowed(hass: HomeAssistant, h264_video) -> None:
"""Test where the output path is not allowed by home assistant configuration."""
stream = create_stream(hass, h264_video, {}, dynamic_stream_settings())
with (
patch.object(hass.config, "is_allowed_path", return_value=False),
pytest.raises(HomeAssistantError),
):
await stream.async_record("/example/path")
def add_parts_to_segment(segment, source):
"""Add relevant part data to segment for testing recorder."""
moof_locs = [*find_box(source.getbuffer(), b"moof"), len(source.getbuffer())]
segment.init = source.getbuffer()[: moof_locs[0]].tobytes()
segment.parts = [
Part(
duration=None,
has_keyframe=None,
data=source.getbuffer()[moof_locs[i] : moof_locs[i + 1]],
)
for i in range(len(moof_locs) - 1)
]
async def test_recorder_discontinuity(
hass: HomeAssistant, filename, h264_video
) -> None:
"""Test recorder save across a discontinuity."""
# Run
segment_1 = Segment(sequence=1, stream_id=0)
add_parts_to_segment(segment_1, h264_video)
segment_1.duration = 4
segment_2 = Segment(sequence=2, stream_id=1)
add_parts_to_segment(segment_2, h264_video)
segment_2.duration = 4
provider_ready = asyncio.Event()
class MockStream(Stream):
"""Mock Stream so we can patch add_provider."""
async def start(self):
"""Make Stream.start a noop that gives up async context."""
await asyncio.sleep(0)
def add_provider(self, fmt, timeout=OUTPUT_IDLE_TIMEOUT):
"""Add a finished event to Stream.add_provider."""
provider = Stream.add_provider(self, fmt, timeout)
provider_ready.set()
return provider
with (
patch.object(hass.config, "is_allowed_path", return_value=True),
patch("homeassistant.components.stream.Stream", wraps=MockStream),
patch("homeassistant.components.stream.recorder.RecorderOutput.recv"),
):
stream = create_stream(hass, "blank", {}, dynamic_stream_settings())
make_recording = hass.async_create_task(stream.async_record(filename))
await provider_ready.wait()
recorder_output = stream.outputs()[RECORDER_PROVIDER]
recorder_output.idle_timer.start()
recorder_output._segments.extend([segment_1, segment_2])
# Fire the IdleTimer
future = dt_util.utcnow() + timedelta(seconds=30)
async_fire_time_changed(hass, future)
await make_recording
# Assert
assert os.path.exists(filename)
async def test_recorder_no_segments(hass: HomeAssistant, filename) -> None:
"""Test recorder behavior with a stream failure which causes no segments."""
stream = create_stream(hass, BytesIO(), {}, dynamic_stream_settings())
# Run
with patch.object(hass.config, "is_allowed_path", return_value=True):
await stream.async_record(filename)
# Assert
assert not os.path.exists(filename)
@pytest.fixture(scope="module")
def h264_mov_video():
"""Generate a source video with no audio."""
return generate_h264_video(container_format="mov")
@pytest.mark.parametrize(
("audio_codec", "expected_audio_streams"),
[
("aac", 1), # aac is a valid mp4 codec
("pcm_mulaw", 0), # G.711 is not a valid mp4 codec
("empty", 0), # audio stream with no packets
(None, 0), # no audio stream
],
)
async def test_record_stream_audio(
hass: HomeAssistant,
filename,
audio_codec,
expected_audio_streams,
h264_mov_video,
) -> None:
"""Test treatment of different audio inputs.
Record stream output should have an audio channel when input has
a valid codec and audio packets and no audio channel otherwise.
"""
# Remux source video with new audio
source = remux_with_audio(h264_mov_video, "mov", audio_codec) # mov can store PCM
worker_finished = asyncio.Event()
class MockStream(Stream):
"""Mock Stream so we can patch remove_provider."""
async def remove_provider(self, provider):
"""Add a finished event to Stream.remove_provider."""
await Stream.remove_provider(self, provider)
worker_finished.set()
with patch("homeassistant.components.stream.Stream", wraps=MockStream):
stream = create_stream(hass, source, {}, dynamic_stream_settings())
with patch.object(hass.config, "is_allowed_path", return_value=True):
make_recording = hass.async_create_task(stream.async_record(filename))
# In general usage the recorder will only include what has already been
# processed by the worker. To guarantee we have some output for the test,
# wait until the worker has finished before firing
await worker_finished.wait()
# Fire the IdleTimer
future = dt_util.utcnow() + timedelta(seconds=30)
async_fire_time_changed(hass, future)
await hass.async_block_till_done()
await make_recording
# Assert
assert os.path.exists(filename)
result = av.open(
filename,
"r",
format="mp4",
)
assert len(result.streams.audio) == expected_audio_streams
result.close()
await stream.stop()
await hass.async_block_till_done()
async def test_recorder_log(
hass: HomeAssistant, filename, caplog: pytest.LogCaptureFixture
) -> None:
"""Test starting a stream to record logs the url without username and password."""
stream = create_stream(
hass, "https://abcd:efgh@foo.bar", {}, dynamic_stream_settings()
)
with patch.object(hass.config, "is_allowed_path", return_value=True):
await stream.async_record(filename)
assert "https://abcd:efgh@foo.bar" not in caplog.text
assert "https://****:****@foo.bar" in caplog.text
async def test_record_stream_rotate(hass: HomeAssistant, filename, h264_video) -> None:
"""Test record stream with rotation."""
worker_finished = asyncio.Event()
class MockStream(Stream):
"""Mock Stream so we can patch remove_provider."""
async def remove_provider(self, provider):
"""Add a finished event to Stream.remove_provider."""
await Stream.remove_provider(self, provider)
worker_finished.set()
with patch("homeassistant.components.stream.Stream", wraps=MockStream):
stream = create_stream(hass, h264_video, {}, dynamic_stream_settings())
stream.dynamic_stream_settings.orientation = Orientation.ROTATE_RIGHT
with patch.object(hass.config, "is_allowed_path", return_value=True):
make_recording = hass.async_create_task(stream.async_record(filename))
# In general usage the recorder will only include what has already been
# processed by the worker. To guarantee we have some output for the test,
# wait until the worker has finished before firing
await worker_finished.wait()
# Fire the IdleTimer
future = dt_util.utcnow() + timedelta(seconds=30)
async_fire_time_changed(hass, future)
await make_recording
# Assert
assert os.path.exists(filename)
data = await hass.async_add_executor_job(Path(filename).read_bytes)
assert_mp4_has_transform_matrix(data, stream.dynamic_stream_settings.orientation)

File diff suppressed because it is too large Load Diff