Repository navigation
Expand file tree
/
Copy pathcamera.py
More file actions
2299 lines (2009 loc) · 94.2 KB
/
Copy pathcamera.py
File metadata and controls
2299 lines (2009 loc) · 94.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""Contains the Camera accessory and related.
When a HAP client (e.g. iOS) wants to start a video stream it does the following:
[0. Read supported RTP configuration]
[0. Read supported video configuration]
[0. Read supported audio configuration]
[0. Read the current streaming status]
1. Sets the SetupEndpoints characteristic to notify the camera about its IP address,
selected security parameters, etc.
2. The camera answers the write with its IP address, etc., and the client reads the
answer back from SetupEndpoints.
3. The client sets the SelectedRTPStreamConfiguration characteristic to notify the
camera of its prefered audio and video configuration and to initiate the start of the
streaming.
4. The camera starts the streaming with the above configuration.
[5. At some point the client can reconfigure or stop the stream similarly to step 3.]
"""
import asyncio
from collections.abc import AsyncGenerator, Callable, Iterable, Mapping, Sequence
import contextlib
import functools
import hashlib
import ipaddress
import logging
import os
import struct
from types import MappingProxyType
from typing import TYPE_CHECKING, Any
from uuid import UUID
from pyhap import (
RESOURCE_DIR,
hds,
hds_recording,
hds_server,
hksv3,
hksv_recording,
tlv,
)
from pyhap.accessory import Accessory
from pyhap.camera_talkback import TalkbackReceiver, talkback_available
from pyhap.characteristic import Characteristic
from pyhap.const import CATEGORY_CAMERA
from pyhap.service import Service
from pyhap.util import base64_to_bytes, byte_bool, callback, to_base64_str
if TYPE_CHECKING:
from pyhap.camera_multi_tier import MultiTierController
from pyhap.camera_webrtc import WebRTCController
SETUP_TYPES = {
"SESSION_ID": b"\x01",
"STATUS": b"\x02",
"ADDRESS": b"\x03",
"VIDEO_SRTP_PARAM": b"\x04",
"AUDIO_SRTP_PARAM": b"\x05",
"VIDEO_SSRC": b"\x06",
"AUDIO_SSRC": b"\x07",
}
SETUP_STATUS = {
"SUCCESS": b"\x00",
"BUSY": b"\x01",
"ERROR": b"\x02",
}
SETUP_IPV = {
"IPV4": b"\x00",
"IPV6": b"\x01",
}
SETUP_ADDR_INFO = {
"ADDRESS_VER": b"\x01",
"ADDRESS": b"\x02",
"VIDEO_RTP_PORT": b"\x03",
"AUDIO_RTP_PORT": b"\x04",
}
SETUP_SRTP_PARAM = {
"CRYPTO": b"\x01",
"MASTER_KEY": b"\x02",
"MASTER_SALT": b"\x03",
}
STREAMING_STATUS = {
"AVAILABLE": b"\x00",
"STREAMING": b"\x01",
"BUSY": b"\x02",
}
RTP_CONFIG_TYPES = {
"CRYPTO": b"\x02",
}
SRTP_CRYPTO_SUITES = {
"AES_CM_128_HMAC_SHA1_80": b"\x00",
"AES_CM_256_HMAC_SHA1_80": b"\x01",
"NONE": b"\x02",
}
VIDEO_TYPES = {
"CODEC": b"\x01",
"CODEC_PARAM": b"\x02",
"ATTRIBUTES": b"\x03",
"RTP_PARAM": b"\x04",
}
VIDEO_CODEC_TYPES = {
"H264": b"\x00",
}
VIDEO_CODEC_PARAM_TYPES = {
"PROFILE_ID": b"\x01",
"LEVEL": b"\x02",
"PACKETIZATION_MODE": b"\x03",
"CVO_ENABLED": b"\x04",
"CVO_ID": b"\x05",
}
VIDEO_CODEC_PARAM_CVO_TYPES = {
"UNSUPPORTED": b"\x01",
"SUPPORTED": b"\x02",
}
VIDEO_CODEC_PARAM_PROFILE_ID_TYPES = {
"BASELINE": b"\x00",
"MAIN": b"\x01",
"HIGH": b"\x02",
}
VIDEO_CODEC_PARAM_LEVEL_TYPES = {
"TYPE3_1": b"\x00",
"TYPE3_2": b"\x01",
"TYPE4_0": b"\x02",
}
VIDEO_CODEC_PARAM_PACKETIZATION_MODE_TYPES = {
"NON_INTERLEAVED": b"\x00",
}
VIDEO_ATTRIBUTES_TYPES = {
"IMAGE_WIDTH": b"\x01",
"IMAGE_HEIGHT": b"\x02",
"FRAME_RATE": b"\x03",
}
SUPPORTED_VIDEO_CONFIG_TAG = b"\x01"
SELECTED_STREAM_CONFIGURATION_TYPES = {
"SESSION": b"\x01",
"VIDEO": b"\x02",
"AUDIO": b"\x03",
}
RTP_PARAM_TYPES = {
"PAYLOAD_TYPE": b"\x01",
"SYNCHRONIZATION_SOURCE": b"\x02",
"MAX_BIT_RATE": b"\x03",
"RTCP_SEND_INTERVAL": b"\x04",
"MAX_MTU": b"\x05",
"COMFORT_NOISE_PAYLOAD_TYPE": b"\x06",
}
AUDIO_TYPES = {
"CODEC": b"\x01",
"CODEC_PARAM": b"\x02",
"RTP_PARAM": b"\x03",
"COMFORT_NOISE": b"\x04",
}
AUDIO_CODEC_TYPES = {
"PCMU": b"\x00",
"PCMA": b"\x01",
"AACELD": b"\x02",
"OPUS": b"\x03",
}
AUDIO_CODEC_PARAM_TYPES = {
"CHANNEL": b"\x01",
"BIT_RATE": b"\x02",
"SAMPLE_RATE": b"\x03",
"PACKET_TIME": b"\x04",
}
AUDIO_CODEC_PARAM_BIT_RATE_TYPES = {
"VARIABLE": b"\x00",
"CONSTANT": b"\x01",
}
AUDIO_CODEC_PARAM_SAMPLE_RATE_TYPES = {
"KHZ_8": b"\x00",
"KHZ_16": b"\x01",
"KHZ_24": b"\x02",
}
SUPPORTED_AUDIO_CODECS_TAG = b"\x01"
SUPPORTED_COMFORT_NOISE_TAG = b"\x02"
SUPPORTED_AUDIO_CONFIG_TAG = b"\x02"
SET_CONFIG_REQUEST_TAG = b"\x02"
SESSION_ID = b"\x01"
NO_SRTP = b"\x01\x01\x02\x02\x00\x03\x00"
"""Configuration value for no SRTP."""
FFMPEG_CMD = (
"ffmpeg -re -f avfoundation -framerate {fps} -i 0:0 -threads 0 "
"-vcodec libx264 -an -pix_fmt yuv420p -r {fps} -f rawvideo -tune zerolatency "
"-vf scale={width}:{height} -b:v {v_max_bitrate}k -bufsize {v_max_bitrate}k "
"-payload_type 99 -ssrc {v_ssrc} -f rtp "
"-srtp_out_suite AES_CM_128_HMAC_SHA1_80 -srtp_out_params {v_srtp_key} "
"srtp://{address}:{v_port}?rtcpport={v_port}&"
"localrtcpport={v_port}&pkt_size=1378"
)
"""Template for the ffmpeg command."""
logger = logging.getLogger(__name__)
SELECTED_RECORDING_CHAR = "SelectedCameraRecordingConfiguration"
PERSISTED_RECORDING_CHARS = (
("CameraRecordingManagement", "Active"),
("CameraRecordingManagement", "RecordingAudioActive"),
("CameraRecordingManagement", SELECTED_RECORDING_CHAR),
("CameraOperatingMode", "EventSnapshotsActive"),
("CameraOperatingMode", "HomeKitCameraActive"),
("CameraOperatingMode", "PeriodicSnapshotsActive"),
)
# accessory_state key of the HKSV 17.99 settings.
HKSV3_STATE = "hksv3"
HKSV3_MOTION_CHARS = ("ContributingSensors", "MotionEnabled")
# Concurrent video encodings each sensor must offer (HKSV 17.99 guide, section 2).
HKSV3_MIN_SENSOR_STREAMS = 3
SUPPORTED_RECORDING_CHARS = (
"SupportedCameraRecordingConfiguration",
"SupportedVideoRecordingConfiguration",
"SupportedAudioRecordingConfiguration",
)
# Global operating mode chars a controller writes, the camera keeps them.
PERSISTED_GLOBAL_OPERATING_MODE_CHARS = (
"HomeKitCameraActive",
"StreamingEnabled",
"CameraOperatingModeIndicator",
"NightVision",
)
def parse_setup_address(
value: bytes, is_ipv6: bool
) -> ipaddress.IPv4Address | ipaddress.IPv6Address:
"""Return the controller address of a Setup Endpoints write.
The address must be an IP address of the announced version, without an
IPv6 scope ID. ``str()`` gives its canonical form, e.g. ``fd00::1`` for
``FD00:0::1``.
:raises ValueError: If the address is anything else.
"""
try:
address = value.decode("utf-8")
parsed = ipaddress.ip_address(address)
except ValueError as ex:
raise ValueError(f"invalid address {value!r}") from ex
if isinstance(parsed, ipaddress.IPv6Address) and parsed.scope_id is not None:
raise ValueError(f"address {address!r} has a scope ID")
if parsed.version != (6 if is_ipv6 else 4):
raise ValueError(f"address {address!r} does not match its IP version")
return parsed
def _decode_setup_endpoints(
session_id: UUID, objs: dict[bytes, Any]
) -> tuple[str, bool, int, int, tuple[bytes, bytes], tuple[bytes, bytes]]:
"""Decode a Setup Endpoints write.
Returns the controller address, whether it is IPv6, its video and audio
ports and the video and audio SRTP master key and salt.
:raises ValueError: If the address is not a valid IP address.
:raises KeyError: If a field is missing.
:raises struct.error: If a field is too short.
:raises IndexError: If a crypto suite is empty.
"""
address_info = tlv.decode(objs[SETUP_TYPES["ADDRESS"]])
is_ipv6 = struct.unpack("?", address_info[SETUP_ADDR_INFO["ADDRESS_VER"]])[0]
address = str(
parse_setup_address(bytes(address_info[SETUP_ADDR_INFO["ADDRESS"]]), is_ipv6)
)
video_port, audio_port = (
int(struct.unpack("<H", address_info[SETUP_ADDR_INFO[key]])[0])
for key in ("VIDEO_RTP_PORT", "AUDIO_RTP_PORT")
)
video = tlv.decode(objs[SETUP_TYPES["VIDEO_SRTP_PARAM"]])
audio = tlv.decode(objs[SETUP_TYPES["AUDIO_SRTP_PARAM"]])
# Do not log the SRTP key material: debug logs may end up in less
# trusted log collections, and the keys live for the whole session.
logger.debug(
"Received endpoint configuration:"
"\nsession_id: %s\naddress: %s\nis_ipv6: %s"
"\ntarget_video_port: %s\ntarget_audio_port: %s"
"\nvideo_crypto_suite: %s\naudio_crypto_suite: %s",
session_id,
address,
is_ipv6,
video_port,
audio_port,
video[SETUP_SRTP_PARAM["CRYPTO"]][0],
audio[SETUP_SRTP_PARAM["CRYPTO"]][0],
)
return (
address,
is_ipv6,
video_port,
audio_port,
(
bytes(video[SETUP_SRTP_PARAM["MASTER_KEY"]]),
bytes(video[SETUP_SRTP_PARAM["MASTER_SALT"]]),
),
(
bytes(audio[SETUP_SRTP_PARAM["MASTER_KEY"]]),
bytes(audio[SETUP_SRTP_PARAM["MASTER_SALT"]]),
),
)
def _setup_endpoints_status(session_id: UUID, status: bytes) -> str:
"""Encode a Setup Endpoints answer that has only a status."""
return tlv.encode(
SETUP_TYPES["SESSION_ID"],
session_id.bytes,
SETUP_TYPES["STATUS"],
status,
to_base64=True,
)
class Camera(Accessory):
"""An Accessory that can negotiate camera stream settings with a HAP client
(e.g. iOS) and start a stream.
The Camera accessory implements the HomeKit Protocol for negotiating stream
settings, such as the picture width and height, number of audio channels and
others. Starting a video and/or audio stream, however, is very platform
specific. Because of this, you need to figure out what video and audio
settings your camera supports and set them in the ``options`` parameter that
is passed to the constructor - see the documentation of :meth:`__init__` for
the settings you need to specify.
By default, HAP-python will execute the :data:`FFMPEG_CMD` command with the
negotiated parameters when a stream should be started and will terminate the
started process when the stream should be stopped. If the default command is
not supported or correctly formatted for your platform, the streaming can
fail. For these cases, HAP-python has hooks so that you can insert your own
command or implement the logic for starting or stopping the stream:
1. Pass your own command that will be executed when the stream should be
started. You pass the command as a value to the key ``start_stream_cmd``
in the ``options`` parameter to the constructor of the ``Camera``
Accessory. The command is formatted using the negotiated stream
configuration parameters. For example, if the negotiated width is 640 and
you pass ``foo start -width {width}``, the command will be formatted as
``foo start -width 640``. The full list of negotiated stream configuration
parameters can be found in the documentation for the
:meth:`start_stream` method.
2. Implement your own logic to start, stop and reconfigure the stream. If
you need more flexibility in managing streams, you can directly override
the :meth:`start_stream`, :meth:`stop_stream` and
:meth:`reconfigure_stream` methods. Each will be called when the stream
should be respectively started, stopped or reconfigured. The start and
reconfigure methods are given the negotiated stream configuration
parameters.
Finally, if you can take snapshots from the camera, you may want to
implement the :meth:`get_snapshot` method. By default, this serves a stock
photo.
"""
category = CATEGORY_CAMERA
@staticmethod
def get_supported_rtp_config(support_srtp: bool) -> Any:
"""Return a tlv representation of the RTP configuration we support.
SRTP support allows only the AES_CM_128_HMAC_SHA1_80 cipher for now.
:param support_srtp: True if SRTP is supported, False otherwise.
:type support_srtp: bool
"""
if support_srtp:
crypto = SRTP_CRYPTO_SUITES["AES_CM_128_HMAC_SHA1_80"]
else:
crypto = SRTP_CRYPTO_SUITES["NONE"]
return tlv.encode(RTP_CONFIG_TYPES["CRYPTO"], crypto, to_base64=True)
@staticmethod
def get_supported_video_stream_config(video_params: dict[str, Any]) -> Any:
"""Return a tlv representation of the supported video stream configuration.
Expected video parameters:
- codec
- resolutions
:param video_params: Supported video configurations
:type video_params: dict
"""
codec_params_tlv = tlv.encode(
VIDEO_CODEC_PARAM_TYPES["PACKETIZATION_MODE"],
VIDEO_CODEC_PARAM_PACKETIZATION_MODE_TYPES["NON_INTERLEAVED"],
)
codec_params = video_params["codec"]
for profile in codec_params["profiles"]:
codec_params_tlv += tlv.encode(
VIDEO_CODEC_PARAM_TYPES["PROFILE_ID"], profile
)
for level in codec_params["levels"]:
codec_params_tlv += tlv.encode(VIDEO_CODEC_PARAM_TYPES["LEVEL"], level)
attr_tlv = b""
for resolution in video_params["resolutions"]:
res_tlv = tlv.encode(
VIDEO_ATTRIBUTES_TYPES["IMAGE_WIDTH"],
struct.pack("<H", resolution[0]),
VIDEO_ATTRIBUTES_TYPES["IMAGE_HEIGHT"],
struct.pack("<H", resolution[1]),
VIDEO_ATTRIBUTES_TYPES["FRAME_RATE"],
struct.pack("<H", resolution[2]),
)
attr_tlv += tlv.encode(VIDEO_TYPES["ATTRIBUTES"], res_tlv)
config_tlv = tlv.encode(
VIDEO_TYPES["CODEC"],
VIDEO_CODEC_TYPES["H264"],
VIDEO_TYPES["CODEC_PARAM"],
codec_params_tlv,
)
return tlv.encode(
SUPPORTED_VIDEO_CONFIG_TAG, config_tlv + attr_tlv, to_base64=True
)
@staticmethod
def get_supported_audio_stream_config(audio_params: dict[str, Any]) -> str:
"""Return a tlv representation of the supported audio stream configuration.
iOS supports only AACELD and OPUS
Expected audio parameters:
- codecs
- comfort_noise
:param audio_params: Supported audio configurations
:type audio_params: dict
"""
has_supported_codec = False
configs = b""
for codec_param in audio_params["codecs"]:
param_type = codec_param["type"]
if param_type == "OPUS":
has_supported_codec = True
codec = AUDIO_CODEC_TYPES["OPUS"]
bitrate = AUDIO_CODEC_PARAM_BIT_RATE_TYPES["VARIABLE"]
elif param_type == "AAC-eld":
has_supported_codec = True
codec = AUDIO_CODEC_TYPES["AACELD"]
bitrate = AUDIO_CODEC_PARAM_BIT_RATE_TYPES["VARIABLE"]
else:
logger.warning("Unsupported codec %s", param_type)
continue
param_samplerate = codec_param["samplerate"]
if param_samplerate == 8:
samplerate = AUDIO_CODEC_PARAM_SAMPLE_RATE_TYPES["KHZ_8"]
elif param_samplerate == 16:
samplerate = AUDIO_CODEC_PARAM_SAMPLE_RATE_TYPES["KHZ_16"]
elif param_samplerate == 24:
samplerate = AUDIO_CODEC_PARAM_SAMPLE_RATE_TYPES["KHZ_24"]
else:
logger.warning("Unsupported sample rate %s", param_samplerate)
continue
param_tlv = tlv.encode(
AUDIO_CODEC_PARAM_TYPES["CHANNEL"],
b"\x01",
AUDIO_CODEC_PARAM_TYPES["BIT_RATE"],
bitrate,
AUDIO_CODEC_PARAM_TYPES["SAMPLE_RATE"],
samplerate,
)
config_tlv = tlv.encode(
AUDIO_TYPES["CODEC"], codec, AUDIO_TYPES["CODEC_PARAM"], param_tlv
)
configs += tlv.encode(SUPPORTED_AUDIO_CODECS_TAG, config_tlv)
if not has_supported_codec:
logger.warning("Client does not support any audio codec that iOS supports.")
codec = AUDIO_CODEC_TYPES["OPUS"]
bitrate = AUDIO_CODEC_PARAM_BIT_RATE_TYPES["VARIABLE"]
samplerate = AUDIO_CODEC_PARAM_SAMPLE_RATE_TYPES["KHZ_24"]
param_tlv = tlv.encode(
AUDIO_CODEC_PARAM_TYPES["CHANNEL"],
b"\x01",
AUDIO_CODEC_PARAM_TYPES["BIT_RATE"],
bitrate,
AUDIO_CODEC_PARAM_TYPES["SAMPLE_RATE"],
samplerate,
)
config_tlv = tlv.encode(
AUDIO_TYPES["CODEC"], codec, AUDIO_TYPES["CODEC_PARAM"], param_tlv
)
configs = tlv.encode(SUPPORTED_AUDIO_CODECS_TAG, config_tlv)
comfort_noise = byte_bool(audio_params.get("comfort_noise", False))
audio_config = to_base64_str(
configs + tlv.encode(SUPPORTED_COMFORT_NOISE_TAG, comfort_noise)
)
return audio_config
def __init__(self, options: dict[str, Any], *args: Any, **kwargs: Any) -> None:
"""Initialize a camera accessory with the given options.
:param options: Describes the supported video and audio configuration
of this camera. Expected values are video, audio, srtp and address.
Example configuration:
.. code-block:: python
{
"video": {
"codec": {
"profiles": [
camera.VIDEO_CODEC_PARAM_PROFILE_ID_TYPES["BASELINE"],
],
"levels": [
camera.VIDEO_CODEC_PARAM_LEVEL_TYPES['TYPE3_1'],
],
},
"resolutions": [
[320, 240, 15], # Width, Height, framerate
[1024, 768, 30],
[640, 480, 30],
[640, 360, 30],
[480, 360, 30],
[480, 270, 30],
[320, 240, 30],
[320, 180, 30],
],
},
"audio": {
"codecs": [
{
'type': 'OPUS',
'samplerate': 24,
},
{
'type': 'AAC-eld',
'samplerate': 16
}
],
},
"address": "192.168.1.226", # Address from which the camera will stream
}
Additional optional values are:
- srtp - boolean, defaults to False. Whether the camera supports SRTP.
- talkback - boolean, defaults to False. Whether the camera supports
receiving two-way ("talkback") audio from the controller during a
live view session. Requires the optional ``pylibsrtp`` dependency
(``pip install HAP-python[Talkback]``). When enabled, a "Speaker"
service is added so that HAP clients know the accessory supports
it, and :meth:`talkback_audio_received` is called with the
received audio for each session that negotiates it.
- global_operating_mode - list of optional characteristics of the
HomeKit Secure Video 17.99 Camera Global Operating Mode service,
e.g. ``["ManuallyDisabled", "NightVision"]``. Opts into the service,
an empty list adds only the required characteristics. With
``recording``, the Camera Operating Mode service has a HomeKit
Camera Active too: the last write to either turns the camera on
or off, and the other one is set to the same value, so a hub
that only knows the classic one still works. While streaming is
not allowed, the camera refuses to set up live streams and ends
running ones. Unknown names raise ``ValueError``, a value that is
not a list raises ``TypeError``.
- start_stream_cmd - string specifying the command to be executed to start
the stream. The string can contain the keywords, corresponding to the
video and audio configuration that was negotiated between the camera
and the client. See the ``start`` method for a full list of parameters.
- sensors - list of :class:`pyhap.hksv3.SensorConfiguration`, the image
sensors of the camera. Opts into the HomeKit Secure Video 17.99
Camera Capabilities and Camera Motion Zones services, and adds
Contributing Sensors and Motion Enabled to the motion sensor,
or adds a motion sensor without ``recording``. Each sensor needs
at least three video encodings. With ``recording``, turning it
on for a paired camera changes the instance IDs of the recording
services with the default IID manager.
- multi_tier - :class:`pyhap.camera_multi_tier.MultiTierConfig`, or a
dict of its fields. Developer Preview of HomeKit Secure Video
17.99, experimental. Adds a Camera Multi-Tier RTP Stream
Management service per sensor, offering the sensor's video
encodings as H.265 tiers. Needs ``webrtc``, ``sensors``,
``global_operating_mode``, ``recording``, ``video`` and
``audio``: iOS 27 shows a camera without the classic RTP stream
management service as not responding. Its services come before
the RTP stream management services, which then get a new
``unique_id``; for a paired camera this changes instance IDs.
- webrtc - :class:`pyhap.camera_webrtc.WebRTCConfig`, or a dict of
its fields. Developer Preview of HomeKit Secure Video 17.99,
experimental. Adds a Camera WebRTC Stream Management service per
sensor, linked to its multi-tier service. Controllers view
remotely through it: one that streams through the multi-tier
service does not fall back to the RTP stream management service.
Needs ``multi_tier`` and the options that it needs.
:type options: ``dict``
"""
self.has_srtp = options.get("srtp", False)
self.support_talkback = options.get("talkback", False)
if self.support_talkback and not talkback_available():
raise ValueError(
"The 'talkback' option requires the optional 'pylibsrtp' "
"dependency. Install it with: pip install HAP-python[Talkback]"
)
self.start_stream_cmd = options.get("start_stream_cmd", FFMPEG_CMD)
self.stream_address = options["address"]
try:
ipaddress.IPv4Address(self.stream_address)
self.stream_address_isv6 = b"\x00"
except ValueError:
self.stream_address_isv6 = b"\x01"
self.sessions = {}
super().__init__(*args, **kwargs)
self.add_preload_service("Microphone")
if self.support_talkback:
self.add_preload_service("Speaker").configure_char("Mute", value=False)
self._streaming_status: list[bytes] = []
self._management = []
# All HKSV state defaults are initialized before any setup runs so the
# setup methods below never follow (and reset) them.
self._status_active_char = None
self._recording_service = None
self._selected_recording_config = None
# Last selection that decoded, the char may hold a rejected write.
self._selected_recording_raw = None
self._recording_defaults = {}
self._save_pending = False
self._recording_changed = False
self._motion_detected_char = None
# Bumped on stop so a start still binding does not publish its listener.
self._hds_generation = 0
self._hds_listener = None
self._hds_connections = set()
self._recording_stream = None
self._homekit_camera_active_char: Characteristic | None = None
# The HomeKit Camera Active of the Camera Operating Mode service, kept
# in step with the global one when both exist.
self._classic_camera_active_char: Characteristic | None = None
self._motion_status_active_char = None
self._global_operating_mode: Service | None = None
# Its chars by name, they don't change after the setup.
self._global_operating_mode_chars: dict[str, Characteristic] = {}
# Persisted HKSV 17.99 chars with their state key, default and the
# handler a reset calls.
self._hksv3_defaults: dict[
Characteristic, tuple[str, Any, Callable[[Any], None]]
] = {}
# The values the handlers last saw, they only hear about changes.
self._hksv3_seen: dict[Characteristic, Any] = {}
self._sensors: list[hksv3.SensorConfiguration] = list(
options.get("sensors") or []
)
self._motion_zones_service: Service | None = None
self._contributing_sensors_char: Characteristic | None = None
self._motion_enabled_char: Characteristic | None = None
self._multi_tier: dict[UUID, MultiTierController] = {}
self._webrtc: dict[UUID, WebRTCController] = {}
self._stream_status_scheduled = False
if options.get("multi_tier") is not None or options.get("webrtc") is not None:
self._setup_stream_controllers(options)
if options.get("video"):
self._setup_stream_management(options)
# Classic HomeKit Secure Video recording (HDS + fragmented MP4).
if options.get("recording"):
self._setup_recording_management(options)
transport = self.get_service("DataStreamTransportManagement")
if transport is not None:
for controller in self._stream_controllers():
controller.service.add_linked_service(transport)
if self._sensors:
self._setup_camera_capabilities()
# Last, so the instance IDs of the other services stay the same.
if options.get("global_operating_mode") is not None:
self._setup_global_operating_mode(options["global_operating_mode"])
self._restore_hksv3_state()
@property
def streaming_status(self) -> bytes | None:
"""For backwards compatibility."""
# A recording-only camera has no RTP stream management service.
return self._streaming_status[0] if self._streaming_status else None
def _setup_stream_management(self, options: dict[str, Any]) -> None:
"""Create stream management."""
stream_count = options.get("stream_count", 1)
for stream_idx in range(stream_count):
self._management.append(self._create_stream_management(stream_idx, options))
self._streaming_status.append(STREAMING_STATUS["AVAILABLE"])
def _create_stream_management(
self, stream_idx: int, options: dict[str, Any]
) -> Service:
"""Create a stream management service."""
# A new unique_id lets a persistent IID manager place the service
# after the multi-tier ones, which come first.
unique_id = stream_idx if not self._multi_tier else f"rtp-{stream_idx}"
management = self.add_preload_service(
"CameraRTPStreamManagement", unique_id=unique_id, chars=["Active"]
)
# HAP-NodeJS exposes an Active (0x0B0) characteristic on every stream
# management service (value 1 = active); iOS' camera validation expects
# it, and it is required for Secure Video eligibility.
management.configure_char("Active", value=1)
management.configure_char(
"StreamingStatus",
getter_callback=lambda: self._get_streaming_status(stream_idx),
)
management.configure_char(
"SupportedRTPConfiguration",
value=self.get_supported_rtp_config(options.get("srtp", False)),
)
management.configure_char(
"SupportedVideoStreamConfiguration",
value=self.get_supported_video_stream_config(options["video"]),
)
management.configure_char(
"SupportedAudioStreamConfiguration",
value=self.get_supported_audio_stream_config(options["audio"]),
)
management.configure_char(
"SelectedRTPStreamConfiguration",
setter_callback=self.set_selected_stream_configuration,
)
setup_endpoints = management.configure_char(
"SetupEndpoints",
setter_callback=lambda value: self.set_endpoints(
value, stream_idx=stream_idx
),
)
# The answer has the session's SRTP keys, only its controller reads it.
setup_endpoints.read_back_response = True
return management
def _setup_stream_controllers(self, options: dict[str, Any]) -> None:
"""Add the multi-tier and WebRTC controllers of each sensor (17.99)."""
# Here, not at the top: these modules import this one.
from pyhap.camera_multi_tier import ( # noqa: PLC0415
MultiTierConfig,
MultiTierController,
)
from pyhap.camera_webrtc import WebRTCConfig, WebRTCController # noqa: PLC0415
if options.get("multi_tier") is None or options.get("webrtc") is None:
raise ValueError(
"multi_tier and webrtc need each other, without WebRTC "
"controllers cannot view remotely"
)
if (
not options.get("video")
or not options.get("audio")
or options.get("stream_count", 1) < 1
):
raise ValueError(
"multi_tier and webrtc need the video and audio options, iOS 27 "
"shows a camera without the classic RTP stream management "
"service as not responding"
)
if (
not self._sensors
or options.get("global_operating_mode") is None
or not options.get("recording")
):
raise ValueError(
"multi_tier and webrtc need the sensors, global_operating_mode "
"and recording options"
)
multi_tier = MultiTierConfig.from_option(options["multi_tier"])
webrtc = WebRTCConfig.from_option(options["webrtc"])
for sensor in self._sensors:
for warning in hksv3.check_video_tiers(sensor):
logger.warning("Sensor %s: %s", sensor.sensor_uuid, warning)
controller = MultiTierController(self, sensor, multi_tier)
self._multi_tier[sensor.sensor_uuid] = controller
self._webrtc[sensor.sensor_uuid] = WebRTCController(
self, controller, webrtc
)
for kind, controllers in (
("multi_tier", self._multi_tier),
("webrtc", self._webrtc),
):
for sensor_uuid, controller in controllers.items():
self._persist_hksv3_char(
controller.streaming_enabled,
f"{kind}.{sensor_uuid}.streaming_enabled",
self._handle_stream_enabled,
)
def _stream_controllers(
self,
) -> "list[MultiTierController | WebRTCController]":
return [*self._multi_tier.values(), *self._webrtc.values()]
@property
def multi_tier_controllers(self) -> "Mapping[UUID, MultiTierController]":
"""The multi-tier RTP controller of each sensor (17.99), by sensor UUID."""
return MappingProxyType(self._multi_tier)
@property
def webrtc_controllers(self) -> "Mapping[UUID, WebRTCController]":
"""The WebRTC controller of each sensor (17.99), by sensor UUID."""
return MappingProxyType(self._webrtc)
def _handle_stream_enabled(self, value: Any) -> None:
self._schedule_stream_status()
def _schedule_stream_status(self) -> None:
"""Update the stream controllers once the current write is done.
A controller writes several of the values they depend on in one
request, e.g. HomeKit Camera Active and Streaming Enabled.
"""
if self._stream_status_scheduled or not self._multi_tier:
return
self._stream_status_scheduled = True
self.driver.loop.call_soon(self._update_stream_status)
def _update_stream_status(self) -> None:
"""Let each stream controller derive whether it may stream now.
Ends the sessions that may no longer stream.
"""
self._stream_status_scheduled = False
for controller in self._stream_controllers():
controller.update_status()
def stream_address_for(
self, client_addr: tuple[str, int] | None, is_ipv6: bool
) -> str | None:
"""The address to stream from to a controller, in the given IP version.
The accessory's address on the controller's connection, else the
``address`` option if it has that version.
"""
address = self.driver.local_address(client_addr, is_ipv6)
if address is not None:
return address
if (self.stream_address_isv6 == b"\x01") == is_ipv6:
return str(self.stream_address)
return None
async def end_session(self, session_id: UUID) -> bool:
"""End a multi-tier or WebRTC session (17.99) on the camera's side.
E.g. when its media source stopped. Ends the sessions with that ID of
every sensor and service and waits until their delegates released
them. Returns False if there is no such session.
"""
ended = await asyncio.gather(
*(
controller.end_session(session_id)
for controller in self._stream_controllers()
)
)
return any(ended)
async def end_all_sessions(self) -> None:
"""End every multi-tier and WebRTC session (17.99) and wait for them."""
await asyncio.gather(
*(
controller.end_all_sessions()
for controller in self._stream_controllers()
)
)
def client_disconnected(self, client_addr: tuple[str, int]) -> None:
"""End the multi-tier and WebRTC sessions of the connection."""
for controller in self._stream_controllers():
controller.client_disconnected(client_addr)
def _default_recording_configs(
self, options: dict[str, Any]
) -> tuple[
hksv_recording.SupportedRecordingConfiguration,
list[hksv_recording.VideoCodecConfiguration],
list[hksv_recording.AudioCodecConfiguration],
]:
"""Derive supported recording configurations from the streaming options.
A widely-compatible default: H.264 (Baseline/Main/High, levels 3.1/3.2/
4.0) at the streaming resolutions, AAC-LC audio. Accessories can override
this to advertise their own recording capabilities.
"""
video_opts = options.get("video") or {}
resolutions = video_opts.get("resolutions") or [[1920, 1080, 30]]
video = [
hksv_recording.VideoCodecConfiguration(
codec_type=hksv_recording.VideoCodecType.H264,
profile=[
VIDEO_CODEC_PARAM_PROFILE_ID_TYPES["BASELINE"][0],
VIDEO_CODEC_PARAM_PROFILE_ID_TYPES["MAIN"][0],
VIDEO_CODEC_PARAM_PROFILE_ID_TYPES["HIGH"][0],
],
level=[
VIDEO_CODEC_PARAM_LEVEL_TYPES["TYPE3_1"][0],
VIDEO_CODEC_PARAM_LEVEL_TYPES["TYPE3_2"][0],
VIDEO_CODEC_PARAM_LEVEL_TYPES["TYPE4_0"][0],
],
bitrate_kbps=2000,
iframe_interval_ms=4000,
attributes=[
hksv_recording.VideoAttributes(width, height, fps)
for width, height, fps in resolutions
],
)
]
audio = [hksv_recording.AudioCodecConfiguration()]
general = hksv_recording.SupportedRecordingConfiguration()
return general, video, audio
def _setup_recording_management(self, options: dict[str, Any]) -> None:
"""Create the Camera Recording Management service (classic HKSV).
Advertises the supported general/video/audio recording configurations
and accepts the controller's selection. Recording stays inactive
(Active=0) unless the ``recording`` option enables it; the fragment
data flow over HDS is wired by the recording transport.
"""
# HKSV requires the Camera Operating Mode service (0000021A); the
# controller validates its presence before enabling recording.
operating_mode = self.add_preload_service(
"CameraOperatingMode", chars=["PeriodicSnapshotsActive"]
)
operating_mode.configure_char("EventSnapshotsActive", value=1)
homekit_camera_active = operating_mode.configure_char(
"HomeKitCameraActive", value=1
)
homekit_camera_active.setter_callback = self._handle_homekit_camera_active
self._homekit_camera_active_char = homekit_camera_active
self._classic_camera_active_char = homekit_camera_active
operating_mode.configure_char("PeriodicSnapshotsActive", value=1)
# HKSV records on an event trigger; the camera owns a motion sensor and
# links it (and the data stream transport) to the recording management.
motion = self.add_preload_service(
"MotionSensor",
chars=["StatusActive", *(HKSV3_MOTION_CHARS if self._sensors else ())],
)
self._motion_detected_char = motion.configure_char(
"MotionDetected", value=False
)
# HAP-NodeJS marks the HKSV event-trigger sensor as active; iOS expects it.
# A restored HomeKitCameraActive bypasses the setter, so reads derive it.
self._motion_status_active_char = motion.configure_char(
"StatusActive", value=True, getter_callback=self._homekit_camera_on
)
general, video, audio = self._default_recording_configs(options)
service = self.add_preload_service(