mirror of
https://github.com/home-assistant/core.git
synced 2025-08-15 16:30:04 +00:00
.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
airthings
airtouch4
airvisual
airzone
alarm_control_panel
alarmdecoder
alert
alexa
almond
ambee
amberelectric
ambiclimate
ambient_station
analytics
androidtv
apache_kafka
api
api_streams
apple_tv
apprise
aprs
arcam_fmj
arlo
aseko_pool_live
asuswrt
atag
august
aurora
aurora_abb_powerone
aussie_broadband
auth
automation
awair
aws
axis
azure_devops
azure_event_hub
backup
balboa
bayesian
binary_sensor
blackbird
blebox
blink
blueprint
bluetooth_le_tracker
bmw_connected_drive
bond
bosch_shc
braviatv
broadlink
brother
brunt
bsblan
buienradar
button
caldav
calendar
camera
canary
cast
cert_expiry
climacell
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
demo
denonavr
derivative
device_automation
device_sun_light_trigger
device_tracker
devolo_home_control
devolo_home_network
dexcom
dhcp
diagnostics
dialogflow
directv
discovery
dlna_dmr
dlna_dms
dnsip
doorbird
dsmr
dte_energy_bridge
duckdns
dunehd
dynalite
eafm
ecobee
econet
efergy
elgato
elkm1
elmax
emonitor
emulated_hue
emulated_kasa
emulated_roku
energy
enocean
enphase_envoy
environment_canada
epson
esphome
everlights
evil_genius_labs
ezviz
faa_delays
facebook
facebox
fail2ban
fan
feedreader
ffmpeg
fido
file
filesize
filter
fireservicerota
firmata
fivem
fjaraskupan
flic
flick_electric
flipr
flo
flume
flunearyou
flux
flux_led
folder
folder_watcher
foobot
forecast_solar
forked_daapd
foscam
freebox
freedns
freedompro
fritz
fritzbox
fritzbox_callmonitor
fronius
frontend
garages_amsterdam
gdacs
generic
generic_hygrostat
generic_thermostat
geo_json_events
geo_location
geo_rss_events
geofency
geonetnz_quakes
geonetnz_volcano
gios
github
glances
goalzero
gogogate2
goodwe
google
google_assistant
google_domains
google_pubsub
google_translate
google_travel_time
google_wifi
gpslogger
graphite
gree
greeneye_monitor
group
growatt_server
guardian
habitica
hangouts
harmony
hassio
hddtemp
heos
here_travel_time
hisense_aehw4a1
history
history_stats
hive
hlk_sw16
home_connect
home_plus_control
homeassistant
homekit
homekit_controller
homematic
homematicip_cloud
homewizard
honeywell
html5
http
huawei_lte
hue
huisbaasje
humidifier
hunterdouglas_powerview
hvv_departures
hyperion
ialarm
iaqualink
icloud
ifttt
ign_sismologia
image
image_processing
imap_email_content
influxdb
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
kaleidescape
keenetic_ndms2
kira
kmtronic
knx
kodi
konnected
kostal_plenticore
kraken
kulersky
lastfm
launch_library
lcn
light
litejet
litterrobot
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
maxcube
mazda
media_player
media_source
melcloud
melissa
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
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
nfandroidtv
nightscout
nina
nmap_tracker
no_ip
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
openalpr_local
openerz
opengarage
openhardwaremonitor
opentherm_gw
openuv
openweathermap
opnsense
overkiz
ovo_energy
owntracks
ozw
p1_monitor
panasonic_viera
panel_custom
panel_iframe
persistent_notification
person
philips_js
pi_hole
picnic
pilight
ping
plaato
plant
plex
plugwise
plum_lightpad
point
poolsense
powerwall
profiler
progettihwsw
prometheus
prosegur
proximity
ps4
pure_energie
push
pushbullet
pvoutput
pvpc_hourly_pricing
python_script
qld_bushfire
qwikswitch
rachio
radarr
radio_browser
rainforest_eagle
rainmachine
random
rdw
recollect_waste
recorder
reddit
remember_the_milk
remote
renault
rest
rest_command
rflink
rfxtrx
ridwell
ring
risco
rituals_perfume_genie
rmvtransport
roku
roomba
roon
rpi_power
rss_feed_template
rtsp_to_webrtc
ruckus_unleashed
safe_mode
samsungtv
scene
scrape
screenlogic
script
search
season
select
sense
senseme
sensibo
sensor
sentry
seventeentrack
sharkiq
shell_command
shelly
shopping_list
sia
sigfox
sighthound
signal_messenger
simplisafe
simulated
siren
slack
sleepiq
sma
smappee
smart_meter_texas
smarthab
smartthings
smarttub
smhi
smtp
snips
solaredge
solarlog
solax
soma
somfy
somfy_mylink
sonarr
songpal
sonos
soundtouch
spaceapi
spc
speedtestdotnet
spider
spotify
sql
squeezebox
srp_energy
ssdp
starline
startca
statistics
statsd
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
switchbot
switcher_kis
syncthing
syncthru
synology_dsm
system_bridge
system_health
system_log
tado
tag
tailscale
tasmota
tcp
telegram
tellduslive
template
tesla_wall_connector
threshold
tibber
tile
time_date
timer
tod
todoist
tolo
tomato
toon
totalconnect
tplink
traccar
trace
tractive
tradfri
trafikverket_weatherstation
transmission
transport_nsw
trend
tts
tuya
twentemilieu
twilio
twinkly
twitch
uk_transport
unifi
unifi_direct
unifiprotect
universal
upb
upcloud
updater
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
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
wsdot
xbox
xiaomi
xiaomi_aqara
xiaomi_miio
yale_smart_alarm
yamaha
yamaha_musiccast
yandex_transport
yandextts
yeelight
youless
zeroconf
zerproc
zha
zodiac
zone
zwave
zwave_js
zwave_me
__init__.py
conftest.py
fixtures
hassfest
helpers
mock
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
.ignore
.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
tox.ini
153 lines
4.7 KiB
Python
153 lines
4.7 KiB
Python
"""Collection of test helpers."""
|
|
from datetime import datetime
|
|
from fractions import Fraction
|
|
import functools
|
|
from functools import partial
|
|
import io
|
|
|
|
import av
|
|
import numpy as np
|
|
|
|
from homeassistant.components.stream.core import Segment
|
|
|
|
FAKE_TIME = datetime.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)
|
|
img = np.clip(img, 0, 255)
|
|
return img
|
|
|
|
|
|
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
|