1
0
mirror of https://github.com/home-assistant/core.git synced 2025-08-13 15:30:03 +00:00
Files
.devcontainer
.github
.vscode
docs
homeassistant
machine
pylint
rootfs
script
tests
auth
backports
components
abode
accuweather
acmeda
adax
adguard
advantage_air
aemet
agent_dvr
air_quality
airly
airnow
airq
airthings
airthings_ble
airtouch4
airvisual
airzone
aladdin_connect
alarm_control_panel
alarmdecoder
alert
alexa
almond
amberelectric
ambiclimate
ambient_station
analytics
android_ip_webcam
androidtv
anthemav
apache_kafka
apcupsd
api
api_streams
apple_tv
application_credentials
apprise
aprs
aranet
arcam_fmj
aseko_pool_live
asuswrt
atag
august
aurora
aurora_abb_powerone
aussie_broadband
auth
automation
awair
aws
axis
azure_devops
azure_event_hub
backup
baf
balboa
bayesian
binary_sensor
blackbird
blebox
blink
bluemaestro
blueprint
bluetooth
bluetooth_le_tracker
bmw_connected_drive
bond
bosch_shc
braviatv
broadlink
brother
brunt
bsblan
bthome
buienradar
button
caldav
calendar
camera
canary
cast
cert_expiry
clicksend_tts
climate
cloud
cloudflare
co2signal
coinbase
color_extractor
comfoconnect
command_line
compensation
config
configurator
control4
conversation
coolmaster
coronavirus
counter
cover
cpuspeed
crownstone
daikin
darksky
datadog
debugpy
deconz
default_config
deluge
demo
denonavr
derivative
device_automation
device_sun_light_trigger
device_tracker
devolo_home_control
devolo_home_network
dexcom
dhcp
diagnostics
dialogflow
directv
discord
discovery
dlna_dmr
dlna_dms
dnsip
doorbird
dsmr
dsmr_reader
dte_energy_bridge
duckdns
dunehd
dynalite
eafm
ecobee
econet
ecowitt
efergy
eight_sleep
elgato
elkm1
elmax
emonitor
emulated_hue
emulated_kasa
emulated_roku
energy
enocean
enphase_envoy
environment_canada
epson
escea
esphome
everlights
evil_genius_labs
ezviz
faa_delays
facebook
facebox
fail2ban
fan
feedreader
ffmpeg
fibaro
fido
file
file_upload
filesize
filter
fireservicerota
firmata
fivem
fjaraskupan
flic
flick_electric
flipr
flo
flume
flux
flux_led
folder
folder_watcher
foobot
forecast_solar
forked_daapd
foscam
freebox
freedns
freedompro
fritz
fritzbox
fritzbox_callmonitor
fronius
frontend
fully_kiosk
garages_amsterdam
gdacs
generic
generic_hygrostat
generic_thermostat
geo_json_events
geo_location
geo_rss_events
geocaching
geofency
geonetnz_quakes
geonetnz_volcano
gios
github
glances
goalzero
gogogate2
goodwe
google
google_assistant
google_assistant_sdk
google_domains
google_pubsub
google_sheets
google_translate
google_travel_time
google_wifi
govee_ble
gpslogger
graphite
gree
greeneye_monitor
group
growatt_server
guardian
habitica
hardkernel
hardware
harmony
hassio
hddtemp
hdmi_cec
heos
here_travel_time
hisense_aehw4a1
history
history_stats
hive
hlk_sw16
home_connect
home_plus_control
homeassistant
homeassistant_alerts
homeassistant_hardware
homeassistant_sky_connect
homeassistant_yellow
homekit
homekit_controller
homematic
homematicip_cloud
homewizard
honeywell
html5
http
huawei_lte
hue
huisbaasje
humidifier
hunterdouglas_powerview
hvv_departures
hyperion
ialarm
iaqualink
ibeacon
icloud
ifttt
ign_sismologia
image
image_processing
imap_email_content
influxdb
inkbird
input_boolean
input_button
input_datetime
input_number
input_select
input_text
insteon
integration
intellifire
intent
intent_script
ios
iotawatt
ipma
ipp
iqvia
islamic_prayer_times
iss
isy994
izone
jellyfin
jewish_calendar
juicenet
justnimbus
kaleidescape
keenetic_ndms2
kegtron
keymitt_ble
kira
kmtronic
knx
kodi
konnected
kostal_plenticore
kraken
kulersky
lacrosse_view
lametric
landisgyr_heat_meter
lastfm
launch_library
laundrify
lcn
led_ble
lg_soundbar
lidarr
life360
lifx
light
litejet
litterrobot
livisi
local_calendar
local_file
local_ip
locative
lock
logbook
logentries
logger
logi_circle
london_air
lookin
lovelace
luftdaten
lutron_caseta
lyric
mailbox
mailgun
manual
manual_mqtt
marytts
matter
maxcube
mazda
meater
media_player
media_source
melcloud
melissa
melnor
meraki
met
met_eireann
meteo_france
meteoclimatic
metoffice
mfi
microsoft_face
microsoft_face_detect
microsoft_face_identify
mikrotik
mill
min_max
minecraft_server
minio
mjpeg
moat
mobile_app
mochad
modbus
modem_callerid
modern_forms
moehlenhoff_alpha2
mold_indicator
monoprice
moon
motion_blinds
motioneye
mqtt
mqtt_eventstream
mqtt_json
mqtt_room
mqtt_statestream
mullvad
mutesync
my
myq
mysensors
mythicbeastsdns
nam
namecheapdns
nanoleaf
neato
ness_alarm
nest
netatmo
netgear
network
nexia
nextbus
nextdns
nfandroidtv
nibe_heatpump
nightscout
nina
nmap_tracker
no_ip
nobo_hub
notify
notify_events
notion
nsw_fuel_station
nsw_rural_fire_service_feed
nuheat
nuki
numato
number
nut
nws
nx584
nzbget
octoprint
omnilogic
onboarding
oncue
ondilo_ico
onewire
onvif
open_meteo
openalpr_cloud
openerz
openexchangerates
opengarage
openhardwaremonitor
opentherm_gw
openuv
openweathermap
opnsense
oralb
overkiz
ovo_energy
owntracks
p1_monitor
panasonic_viera
panel_custom
panel_iframe
peco
persistent_notification
person
philips_js
pi_hole
picnic
pilight
ping
plaato
plant
plex
plugwise
plum_lightpad
point
poolsense
powerwall
profiler
progettihwsw
prometheus
prosegur
proximity
prusalink
ps4
pure_energie
push
pushbullet
pushover
pvoutput
pvpc_hourly_pricing
python_script
qingping
qld_bushfire
qnap_qsw
qwikswitch
rachio
radarr
radio_browser
radiotherm
rainforest_eagle
rainmachine
random
raspberry_pi
rdw
recollect_waste
recorder
reddit
remember_the_milk
remote
renault
repairs
rest
rest_command
rflink
rfxtrx
rhasspy
ridwell
ring
risco
rituals_perfume_genie
rmvtransport
roku
roomba
roon
rpi_power
rss_feed_template
rtsp_to_webrtc
ruckus_unleashed
ruuvitag_ble
sabnzbd
safe_mode
samsungtv
scene
schedule
scrape
screenlogic
script
search
season
select
sense
senseme
sensibo
sensirion_ble
sensor
sensorpro
sensorpush
sentry
senz
seventeentrack
sharkiq
shell_command
shelly
shopping_list
sia
sigfox
sighthound
signal_messenger
simplepush
simplisafe
simulated
siren
skybell
slack
sleepiq
slimproto
sma
smappee
smart_meter_texas
smartthings
smarttub
smhi
smtp
snips
snmp
snooz
solaredge
solarlog
solax
soma
somfy_mylink
sonarr
songpal
sonos
soundtouch
spaceapi
spc
speedtestdotnet
spider
spotify
sql
squeezebox
srp_energy
ssdp
starline
startca
statistics
statsd
steam_online
steamist
stookalert
stream
__init__.py
common.py
conftest.py
test_hls.py
test_init.py
test_ll_hls.py
test_recorder.py
test_worker.py
stt
subaru
sun
surepetcare
switch
switch_as_x
switchbee
switchbot
switcher_kis
syncthing
syncthru
synology_dsm
system_bridge
system_health
system_log
tado
tag
tailscale
tankerkoenig
tasmota
tautulli
tcp
telegram
telegram_bot
tellduslive
template
tesla_wall_connector
text
thermobeacon
thermopro
threshold
tibber
tile
tilt_ble
time_date
timer
tod
todoist
tolo
tomato
tomorrowio
toon
totalconnect
tplink
traccar
trace
tractive
tradfri
trafikverket_ferry
trafikverket_train
trafikverket_weatherstation
transmission
transport_nsw
trend
tts
tuya
twentemilieu
twilio
twinkly
twitch
uk_transport
ukraine_alarm
unifi
unifi_direct
unifiprotect
universal
upb
upcloud
update
upnp
uptime
uptimerobot
usb
usgs_earthquakes_feed
utility_meter
uvc
vacuum
vallox
velbus
venstar
vera
verisure
version
vesync
vicare
vilfo
vizio
vlc_telnet
voicerss
volumio
volvooncall
vulcan
vultr
wake_on_lan
wallbox
water_heater
watttime
waze_travel_time
weather
webhook
webostv
websocket_api
wemo
whirlpool
whois
wiffi
wilight
withings
wiz
wled
wolflink
workday
worldclock
ws66i
wsdot
xbox
xiaomi
xiaomi_aqara
xiaomi_ble
xiaomi_miio
yale_smart_alarm
yalexs_ble
yamaha
yamaha_musiccast
yandex_transport
yandextts
yeelight
yolink
youless
zamg
zeroconf
zerproc
zha
zodiac
zone
zwave_js
zwave_me
__init__.py
conftest.py
fixtures
hassfest
helpers
pylint
resources
scripts
test_util
testing_config
util
__init__.py
bandit.yaml
common.py
conftest.py
ignore_uncaught_exceptions.py
test_bootstrap.py
test_config.py
test_config_entries.py
test_core.py
test_data_entry_flow.py
test_exceptions.py
test_loader.py
test_main.py
test_requirements.py
test_runner.py
test_setup.py
test_test_fixtures.py
.core_files.yaml
.coveragerc
.dockerignore
.gitattributes
.gitignore
.hadolint.yaml
.pre-commit-config.yaml
.prettierignore
.readthedocs.yml
.strict-typing
.yamllint
CLA.md
CODEOWNERS
CODE_OF_CONDUCT.md
CONTRIBUTING.md
Dockerfile
Dockerfile.dev
LICENSE.md
MANIFEST.in
README.rst
build.yaml
codecov.yml
mypy.ini
pyproject.toml
requirements.txt
requirements_all.txt
requirements_docs.txt
requirements_test.txt
requirements_test_all.txt
requirements_test_pre_commit.txt
setup.cfg
core/tests/components/stream/test_hls.py
2022-11-13 01:22:59 +08:00

564 lines
18 KiB
Python

"""The tests for hls streams."""
from datetime import timedelta
from http import HTTPStatus
import logging
from unittest.mock import patch
from urllib.parse import urlparse
import av
import pytest
from homeassistant.components.stream import 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.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
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) -> 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):
"""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, hass_client):
"""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, setup_component, hls_stream, stream_worker_sync, h264_video
):
"""
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, hass_client, setup_component, stream_worker_sync, h264_video
):
"""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, hass_client, setup_component, stream_worker_sync, h264_video
):
"""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, setup_component, should_retry):
"""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)
cur_time = 0
def time_side_effect():
logging.info("time side effect")
nonlocal cur_time
if cur_time >= 80:
logging.info("changing return value")
should_retry.return_value = False # Thread should exit and be joinable.
cur_time += 40
return cur_time
with patch("av.open") as av_open, patch(
"homeassistant.components.stream.time"
) as mock_time, patch(
"homeassistant.components.stream.STREAM_RESTART_INCREMENT", 0
):
av_open.side_effect = av.error.InvalidDataError(-2, "error")
mock_time.time.side_effect = time_side_effect
# Request stream. Enable retries which are disabled by default in tests.
should_retry.return_value = True
await stream.start()
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, setup_component, hls_stream):
"""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, setup_component, hls_stream, stream_worker_sync):
"""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, setup_component, hls_stream, stream_worker_sync):
"""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 = []
for sequence in range(start, MAX_SEGMENTS + 1):
segments.append(make_segment(sequence))
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, setup_component, hls_stream, stream_worker_sync
):
"""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, setup_component, hls_stream, stream_worker_sync
):
"""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 = []
for sequence in range(start, MAX_SEGMENTS + 1):
segments.append(make_segment(sequence))
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, setup_component, stream_worker_sync
):
"""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, setup_component, hls_stream, stream_worker_sync, h264_video
):
"""
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()