HAP-python 4.9.2__py3-none-any.whl → 5.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
pyhap/camera.py CHANGED
@@ -22,205 +22,210 @@ import ipaddress
22
22
  import logging
23
23
  import os
24
24
  import struct
25
+ import sys
25
26
  from uuid import UUID
26
27
 
27
- import async_timeout
28
-
29
- from pyhap import RESOURCE_DIR, tlv
28
+ from pyhap import RESOURCE_DIR, hds, hds_recording, hds_server, hksv_recording, tlv
30
29
  from pyhap.accessory import Accessory
30
+ from pyhap.camera_talkback import TalkbackReceiver, talkback_available
31
31
  from pyhap.const import CATEGORY_CAMERA
32
- from pyhap.util import byte_bool, to_base64_str
32
+ from pyhap.util import base64_to_bytes, byte_bool, to_base64_str
33
+
34
+ if sys.version_info >= (3, 11):
35
+ from asyncio import timeout as async_timeout
36
+ else:
37
+ from async_timeout import timeout as async_timeout
33
38
 
34
39
  SETUP_TYPES = {
35
- 'SESSION_ID': b'\x01',
36
- 'STATUS': b'\x02',
37
- 'ADDRESS': b'\x03',
38
- 'VIDEO_SRTP_PARAM': b'\x04',
39
- 'AUDIO_SRTP_PARAM': b'\x05',
40
- 'VIDEO_SSRC': b'\x06',
41
- 'AUDIO_SSRC': b'\x07'
40
+ "SESSION_ID": b"\x01",
41
+ "STATUS": b"\x02",
42
+ "ADDRESS": b"\x03",
43
+ "VIDEO_SRTP_PARAM": b"\x04",
44
+ "AUDIO_SRTP_PARAM": b"\x05",
45
+ "VIDEO_SSRC": b"\x06",
46
+ "AUDIO_SSRC": b"\x07",
42
47
  }
43
48
 
44
49
 
45
50
  SETUP_STATUS = {
46
- 'SUCCESS': b'\x00',
47
- 'BUSY': b'\x01',
48
- 'ERROR': b'\x02'
51
+ "SUCCESS": b"\x00",
52
+ "BUSY": b"\x01",
53
+ "ERROR": b"\x02",
49
54
  }
50
55
 
51
56
 
52
57
  SETUP_IPV = {
53
- 'IPV4': b'\x00',
54
- 'IPV6': b'\x01'
58
+ "IPV4": b"\x00",
59
+ "IPV6": b"\x01",
55
60
  }
56
61
 
57
62
 
58
63
  SETUP_ADDR_INFO = {
59
- 'ADDRESS_VER': b'\x01',
60
- 'ADDRESS': b'\x02',
61
- 'VIDEO_RTP_PORT': b'\x03',
62
- 'AUDIO_RTP_PORT': b'\x04'
64
+ "ADDRESS_VER": b"\x01",
65
+ "ADDRESS": b"\x02",
66
+ "VIDEO_RTP_PORT": b"\x03",
67
+ "AUDIO_RTP_PORT": b"\x04",
63
68
  }
64
69
 
65
70
 
66
71
  SETUP_SRTP_PARAM = {
67
- 'CRYPTO': b'\x01',
68
- 'MASTER_KEY': b'\x02',
69
- 'MASTER_SALT': b'\x03'
72
+ "CRYPTO": b"\x01",
73
+ "MASTER_KEY": b"\x02",
74
+ "MASTER_SALT": b"\x03",
70
75
  }
71
76
 
72
77
 
73
78
  STREAMING_STATUS = {
74
- 'AVAILABLE': b'\x00',
75
- 'STREAMING': b'\x01',
76
- 'BUSY': b'\x02'
79
+ "AVAILABLE": b"\x00",
80
+ "STREAMING": b"\x01",
81
+ "BUSY": b"\x02",
77
82
  }
78
83
 
79
84
 
80
85
  RTP_CONFIG_TYPES = {
81
- 'CRYPTO': b'\x02'
86
+ "CRYPTO": b"\x02",
82
87
  }
83
88
 
84
89
 
85
90
  SRTP_CRYPTO_SUITES = {
86
- 'AES_CM_128_HMAC_SHA1_80': b'\x00',
87
- 'AES_CM_256_HMAC_SHA1_80': b'\x01',
88
- 'NONE': b'\x02'
91
+ "AES_CM_128_HMAC_SHA1_80": b"\x00",
92
+ "AES_CM_256_HMAC_SHA1_80": b"\x01",
93
+ "NONE": b"\x02",
89
94
  }
90
95
 
91
96
 
92
97
  VIDEO_TYPES = {
93
- 'CODEC': b'\x01',
94
- 'CODEC_PARAM': b'\x02',
95
- 'ATTRIBUTES': b'\x03',
96
- 'RTP_PARAM': b'\x04'
98
+ "CODEC": b"\x01",
99
+ "CODEC_PARAM": b"\x02",
100
+ "ATTRIBUTES": b"\x03",
101
+ "RTP_PARAM": b"\x04",
97
102
  }
98
103
 
99
104
 
100
105
  VIDEO_CODEC_TYPES = {
101
- 'H264': b'\x00'
106
+ "H264": b"\x00",
102
107
  }
103
108
 
104
109
 
105
110
  VIDEO_CODEC_PARAM_TYPES = {
106
- 'PROFILE_ID': b'\x01',
107
- 'LEVEL': b'\x02',
108
- 'PACKETIZATION_MODE': b'\x03',
109
- 'CVO_ENABLED': b'\x04',
110
- 'CVO_ID': b'\x05'
111
+ "PROFILE_ID": b"\x01",
112
+ "LEVEL": b"\x02",
113
+ "PACKETIZATION_MODE": b"\x03",
114
+ "CVO_ENABLED": b"\x04",
115
+ "CVO_ID": b"\x05",
111
116
  }
112
117
 
113
118
 
114
119
  VIDEO_CODEC_PARAM_CVO_TYPES = {
115
- 'UNSUPPORTED': b'\x01',
116
- 'SUPPORTED': b'\x02'
120
+ "UNSUPPORTED": b"\x01",
121
+ "SUPPORTED": b"\x02",
117
122
  }
118
123
 
119
124
 
120
125
  VIDEO_CODEC_PARAM_PROFILE_ID_TYPES = {
121
- 'BASELINE': b'\x00',
122
- 'MAIN': b'\x01',
123
- 'HIGH': b'\x02'
126
+ "BASELINE": b"\x00",
127
+ "MAIN": b"\x01",
128
+ "HIGH": b"\x02",
124
129
  }
125
130
 
126
131
 
127
132
  VIDEO_CODEC_PARAM_LEVEL_TYPES = {
128
- 'TYPE3_1': b'\x00',
129
- 'TYPE3_2': b'\x01',
130
- 'TYPE4_0': b'\x02'
133
+ "TYPE3_1": b"\x00",
134
+ "TYPE3_2": b"\x01",
135
+ "TYPE4_0": b"\x02",
131
136
  }
132
137
 
133
138
 
134
139
  VIDEO_CODEC_PARAM_PACKETIZATION_MODE_TYPES = {
135
- 'NON_INTERLEAVED': b'\x00'
140
+ "NON_INTERLEAVED": b"\x00",
136
141
  }
137
142
 
138
143
 
139
144
  VIDEO_ATTRIBUTES_TYPES = {
140
- 'IMAGE_WIDTH': b'\x01',
141
- 'IMAGE_HEIGHT': b'\x02',
142
- 'FRAME_RATE': b'\x03'
145
+ "IMAGE_WIDTH": b"\x01",
146
+ "IMAGE_HEIGHT": b"\x02",
147
+ "FRAME_RATE": b"\x03",
143
148
  }
144
149
 
145
150
 
146
- SUPPORTED_VIDEO_CONFIG_TAG = b'\x01'
151
+ SUPPORTED_VIDEO_CONFIG_TAG = b"\x01"
147
152
 
148
153
 
149
154
  SELECTED_STREAM_CONFIGURATION_TYPES = {
150
- 'SESSION': b'\x01',
151
- 'VIDEO': b'\x02',
152
- 'AUDIO': b'\x03'
155
+ "SESSION": b"\x01",
156
+ "VIDEO": b"\x02",
157
+ "AUDIO": b"\x03",
153
158
  }
154
159
 
155
160
 
156
161
  RTP_PARAM_TYPES = {
157
- 'PAYLOAD_TYPE': b'\x01',
158
- 'SYNCHRONIZATION_SOURCE': b'\x02',
159
- 'MAX_BIT_RATE': b'\x03',
160
- 'RTCP_SEND_INTERVAL': b'\x04',
161
- 'MAX_MTU': b'\x05',
162
- 'COMFORT_NOISE_PAYLOAD_TYPE': b'\x06'
162
+ "PAYLOAD_TYPE": b"\x01",
163
+ "SYNCHRONIZATION_SOURCE": b"\x02",
164
+ "MAX_BIT_RATE": b"\x03",
165
+ "RTCP_SEND_INTERVAL": b"\x04",
166
+ "MAX_MTU": b"\x05",
167
+ "COMFORT_NOISE_PAYLOAD_TYPE": b"\x06",
163
168
  }
164
169
 
165
170
 
166
171
  AUDIO_TYPES = {
167
- 'CODEC': b'\x01',
168
- 'CODEC_PARAM': b'\x02',
169
- 'RTP_PARAM': b'\x03',
170
- 'COMFORT_NOISE': b'\x04'
172
+ "CODEC": b"\x01",
173
+ "CODEC_PARAM": b"\x02",
174
+ "RTP_PARAM": b"\x03",
175
+ "COMFORT_NOISE": b"\x04",
171
176
  }
172
177
 
173
178
 
174
179
  AUDIO_CODEC_TYPES = {
175
- 'PCMU': b'\x00',
176
- 'PCMA': b'\x01',
177
- 'AACELD': b'\x02',
178
- 'OPUS': b'\x03'
180
+ "PCMU": b"\x00",
181
+ "PCMA": b"\x01",
182
+ "AACELD": b"\x02",
183
+ "OPUS": b"\x03",
179
184
  }
180
185
 
181
186
 
182
187
  AUDIO_CODEC_PARAM_TYPES = {
183
- 'CHANNEL': b'\x01',
184
- 'BIT_RATE': b'\x02',
185
- 'SAMPLE_RATE': b'\x03',
186
- 'PACKET_TIME': b'\x04'
188
+ "CHANNEL": b"\x01",
189
+ "BIT_RATE": b"\x02",
190
+ "SAMPLE_RATE": b"\x03",
191
+ "PACKET_TIME": b"\x04",
187
192
  }
188
193
 
189
194
 
190
195
  AUDIO_CODEC_PARAM_BIT_RATE_TYPES = {
191
- 'VARIABLE': b'\x00',
192
- 'CONSTANT': b'\x01'
196
+ "VARIABLE": b"\x00",
197
+ "CONSTANT": b"\x01",
193
198
  }
194
199
 
195
200
 
196
201
  AUDIO_CODEC_PARAM_SAMPLE_RATE_TYPES = {
197
- 'KHZ_8': b'\x00',
198
- 'KHZ_16': b'\x01',
199
- 'KHZ_24': b'\x02'
202
+ "KHZ_8": b"\x00",
203
+ "KHZ_16": b"\x01",
204
+ "KHZ_24": b"\x02",
200
205
  }
201
206
 
202
207
 
203
- SUPPORTED_AUDIO_CODECS_TAG = b'\x01'
204
- SUPPORTED_COMFORT_NOISE_TAG = b'\x02'
205
- SUPPORTED_AUDIO_CONFIG_TAG = b'\x02'
206
- SET_CONFIG_REQUEST_TAG = b'\x02'
207
- SESSION_ID = b'\x01'
208
+ SUPPORTED_AUDIO_CODECS_TAG = b"\x01"
209
+ SUPPORTED_COMFORT_NOISE_TAG = b"\x02"
210
+ SUPPORTED_AUDIO_CONFIG_TAG = b"\x02"
211
+ SET_CONFIG_REQUEST_TAG = b"\x02"
212
+ SESSION_ID = b"\x01"
208
213
 
209
214
 
210
- NO_SRTP = b'\x01\x01\x02\x02\x00\x03\x00'
211
- '''Configuration value for no SRTP.'''
215
+ NO_SRTP = b"\x01\x01\x02\x02\x00\x03\x00"
216
+ """Configuration value for no SRTP."""
212
217
 
213
218
 
214
219
  FFMPEG_CMD = (
215
- 'ffmpeg -re -f avfoundation -framerate {fps} -i 0:0 -threads 0 '
216
- '-vcodec libx264 -an -pix_fmt yuv420p -r {fps} -f rawvideo -tune zerolatency '
217
- '-vf scale={width}:{height} -b:v {v_max_bitrate}k -bufsize {v_max_bitrate}k '
218
- '-payload_type 99 -ssrc {v_ssrc} -f rtp '
219
- '-srtp_out_suite AES_CM_128_HMAC_SHA1_80 -srtp_out_params {v_srtp_key} '
220
- 'srtp://{address}:{v_port}?rtcpport={v_port}&'
221
- 'localrtcpport={v_port}&pkt_size=1378'
220
+ "ffmpeg -re -f avfoundation -framerate {fps} -i 0:0 -threads 0 "
221
+ "-vcodec libx264 -an -pix_fmt yuv420p -r {fps} -f rawvideo -tune zerolatency "
222
+ "-vf scale={width}:{height} -b:v {v_max_bitrate}k -bufsize {v_max_bitrate}k "
223
+ "-payload_type 99 -ssrc {v_ssrc} -f rtp "
224
+ "-srtp_out_suite AES_CM_128_HMAC_SHA1_80 -srtp_out_params {v_srtp_key} "
225
+ "srtp://{address}:{v_port}?rtcpport={v_port}&"
226
+ "localrtcpport={v_port}&pkt_size=1378"
222
227
  )
223
- '''Template for the ffmpeg command.'''
228
+ """Template for the ffmpeg command."""
224
229
 
225
230
  logger = logging.getLogger(__name__)
226
231
 
@@ -242,10 +247,10 @@ class Camera(Accessory):
242
247
  :type support_srtp: bool
243
248
  """
244
249
  if support_srtp:
245
- crypto = SRTP_CRYPTO_SUITES['AES_CM_128_HMAC_SHA1_80']
250
+ crypto = SRTP_CRYPTO_SUITES["AES_CM_128_HMAC_SHA1_80"]
246
251
  else:
247
- crypto = SRTP_CRYPTO_SUITES['NONE']
248
- return tlv.encode(RTP_CONFIG_TYPES['CRYPTO'], crypto, to_base64=True)
252
+ crypto = SRTP_CRYPTO_SUITES["NONE"]
253
+ return tlv.encode(RTP_CONFIG_TYPES["CRYPTO"], crypto, to_base64=True)
249
254
 
250
255
  @staticmethod
251
256
  def get_supported_video_stream_config(video_params):
@@ -259,31 +264,41 @@ class Camera(Accessory):
259
264
  :type video_params: dict
260
265
  """
261
266
  codec_params_tlv = tlv.encode(
262
- VIDEO_CODEC_PARAM_TYPES['PACKETIZATION_MODE'],
263
- VIDEO_CODEC_PARAM_PACKETIZATION_MODE_TYPES['NON_INTERLEAVED'])
267
+ VIDEO_CODEC_PARAM_TYPES["PACKETIZATION_MODE"],
268
+ VIDEO_CODEC_PARAM_PACKETIZATION_MODE_TYPES["NON_INTERLEAVED"],
269
+ )
264
270
 
265
- codec_params = video_params['codec']
266
- for profile in codec_params['profiles']:
267
- codec_params_tlv += \
268
- tlv.encode(VIDEO_CODEC_PARAM_TYPES['PROFILE_ID'], profile)
271
+ codec_params = video_params["codec"]
272
+ for profile in codec_params["profiles"]:
273
+ codec_params_tlv += tlv.encode(
274
+ VIDEO_CODEC_PARAM_TYPES["PROFILE_ID"], profile
275
+ )
269
276
 
270
- for level in codec_params['levels']:
271
- codec_params_tlv += \
272
- tlv.encode(VIDEO_CODEC_PARAM_TYPES['LEVEL'], level)
277
+ for level in codec_params["levels"]:
278
+ codec_params_tlv += tlv.encode(VIDEO_CODEC_PARAM_TYPES["LEVEL"], level)
273
279
 
274
- attr_tlv = b''
275
- for resolution in video_params['resolutions']:
280
+ attr_tlv = b""
281
+ for resolution in video_params["resolutions"]:
276
282
  res_tlv = tlv.encode(
277
- VIDEO_ATTRIBUTES_TYPES['IMAGE_WIDTH'], struct.pack('<H', resolution[0]),
278
- VIDEO_ATTRIBUTES_TYPES['IMAGE_HEIGHT'], struct.pack('<H', resolution[1]),
279
- VIDEO_ATTRIBUTES_TYPES['FRAME_RATE'], struct.pack('<H', resolution[2]))
280
- attr_tlv += tlv.encode(VIDEO_TYPES['ATTRIBUTES'], res_tlv)
283
+ VIDEO_ATTRIBUTES_TYPES["IMAGE_WIDTH"],
284
+ struct.pack("<H", resolution[0]),
285
+ VIDEO_ATTRIBUTES_TYPES["IMAGE_HEIGHT"],
286
+ struct.pack("<H", resolution[1]),
287
+ VIDEO_ATTRIBUTES_TYPES["FRAME_RATE"],
288
+ struct.pack("<H", resolution[2]),
289
+ )
290
+ attr_tlv += tlv.encode(VIDEO_TYPES["ATTRIBUTES"], res_tlv)
281
291
 
282
- config_tlv = tlv.encode(VIDEO_TYPES['CODEC'], VIDEO_CODEC_TYPES['H264'],
283
- VIDEO_TYPES['CODEC_PARAM'], codec_params_tlv)
292
+ config_tlv = tlv.encode(
293
+ VIDEO_TYPES["CODEC"],
294
+ VIDEO_CODEC_TYPES["H264"],
295
+ VIDEO_TYPES["CODEC_PARAM"],
296
+ codec_params_tlv,
297
+ )
284
298
 
285
- return tlv.encode(SUPPORTED_VIDEO_CONFIG_TAG, config_tlv + attr_tlv,
286
- to_base64=True)
299
+ return tlv.encode(
300
+ SUPPORTED_VIDEO_CONFIG_TAG, config_tlv + attr_tlv, to_base64=True
301
+ )
287
302
 
288
303
  @staticmethod
289
304
  def get_supported_audio_stream_config(audio_params):
@@ -299,60 +314,71 @@ class Camera(Accessory):
299
314
  :type audio_params: dict
300
315
  """
301
316
  has_supported_codec = False
302
- configs = b''
303
- for codec_param in audio_params['codecs']:
304
- param_type = codec_param['type']
305
- if param_type == 'OPUS':
317
+ configs = b""
318
+ for codec_param in audio_params["codecs"]:
319
+ param_type = codec_param["type"]
320
+ if param_type == "OPUS":
306
321
  has_supported_codec = True
307
- codec = AUDIO_CODEC_TYPES['OPUS']
308
- bitrate = AUDIO_CODEC_PARAM_BIT_RATE_TYPES['VARIABLE']
309
- elif param_type == 'AAC-eld':
322
+ codec = AUDIO_CODEC_TYPES["OPUS"]
323
+ bitrate = AUDIO_CODEC_PARAM_BIT_RATE_TYPES["VARIABLE"]
324
+ elif param_type == "AAC-eld":
310
325
  has_supported_codec = True
311
- codec = AUDIO_CODEC_TYPES['AACELD']
312
- bitrate = AUDIO_CODEC_PARAM_BIT_RATE_TYPES['VARIABLE']
326
+ codec = AUDIO_CODEC_TYPES["AACELD"]
327
+ bitrate = AUDIO_CODEC_PARAM_BIT_RATE_TYPES["VARIABLE"]
313
328
  else:
314
- logger.warning('Unsupported codec %s', param_type)
329
+ logger.warning("Unsupported codec %s", param_type)
315
330
  continue
316
331
 
317
- param_samplerate = codec_param['samplerate']
332
+ param_samplerate = codec_param["samplerate"]
318
333
  if param_samplerate == 8:
319
- samplerate = AUDIO_CODEC_PARAM_SAMPLE_RATE_TYPES['KHZ_8']
334
+ samplerate = AUDIO_CODEC_PARAM_SAMPLE_RATE_TYPES["KHZ_8"]
320
335
  elif param_samplerate == 16:
321
- samplerate = AUDIO_CODEC_PARAM_SAMPLE_RATE_TYPES['KHZ_16']
336
+ samplerate = AUDIO_CODEC_PARAM_SAMPLE_RATE_TYPES["KHZ_16"]
322
337
  elif param_samplerate == 24:
323
- samplerate = AUDIO_CODEC_PARAM_SAMPLE_RATE_TYPES['KHZ_24']
338
+ samplerate = AUDIO_CODEC_PARAM_SAMPLE_RATE_TYPES["KHZ_24"]
324
339
  else:
325
- logger.warning('Unsupported sample rate %s', param_samplerate)
340
+ logger.warning("Unsupported sample rate %s", param_samplerate)
326
341
  continue
327
342
 
328
- param_tlv = tlv.encode(AUDIO_CODEC_PARAM_TYPES['CHANNEL'], b'\x01',
329
- AUDIO_CODEC_PARAM_TYPES['BIT_RATE'], bitrate,
330
- AUDIO_CODEC_PARAM_TYPES['SAMPLE_RATE'], samplerate)
331
- config_tlv = tlv.encode(AUDIO_TYPES['CODEC'], codec,
332
- AUDIO_TYPES['CODEC_PARAM'], param_tlv)
343
+ param_tlv = tlv.encode(
344
+ AUDIO_CODEC_PARAM_TYPES["CHANNEL"],
345
+ b"\x01",
346
+ AUDIO_CODEC_PARAM_TYPES["BIT_RATE"],
347
+ bitrate,
348
+ AUDIO_CODEC_PARAM_TYPES["SAMPLE_RATE"],
349
+ samplerate,
350
+ )
351
+ config_tlv = tlv.encode(
352
+ AUDIO_TYPES["CODEC"], codec, AUDIO_TYPES["CODEC_PARAM"], param_tlv
353
+ )
333
354
  configs += tlv.encode(SUPPORTED_AUDIO_CODECS_TAG, config_tlv)
334
355
 
335
356
  if not has_supported_codec:
336
- logger.warning('Client does not support any audio codec that iOS supports.')
357
+ logger.warning("Client does not support any audio codec that iOS supports.")
337
358
 
338
- codec = AUDIO_CODEC_TYPES['OPUS']
339
- bitrate = AUDIO_CODEC_PARAM_BIT_RATE_TYPES['VARIABLE']
340
- samplerate = AUDIO_CODEC_PARAM_SAMPLE_RATE_TYPES['KHZ_24']
359
+ codec = AUDIO_CODEC_TYPES["OPUS"]
360
+ bitrate = AUDIO_CODEC_PARAM_BIT_RATE_TYPES["VARIABLE"]
361
+ samplerate = AUDIO_CODEC_PARAM_SAMPLE_RATE_TYPES["KHZ_24"]
341
362
 
342
363
  param_tlv = tlv.encode(
343
- AUDIO_CODEC_PARAM_TYPES['CHANNEL'], b'\x01',
344
- AUDIO_CODEC_PARAM_TYPES['BIT_RATE'], bitrate,
345
- AUDIO_CODEC_PARAM_TYPES['SAMPLE_RATE'], samplerate)
364
+ AUDIO_CODEC_PARAM_TYPES["CHANNEL"],
365
+ b"\x01",
366
+ AUDIO_CODEC_PARAM_TYPES["BIT_RATE"],
367
+ bitrate,
368
+ AUDIO_CODEC_PARAM_TYPES["SAMPLE_RATE"],
369
+ samplerate,
370
+ )
346
371
 
347
- config_tlv = tlv.encode(AUDIO_TYPES['CODEC'], codec,
348
- AUDIO_TYPES['CODEC_PARAM'], param_tlv)
372
+ config_tlv = tlv.encode(
373
+ AUDIO_TYPES["CODEC"], codec, AUDIO_TYPES["CODEC_PARAM"], param_tlv
374
+ )
349
375
 
350
376
  configs = tlv.encode(SUPPORTED_AUDIO_CODECS_TAG, config_tlv)
351
377
 
352
- comfort_noise = byte_bool(
353
- audio_params.get('comfort_noise', False))
378
+ comfort_noise = byte_bool(audio_params.get("comfort_noise", False))
354
379
  audio_config = to_base64_str(
355
- configs + tlv.encode(SUPPORTED_COMFORT_NOISE_TAG, comfort_noise))
380
+ configs + tlv.encode(SUPPORTED_COMFORT_NOISE_TAG, comfort_noise)
381
+ )
356
382
  return audio_config
357
383
 
358
384
  def __init__(self, options, *args, **kwargs):
@@ -402,6 +428,13 @@ class Camera(Accessory):
402
428
 
403
429
  Additional optional values are:
404
430
  - srtp - boolean, defaults to False. Whether the camera supports SRTP.
431
+ - talkback - boolean, defaults to False. Whether the camera supports
432
+ receiving two-way ("talkback") audio from the controller during a
433
+ live view session. Requires the optional ``pylibsrtp`` dependency
434
+ (``pip install HAP-python[Talkback]``). When enabled, a "Speaker"
435
+ service is added so that HAP clients know the accessory supports
436
+ it, and :meth:`talkback_audio_received` is called with the
437
+ received audio for each session that negotiates it.
405
438
  - start_stream_cmd - string specifying the command to be executed to start
406
439
  the stream. The string can contain the keywords, corresponding to the
407
440
  video and audio configuration that was negotiated between the camera
@@ -409,28 +442,49 @@ class Camera(Accessory):
409
442
 
410
443
  :type options: ``dict``
411
444
  """
412
- self.has_srtp = options.get('srtp', False)
413
- self.start_stream_cmd = options.get('start_stream_cmd', FFMPEG_CMD)
445
+ self.has_srtp = options.get("srtp", False)
446
+ self.support_talkback = options.get("talkback", False)
447
+ if self.support_talkback and not talkback_available():
448
+ raise ValueError(
449
+ "The 'talkback' option requires the optional 'pylibsrtp' "
450
+ "dependency. Install it with: pip install HAP-python[Talkback]"
451
+ )
452
+ self.start_stream_cmd = options.get("start_stream_cmd", FFMPEG_CMD)
414
453
 
415
- self.stream_address = options['address']
454
+ self.stream_address = options["address"]
416
455
  try:
417
456
  ipaddress.IPv4Address(self.stream_address)
418
- self.stream_address_isv6 = b'\x00'
457
+ self.stream_address_isv6 = b"\x00"
419
458
  except ValueError:
420
- self.stream_address_isv6 = b'\x01'
459
+ self.stream_address_isv6 = b"\x01"
421
460
  self.sessions = {}
422
461
 
423
462
  super().__init__(*args, **kwargs)
424
463
 
425
- self.add_preload_service('Microphone')
464
+ self.add_preload_service("Microphone")
465
+ if self.support_talkback:
466
+ self.add_preload_service("Speaker").configure_char("Mute", value=False)
426
467
  self._streaming_status = []
427
468
  self._management = []
428
- self._setup_stream_management(options)
469
+ # All HKSV state defaults are initialized before any setup runs so the
470
+ # setup methods below never follow (and reset) them.
471
+ self._status_active_char = None
472
+ self._recording_service = None
473
+ self._selected_recording_config = None
474
+ self._motion_detected_char = None
475
+ self._hds_listener = None
476
+ self._hds_connections = set()
477
+ if options.get("video"):
478
+ self._setup_stream_management(options)
479
+ # Classic HomeKit Secure Video recording (HDS + fragmented MP4).
480
+ if options.get("recording"):
481
+ self._setup_recording_management(options)
429
482
 
430
483
  @property
431
484
  def streaming_status(self):
432
485
  """For backwards compatibility."""
433
- return self._streaming_status[0]
486
+ # A recording-only camera has no RTP stream management service.
487
+ return self._streaming_status[0] if self._streaming_status else None
434
488
 
435
489
  def _setup_stream_management(self, options):
436
490
  """Create stream management."""
@@ -441,7 +495,13 @@ class Camera(Accessory):
441
495
 
442
496
  def _create_stream_management(self, stream_idx, options):
443
497
  """Create a stream management service."""
444
- management = self.add_preload_service("CameraRTPStreamManagement", unique_id=stream_idx)
498
+ management = self.add_preload_service(
499
+ "CameraRTPStreamManagement", unique_id=stream_idx, chars=["Active"]
500
+ )
501
+ # HAP-NodeJS exposes an Active (0x0B0) characteristic on every stream
502
+ # management service (value 1 = active); iOS' camera validation expects
503
+ # it, and it is required for Secure Video eligibility.
504
+ management.configure_char("Active", value=1)
445
505
  management.configure_char(
446
506
  "StreamingStatus",
447
507
  getter_callback=lambda: self._get_streaming_status(stream_idx),
@@ -470,6 +530,203 @@ class Camera(Accessory):
470
530
  )
471
531
  return management
472
532
 
533
+ def _default_recording_configs(self, options):
534
+ """Derive supported recording configurations from the streaming options.
535
+
536
+ A widely-compatible default: H.264 (Baseline/Main/High, levels 3.1/3.2/
537
+ 4.0) at the streaming resolutions, AAC-LC audio. Accessories can override
538
+ this to advertise their own recording capabilities.
539
+ """
540
+ video_opts = options.get("video") or {}
541
+ resolutions = video_opts.get("resolutions") or [[1920, 1080, 30]]
542
+ video = [
543
+ hksv_recording.VideoCodecConfiguration(
544
+ codec_type=hksv_recording.VideoCodecType.H264,
545
+ profile=[
546
+ VIDEO_CODEC_PARAM_PROFILE_ID_TYPES["BASELINE"][0],
547
+ VIDEO_CODEC_PARAM_PROFILE_ID_TYPES["MAIN"][0],
548
+ VIDEO_CODEC_PARAM_PROFILE_ID_TYPES["HIGH"][0],
549
+ ],
550
+ level=[
551
+ VIDEO_CODEC_PARAM_LEVEL_TYPES["TYPE3_1"][0],
552
+ VIDEO_CODEC_PARAM_LEVEL_TYPES["TYPE3_2"][0],
553
+ VIDEO_CODEC_PARAM_LEVEL_TYPES["TYPE4_0"][0],
554
+ ],
555
+ bitrate_kbps=2000,
556
+ iframe_interval_ms=4000,
557
+ attributes=[
558
+ hksv_recording.VideoAttributes(width, height, fps)
559
+ for width, height, fps in resolutions
560
+ ],
561
+ )
562
+ ]
563
+ audio = [hksv_recording.AudioCodecConfiguration()]
564
+ general = hksv_recording.SupportedRecordingConfiguration()
565
+ return general, video, audio
566
+
567
+ def _setup_recording_management(self, options):
568
+ """Create the Camera Recording Management service (classic HKSV).
569
+
570
+ Advertises the supported general/video/audio recording configurations
571
+ and accepts the controller's selection. Recording stays inactive
572
+ (Active=0) unless the ``recording`` option enables it; the fragment
573
+ data flow over HDS is wired by the recording transport.
574
+ """
575
+ # HKSV requires the Camera Operating Mode service (0000021A); the
576
+ # controller validates its presence before enabling recording.
577
+ operating_mode = self.add_preload_service(
578
+ "CameraOperatingMode", chars=["PeriodicSnapshotsActive"]
579
+ )
580
+ operating_mode.configure_char("EventSnapshotsActive", value=1)
581
+ operating_mode.configure_char("HomeKitCameraActive", value=1)
582
+ operating_mode.configure_char("PeriodicSnapshotsActive", value=1)
583
+
584
+ # HKSV records on an event trigger; the camera owns a motion sensor and
585
+ # links it (and the data stream transport) to the recording management.
586
+ motion = self.add_preload_service("MotionSensor", chars=["StatusActive"])
587
+ self._motion_detected_char = motion.configure_char(
588
+ "MotionDetected", value=False
589
+ )
590
+ # HAP-NodeJS marks the HKSV event-trigger sensor as active; iOS expects it.
591
+ motion.configure_char("StatusActive", value=True)
592
+
593
+ general, video, audio = self._default_recording_configs(options)
594
+ service = self.add_preload_service(
595
+ "CameraRecordingManagement", chars=["RecordingAudioActive"]
596
+ )
597
+ service.add_linked_service(motion)
598
+ service.configure_char("Active", value=0)
599
+ service.configure_char(
600
+ "RecordingAudioActive", value=1 if options.get("recording_audio") else 0
601
+ )
602
+ service.configure_char(
603
+ "SupportedCameraRecordingConfiguration",
604
+ value=to_base64_str(general.encode()),
605
+ )
606
+ service.configure_char(
607
+ "SupportedVideoRecordingConfiguration",
608
+ value=to_base64_str(hksv_recording.encode_supported_video(video)),
609
+ )
610
+ service.configure_char(
611
+ "SupportedAudioRecordingConfiguration",
612
+ value=to_base64_str(hksv_recording.encode_supported_audio(audio)),
613
+ )
614
+ service.configure_char(
615
+ "SelectedCameraRecordingConfiguration",
616
+ setter_callback=self.set_selected_recording_configuration,
617
+ )
618
+ self._recording_service = service
619
+ self._setup_data_stream_transport()
620
+
621
+ def _setup_data_stream_transport(self):
622
+ """Create the Data Stream Transport Management service used by HDS.
623
+
624
+ SetupDataStreamTransport needs the HAP session shared secret, so its
625
+ setter receives the sender's client address to look the secret up.
626
+ """
627
+ transport = self.add_preload_service("DataStreamTransportManagement")
628
+ transport.configure_char("Version", value="1.0")
629
+ transport.configure_char(
630
+ "SupportedDataStreamTransportConfiguration",
631
+ value=to_base64_str(self._supported_data_stream_transport()),
632
+ )
633
+ transport.configure_char(
634
+ "SetupDataStreamTransport",
635
+ setter_callback=self.set_data_stream_transport,
636
+ )
637
+ # HKSV requires the recording management service to link the data stream
638
+ # transport it records over; without the link the controller rejects
639
+ # recording during validation, before writing any configuration.
640
+ self._recording_service.add_linked_service(transport)
641
+
642
+ @staticmethod
643
+ def _supported_data_stream_transport():
644
+ # A single supported transport configuration: TCP.
645
+ transport_configuration = tlv.encode(b"\x01", hds.TRANSPORT_TYPE_TCP)
646
+ return tlv.encode(b"\x01", transport_configuration)
647
+
648
+ async def _ensure_hds_listener(self):
649
+ if self._hds_listener is None:
650
+ self._hds_listener = hds_server.HDSListener()
651
+ self._hds_listener.on_connection = self._on_hds_connection
652
+ await self._hds_listener.start()
653
+
654
+ def _on_hds_connection(self, connection):
655
+ self._hds_connections.add(connection)
656
+ connection.add_close_callback(self._hds_connections.discard)
657
+ hds_recording.RecordingStreamManager(connection, self._recording_delegate)
658
+
659
+ def set_data_stream_transport(self, value, sender_client_addr=None):
660
+ """Handle a write to SetupDataStreamTransport (HDS session setup).
661
+
662
+ SetupDataStreamTransport is a write-response ('wr') characteristic: the
663
+ controller writes with ``r: true`` and reads the encoded setup response
664
+ (TCP listening port + accessory key salt) straight back from the write
665
+ response. That means the value MUST be RETURNED from the setter so the
666
+ HAP layer includes it in the write response — setting it on the
667
+ characteristic is not delivered to the controller and leaves it without
668
+ the port, so it can never open the HDS connection.
669
+ """
670
+ request = hds.SetupRequest.decode(base64_to_bytes(value))
671
+ shared_secret = self.driver.session_shared_keys.get(sender_client_addr)
672
+ if shared_secret is None or self._hds_listener is None:
673
+ response = hds.encode_setup_response(
674
+ 0, b"", status=hds.SETUP_STATUS_GENERIC_ERROR
675
+ )
676
+ else:
677
+ accessory_salt = self._hds_listener.register_transport(
678
+ shared_secret, request.controller_key_salt
679
+ )
680
+ response = hds.encode_setup_response(
681
+ self._hds_listener.port, accessory_salt
682
+ )
683
+ return to_base64_str(response)
684
+
685
+ async def _recording_delegate(self, stream_id):
686
+ """Yield recording fragments for ``stream_id``.
687
+
688
+ Override ``handle_recording_stream`` to produce the fragmented MP4
689
+ packets; this adapter exists so the transport can await an async
690
+ generator.
691
+ """
692
+ async for packet in self.handle_recording_stream(stream_id):
693
+ yield packet
694
+
695
+ async def handle_recording_stream(self, stream_id):
696
+ """Produce the fragmented-MP4 recording for ``stream_id``.
697
+
698
+ Override to yield :class:`pyhap.hds_recording.RecordingPacket` objects,
699
+ the first being the MP4 initialization segment. The default yields
700
+ nothing (no recording).
701
+ """
702
+ return
703
+ yield # pragma: no cover - makes this an async generator
704
+
705
+ @property
706
+ def selected_recording_configuration(self):
707
+ """The controller's selected recording configuration, if any."""
708
+ return self._selected_recording_config
709
+
710
+ def set_selected_recording_configuration(self, value):
711
+ """Handle a write to Selected Camera Recording Configuration (spec HKSV)."""
712
+ self._selected_recording_config = (
713
+ hksv_recording.SelectedRecordingConfiguration.decode(base64_to_bytes(value))
714
+ )
715
+ self.recording_configuration_selected(self._selected_recording_config)
716
+
717
+ def recording_configuration_selected(self, configuration):
718
+ """React to the controller selecting a recording configuration. Override."""
719
+
720
+ def set_motion_detected(self, detected):
721
+ """Fire (``True``) or clear (``False``) the recording motion trigger.
722
+
723
+ This is the entry point an integration calls when its own motion
724
+ detector changes state: it drives the HKSV event-trigger MotionSensor,
725
+ which is what makes the Home Hub start (and later finish) a recording.
726
+ """
727
+ if self._motion_detected_char is not None:
728
+ self._motion_detected_char.set_value(bool(detected))
729
+
473
730
  async def _start_stream(self, objs, reconfigure): # pylint: disable=unused-argument
474
731
  """Start or reconfigure video streaming for the given session.
475
732
 
@@ -484,105 +741,130 @@ class Camera(Accessory):
484
741
  started.
485
742
  :type reconfigure: bool
486
743
  """
487
- video_tlv = objs.get(SELECTED_STREAM_CONFIGURATION_TYPES['VIDEO'])
488
- audio_tlv = objs.get(SELECTED_STREAM_CONFIGURATION_TYPES['AUDIO'])
744
+ video_tlv = objs.get(SELECTED_STREAM_CONFIGURATION_TYPES["VIDEO"])
745
+ audio_tlv = objs.get(SELECTED_STREAM_CONFIGURATION_TYPES["AUDIO"])
489
746
 
490
747
  opts = {}
491
748
 
492
749
  if video_tlv:
493
750
  video_objs = tlv.decode(video_tlv)
494
751
 
495
- video_codec_params = video_objs.get(VIDEO_TYPES['CODEC_PARAM'])
752
+ video_codec_params = video_objs.get(VIDEO_TYPES["CODEC_PARAM"])
496
753
  if video_codec_params:
497
754
  video_codec_param_objs = tlv.decode(video_codec_params)
498
- opts['v_profile_id'] = \
499
- video_codec_param_objs[VIDEO_CODEC_PARAM_TYPES['PROFILE_ID']]
500
- opts['v_level'] = \
501
- video_codec_param_objs[VIDEO_CODEC_PARAM_TYPES['LEVEL']]
502
-
503
- video_attrs = video_objs.get(VIDEO_TYPES['ATTRIBUTES'])
755
+ opts["v_profile_id"] = video_codec_param_objs[
756
+ VIDEO_CODEC_PARAM_TYPES["PROFILE_ID"]
757
+ ]
758
+ opts["v_level"] = video_codec_param_objs[
759
+ VIDEO_CODEC_PARAM_TYPES["LEVEL"]
760
+ ]
761
+
762
+ video_attrs = video_objs.get(VIDEO_TYPES["ATTRIBUTES"])
504
763
  if video_attrs:
505
764
  video_attr_objs = tlv.decode(video_attrs)
506
- opts['width'] = struct.unpack('<H',
507
- video_attr_objs[VIDEO_ATTRIBUTES_TYPES['IMAGE_WIDTH']])[0]
508
- opts['height'] = struct.unpack('<H',
509
- video_attr_objs[VIDEO_ATTRIBUTES_TYPES['IMAGE_HEIGHT']])[0]
510
- opts['fps'] = struct.unpack('<B',
511
- video_attr_objs[VIDEO_ATTRIBUTES_TYPES['FRAME_RATE']])[0]
512
-
513
- video_rtp_param = video_objs.get(VIDEO_TYPES['RTP_PARAM'])
765
+ opts["width"] = struct.unpack(
766
+ "<H", video_attr_objs[VIDEO_ATTRIBUTES_TYPES["IMAGE_WIDTH"]]
767
+ )[0]
768
+ opts["height"] = struct.unpack(
769
+ "<H", video_attr_objs[VIDEO_ATTRIBUTES_TYPES["IMAGE_HEIGHT"]]
770
+ )[0]
771
+ opts["fps"] = struct.unpack(
772
+ "<B", video_attr_objs[VIDEO_ATTRIBUTES_TYPES["FRAME_RATE"]]
773
+ )[0]
774
+
775
+ video_rtp_param = video_objs.get(VIDEO_TYPES["RTP_PARAM"])
514
776
  if video_rtp_param:
515
777
  video_rtp_param_objs = tlv.decode(video_rtp_param)
516
- if RTP_PARAM_TYPES['SYNCHRONIZATION_SOURCE'] in video_rtp_param_objs:
517
- opts['v_ssrc'] = struct.unpack('<I',
778
+ if RTP_PARAM_TYPES["SYNCHRONIZATION_SOURCE"] in video_rtp_param_objs:
779
+ opts["v_ssrc"] = struct.unpack(
780
+ "<I",
518
781
  video_rtp_param_objs.get(
519
- RTP_PARAM_TYPES['SYNCHRONIZATION_SOURCE']))[0]
520
- if RTP_PARAM_TYPES['PAYLOAD_TYPE'] in video_rtp_param_objs:
521
- opts['v_payload_type'] = \
522
- video_rtp_param_objs.get(RTP_PARAM_TYPES['PAYLOAD_TYPE'])
523
- if RTP_PARAM_TYPES['MAX_BIT_RATE'] in video_rtp_param_objs:
524
- opts['v_max_bitrate'] = struct.unpack('<H',
525
- video_rtp_param_objs.get(RTP_PARAM_TYPES['MAX_BIT_RATE']))[0]
526
- if RTP_PARAM_TYPES['RTCP_SEND_INTERVAL'] in video_rtp_param_objs:
527
- opts['v_rtcp_interval'] = struct.unpack('<f',
528
- video_rtp_param_objs.get(RTP_PARAM_TYPES['RTCP_SEND_INTERVAL']))[0]
529
- if RTP_PARAM_TYPES['MAX_MTU'] in video_rtp_param_objs:
530
- opts['v_max_mtu'] = video_rtp_param_objs.get(RTP_PARAM_TYPES['MAX_MTU'])
782
+ RTP_PARAM_TYPES["SYNCHRONIZATION_SOURCE"]
783
+ ),
784
+ )[0]
785
+ if RTP_PARAM_TYPES["PAYLOAD_TYPE"] in video_rtp_param_objs:
786
+ opts["v_payload_type"] = video_rtp_param_objs.get(
787
+ RTP_PARAM_TYPES["PAYLOAD_TYPE"]
788
+ )
789
+ if RTP_PARAM_TYPES["MAX_BIT_RATE"] in video_rtp_param_objs:
790
+ opts["v_max_bitrate"] = struct.unpack(
791
+ "<H", video_rtp_param_objs.get(RTP_PARAM_TYPES["MAX_BIT_RATE"])
792
+ )[0]
793
+ if RTP_PARAM_TYPES["RTCP_SEND_INTERVAL"] in video_rtp_param_objs:
794
+ opts["v_rtcp_interval"] = struct.unpack(
795
+ "<f",
796
+ video_rtp_param_objs.get(RTP_PARAM_TYPES["RTCP_SEND_INTERVAL"]),
797
+ )[0]
798
+ if RTP_PARAM_TYPES["MAX_MTU"] in video_rtp_param_objs:
799
+ opts["v_max_mtu"] = video_rtp_param_objs.get(
800
+ RTP_PARAM_TYPES["MAX_MTU"]
801
+ )
531
802
 
532
803
  if audio_tlv:
533
804
  audio_objs = tlv.decode(audio_tlv)
534
805
 
535
- opts['a_codec'] = audio_objs[AUDIO_TYPES['CODEC']]
536
- audio_codec_param_objs = tlv.decode(
537
- audio_objs[AUDIO_TYPES['CODEC_PARAM']])
538
- audio_rtp_param_objs = tlv.decode(
539
- audio_objs[AUDIO_TYPES['RTP_PARAM']])
540
- opts['a_comfort_noise'] = audio_objs[AUDIO_TYPES['COMFORT_NOISE']]
541
-
542
- opts['a_channel'] = \
543
- audio_codec_param_objs[AUDIO_CODEC_PARAM_TYPES['CHANNEL']][0]
544
- opts['a_bitrate'] = struct.unpack('?',
545
- audio_codec_param_objs[AUDIO_CODEC_PARAM_TYPES['BIT_RATE']])[0]
546
- opts['a_sample_rate'] = 8 * (
547
- 1 + audio_codec_param_objs[AUDIO_CODEC_PARAM_TYPES['SAMPLE_RATE']][0])
548
- opts['a_packet_time'] = struct.unpack('<B',
549
- audio_codec_param_objs[AUDIO_CODEC_PARAM_TYPES['PACKET_TIME']])[0]
550
-
551
- opts['a_ssrc'] = struct.unpack('<I',
552
- audio_rtp_param_objs[RTP_PARAM_TYPES['SYNCHRONIZATION_SOURCE']])[0]
553
- opts['a_payload_type'] = audio_rtp_param_objs[RTP_PARAM_TYPES['PAYLOAD_TYPE']]
554
- opts['a_max_bitrate'] = struct.unpack('<H',
555
- audio_rtp_param_objs[RTP_PARAM_TYPES['MAX_BIT_RATE']])[0]
556
- opts['a_rtcp_interval'] = struct.unpack('<f',
557
- audio_rtp_param_objs[RTP_PARAM_TYPES['RTCP_SEND_INTERVAL']])[0]
558
- opts['a_comfort_payload_type'] = \
559
- audio_rtp_param_objs[RTP_PARAM_TYPES['COMFORT_NOISE_PAYLOAD_TYPE']]
560
-
561
- session_objs = tlv.decode(objs[SELECTED_STREAM_CONFIGURATION_TYPES['SESSION']])
562
- session_id = UUID(bytes=session_objs[SETUP_TYPES['SESSION_ID']])
806
+ opts["a_codec"] = audio_objs[AUDIO_TYPES["CODEC"]]
807
+ audio_codec_param_objs = tlv.decode(audio_objs[AUDIO_TYPES["CODEC_PARAM"]])
808
+ audio_rtp_param_objs = tlv.decode(audio_objs[AUDIO_TYPES["RTP_PARAM"]])
809
+ opts["a_comfort_noise"] = audio_objs[AUDIO_TYPES["COMFORT_NOISE"]]
810
+
811
+ opts["a_channel"] = audio_codec_param_objs[
812
+ AUDIO_CODEC_PARAM_TYPES["CHANNEL"]
813
+ ][0]
814
+ opts["a_bitrate"] = struct.unpack(
815
+ "?", audio_codec_param_objs[AUDIO_CODEC_PARAM_TYPES["BIT_RATE"]]
816
+ )[0]
817
+ opts["a_sample_rate"] = 8 * (
818
+ 1 + audio_codec_param_objs[AUDIO_CODEC_PARAM_TYPES["SAMPLE_RATE"]][0]
819
+ )
820
+ opts["a_packet_time"] = struct.unpack(
821
+ "<B", audio_codec_param_objs[AUDIO_CODEC_PARAM_TYPES["PACKET_TIME"]]
822
+ )[0]
823
+
824
+ opts["a_ssrc"] = struct.unpack(
825
+ "<I", audio_rtp_param_objs[RTP_PARAM_TYPES["SYNCHRONIZATION_SOURCE"]]
826
+ )[0]
827
+ opts["a_payload_type"] = audio_rtp_param_objs[
828
+ RTP_PARAM_TYPES["PAYLOAD_TYPE"]
829
+ ]
830
+ opts["a_max_bitrate"] = struct.unpack(
831
+ "<H", audio_rtp_param_objs[RTP_PARAM_TYPES["MAX_BIT_RATE"]]
832
+ )[0]
833
+ opts["a_rtcp_interval"] = struct.unpack(
834
+ "<f", audio_rtp_param_objs[RTP_PARAM_TYPES["RTCP_SEND_INTERVAL"]]
835
+ )[0]
836
+ opts["a_comfort_payload_type"] = audio_rtp_param_objs[
837
+ RTP_PARAM_TYPES["COMFORT_NOISE_PAYLOAD_TYPE"]
838
+ ]
839
+
840
+ session_objs = tlv.decode(objs[SELECTED_STREAM_CONFIGURATION_TYPES["SESSION"]])
841
+ session_id = UUID(bytes=session_objs[SETUP_TYPES["SESSION_ID"]])
563
842
  session_info = self.sessions[session_id]
564
- stream_idx = session_info['stream_idx']
843
+ stream_idx = session_info["stream_idx"]
565
844
 
566
845
  opts.update(session_info)
567
- success = await self.reconfigure_stream(session_info, opts) if reconfigure \
846
+ success = (
847
+ await self.reconfigure_stream(session_info, opts)
848
+ if reconfigure
568
849
  else await self.start_stream(session_info, opts)
850
+ )
569
851
 
570
852
  if success:
571
- self._streaming_status[stream_idx] = STREAMING_STATUS['STREAMING']
853
+ self._streaming_status[stream_idx] = STREAMING_STATUS["STREAMING"]
572
854
  else:
573
855
  logger.error(
574
- '[%s] Failed to start/reconfigure stream, deleting session.',
575
- session_id
856
+ "[%s] Failed to start/reconfigure stream, deleting session.", session_id
576
857
  )
858
+ self._close_talkback(session_info)
577
859
  del self.sessions[session_id]
578
- self._streaming_status[stream_idx] = STREAMING_STATUS['AVAILABLE']
860
+ self._streaming_status[stream_idx] = STREAMING_STATUS["AVAILABLE"]
579
861
 
580
862
  def _get_streaming_status(self, stream_idx):
581
863
  """Get the streaming status in TLV format.
582
864
 
583
865
  Called when iOS reads the StreaminStatus ``Characteristic``.
584
866
  """
585
- return tlv.encode(b'\x01', self._streaming_status[stream_idx], to_base64=True)
867
+ return tlv.encode(b"\x01", self._streaming_status[stream_idx], to_base64=True)
586
868
 
587
869
  async def _stop_stream(self, objs):
588
870
  """Stop the stream for the specified session.
@@ -592,23 +874,66 @@ class Camera(Accessory):
592
874
  :param objs: TLV-decoded SelectedRTPStreamConfiguration value.
593
875
  :param objs: ``dict``
594
876
  """
595
- session_objs = tlv.decode(objs[SELECTED_STREAM_CONFIGURATION_TYPES['SESSION']])
596
- session_id = UUID(bytes=session_objs[SETUP_TYPES['SESSION_ID']])
877
+ session_objs = tlv.decode(objs[SELECTED_STREAM_CONFIGURATION_TYPES["SESSION"]])
878
+ session_id = UUID(bytes=session_objs[SETUP_TYPES["SESSION_ID"]])
597
879
 
598
880
  session_info = self.sessions.get(session_id)
599
881
  if not session_info:
600
882
  logger.error(
601
- 'Requested to stop stream for session %s, but no '
602
- 'such session was found',
603
- session_id
883
+ "Requested to stop stream for session %s, but no "
884
+ "such session was found",
885
+ session_id,
604
886
  )
605
887
  return
606
888
 
607
- stream_idx = session_info['stream_idx']
889
+ stream_idx = session_info["stream_idx"]
608
890
  await self.stop_stream(session_info)
891
+ self._close_talkback(session_info)
609
892
  del self.sessions[session_id]
610
893
 
611
- self._streaming_status[stream_idx] = STREAMING_STATUS['AVAILABLE']
894
+ self._streaming_status[stream_idx] = STREAMING_STATUS["AVAILABLE"]
895
+
896
+ @staticmethod
897
+ def _close_talkback(session_info):
898
+ """Stop the talkback audio receiver for a session, if any."""
899
+ audio_backchannel = session_info.pop("audio_backchannel", None)
900
+ if audio_backchannel is not None:
901
+ audio_backchannel.stop()
902
+
903
+ def _talkback_payload_received(self, session_id, payload: bytes) -> None:
904
+ """Dispatch a received talkback RTP payload to the accessory implementation.
905
+
906
+ Called from the :class:`~pyhap.camera_talkback.TalkbackReceiver`
907
+ background thread, so this hops back onto the accessory driver's event
908
+ loop before calling the (synchronous) public callback, to keep
909
+ :meth:`talkback_audio_received` easy to implement without every caller
910
+ having to worry about thread-safety.
911
+ """
912
+ loop = getattr(self.driver, "loop", None)
913
+ if loop is None:
914
+ logger.warning(
915
+ "Dropping talkback audio packet: driver event loop is not available."
916
+ )
917
+ return
918
+ loop.call_soon_threadsafe(self.talkback_audio_received, session_id, payload)
919
+
920
+ def talkback_audio_received(
921
+ self, session_id, payload: bytes
922
+ ) -> None: # pylint: disable=unused-argument
923
+ """Handle received two-way ("talkback") audio for a streaming session.
924
+
925
+ Only called for sessions of accessories constructed with the
926
+ ``talkback`` option enabled (see ``__init__``). Override to consume the
927
+ received audio, e.g. decode it (the codec is whichever was negotiated,
928
+ see ``a_codec`` in the stream configuration passed to
929
+ :meth:`start_stream`) and play it out through a speaker.
930
+
931
+ :param session_id: The session ID this audio belongs to.
932
+ :type session_id: :class:`~uuid.UUID`
933
+ :param payload: The RTP payload of one received packet, still encoded
934
+ with the negotiated audio codec (not decoded by pyhap).
935
+ :type payload: ``bytes``
936
+ """
612
937
 
613
938
  def set_selected_stream_configuration(self, value):
614
939
  """Set the selected stream configuration.
@@ -621,17 +946,17 @@ class Camera(Accessory):
621
946
  :param value: base64-encoded selected configuration in TLV format
622
947
  :type value: ``str``
623
948
  """
624
- logger.debug('set_selected_stream_config - value - %s', value)
949
+ logger.debug("set_selected_stream_config - value - %s", value)
625
950
 
626
951
  objs = tlv.decode(value, from_base64=True)
627
- if SELECTED_STREAM_CONFIGURATION_TYPES['SESSION'] not in objs:
628
- logger.error('Bad request to set selected stream configuration.')
952
+ if SELECTED_STREAM_CONFIGURATION_TYPES["SESSION"] not in objs:
953
+ logger.error("Bad request to set selected stream configuration.")
629
954
  return
630
955
 
631
- session = tlv.decode(objs[SELECTED_STREAM_CONFIGURATION_TYPES['SESSION']])
956
+ session = tlv.decode(objs[SELECTED_STREAM_CONFIGURATION_TYPES["SESSION"]])
632
957
 
633
- request_type = session[b'\x02'][0]
634
- logger.debug('Set stream config request: %d', request_type)
958
+ request_type = session[b"\x02"][0]
959
+ logger.debug("Set stream config request: %d", request_type)
635
960
  if request_type == 1:
636
961
  job = functools.partial(self._start_stream, reconfigure=False)
637
962
  elif request_type == 0:
@@ -639,7 +964,7 @@ class Camera(Accessory):
639
964
  elif request_type == 4:
640
965
  job = functools.partial(self._start_stream, reconfigure=True)
641
966
  else:
642
- logger.error('Unknown request type %d', request_type)
967
+ logger.error("Unknown request type %d", request_type)
643
968
  return
644
969
 
645
970
  self.driver.add_job(job, objs)
@@ -662,58 +987,73 @@ class Camera(Accessory):
662
987
  stream_idx = 0
663
988
 
664
989
  objs = tlv.decode(value, from_base64=True)
665
- session_id = UUID(bytes=objs[SETUP_TYPES['SESSION_ID']])
990
+ session_id = UUID(bytes=objs[SETUP_TYPES["SESSION_ID"]])
666
991
 
667
992
  # Extract address info
668
- address_tlv = objs[SETUP_TYPES['ADDRESS']]
993
+ address_tlv = objs[SETUP_TYPES["ADDRESS"]]
669
994
  address_info_objs = tlv.decode(address_tlv)
670
- is_ipv6 = struct.unpack('?',
671
- address_info_objs[SETUP_ADDR_INFO['ADDRESS_VER']])[0]
672
- address = address_info_objs[SETUP_ADDR_INFO['ADDRESS']].decode('utf8')
995
+ is_ipv6 = struct.unpack("?", address_info_objs[SETUP_ADDR_INFO["ADDRESS_VER"]])[
996
+ 0
997
+ ]
998
+ address = address_info_objs[SETUP_ADDR_INFO["ADDRESS"]].decode("utf8")
673
999
  target_video_port = struct.unpack(
674
- '<H', address_info_objs[SETUP_ADDR_INFO['VIDEO_RTP_PORT']])[0]
1000
+ "<H", address_info_objs[SETUP_ADDR_INFO["VIDEO_RTP_PORT"]]
1001
+ )[0]
675
1002
  target_audio_port = struct.unpack(
676
- '<H', address_info_objs[SETUP_ADDR_INFO['AUDIO_RTP_PORT']])[0]
1003
+ "<H", address_info_objs[SETUP_ADDR_INFO["AUDIO_RTP_PORT"]]
1004
+ )[0]
677
1005
 
678
1006
  # Video SRTP Params
679
- video_srtp_tlv = objs[SETUP_TYPES['VIDEO_SRTP_PARAM']]
1007
+ video_srtp_tlv = objs[SETUP_TYPES["VIDEO_SRTP_PARAM"]]
680
1008
  video_info_objs = tlv.decode(video_srtp_tlv)
681
- video_crypto_suite = video_info_objs[SETUP_SRTP_PARAM['CRYPTO']][0]
682
- video_master_key = video_info_objs[SETUP_SRTP_PARAM['MASTER_KEY']]
683
- video_master_salt = video_info_objs[SETUP_SRTP_PARAM['MASTER_SALT']]
1009
+ video_crypto_suite = video_info_objs[SETUP_SRTP_PARAM["CRYPTO"]][0]
1010
+ video_master_key = video_info_objs[SETUP_SRTP_PARAM["MASTER_KEY"]]
1011
+ video_master_salt = video_info_objs[SETUP_SRTP_PARAM["MASTER_SALT"]]
684
1012
 
685
1013
  # Audio SRTP Params
686
- audio_srtp_tlv = objs[SETUP_TYPES['AUDIO_SRTP_PARAM']]
1014
+ audio_srtp_tlv = objs[SETUP_TYPES["AUDIO_SRTP_PARAM"]]
687
1015
  audio_info_objs = tlv.decode(audio_srtp_tlv)
688
- audio_crypto_suite = audio_info_objs[SETUP_SRTP_PARAM['CRYPTO']][0]
689
- audio_master_key = audio_info_objs[SETUP_SRTP_PARAM['MASTER_KEY']]
690
- audio_master_salt = audio_info_objs[SETUP_SRTP_PARAM['MASTER_SALT']]
1016
+ audio_crypto_suite = audio_info_objs[SETUP_SRTP_PARAM["CRYPTO"]][0]
1017
+ audio_master_key = audio_info_objs[SETUP_SRTP_PARAM["MASTER_KEY"]]
1018
+ audio_master_salt = audio_info_objs[SETUP_SRTP_PARAM["MASTER_SALT"]]
691
1019
 
692
1020
  logger.debug(
693
- 'Received endpoint configuration:'
694
- '\nsession_id: %s\naddress: %s\nis_ipv6: %s'
695
- '\ntarget_video_port: %s\ntarget_audio_port: %s'
696
- '\nvideo_crypto_suite: %s\nvideo_srtp: %s'
697
- '\naudio_crypto_suite: %s\naudio_srtp: %s',
698
- session_id, address, is_ipv6, target_video_port, target_audio_port,
1021
+ "Received endpoint configuration:"
1022
+ "\nsession_id: %s\naddress: %s\nis_ipv6: %s"
1023
+ "\ntarget_video_port: %s\ntarget_audio_port: %s"
1024
+ "\nvideo_crypto_suite: %s\nvideo_srtp: %s"
1025
+ "\naudio_crypto_suite: %s\naudio_srtp: %s",
1026
+ session_id,
1027
+ address,
1028
+ is_ipv6,
1029
+ target_video_port,
1030
+ target_audio_port,
699
1031
  video_crypto_suite,
700
1032
  to_base64_str(video_master_key + video_master_salt),
701
1033
  audio_crypto_suite,
702
- to_base64_str(audio_master_key + audio_master_salt)
1034
+ to_base64_str(audio_master_key + audio_master_salt),
703
1035
  )
704
1036
 
705
1037
  # Configure the SetupEndpoints response
706
1038
 
707
1039
  if self.has_srtp:
708
1040
  video_srtp_tlv = tlv.encode(
709
- SETUP_SRTP_PARAM['CRYPTO'], SRTP_CRYPTO_SUITES['AES_CM_128_HMAC_SHA1_80'],
710
- SETUP_SRTP_PARAM['MASTER_KEY'], video_master_key,
711
- SETUP_SRTP_PARAM['MASTER_SALT'], video_master_salt)
1041
+ SETUP_SRTP_PARAM["CRYPTO"],
1042
+ SRTP_CRYPTO_SUITES["AES_CM_128_HMAC_SHA1_80"],
1043
+ SETUP_SRTP_PARAM["MASTER_KEY"],
1044
+ video_master_key,
1045
+ SETUP_SRTP_PARAM["MASTER_SALT"],
1046
+ video_master_salt,
1047
+ )
712
1048
 
713
1049
  audio_srtp_tlv = tlv.encode(
714
- SETUP_SRTP_PARAM['CRYPTO'], SRTP_CRYPTO_SUITES['AES_CM_128_HMAC_SHA1_80'],
715
- SETUP_SRTP_PARAM['MASTER_KEY'], audio_master_key,
716
- SETUP_SRTP_PARAM['MASTER_SALT'], audio_master_salt)
1050
+ SETUP_SRTP_PARAM["CRYPTO"],
1051
+ SRTP_CRYPTO_SUITES["AES_CM_128_HMAC_SHA1_80"],
1052
+ SETUP_SRTP_PARAM["MASTER_KEY"],
1053
+ audio_master_key,
1054
+ SETUP_SRTP_PARAM["MASTER_SALT"],
1055
+ audio_master_salt,
1056
+ )
717
1057
  else:
718
1058
  video_srtp_tlv = NO_SRTP
719
1059
  audio_srtp_tlv = NO_SRTP
@@ -721,40 +1061,92 @@ class Camera(Accessory):
721
1061
  video_ssrc = int.from_bytes(os.urandom(3), byteorder="big")
722
1062
  audio_ssrc = int.from_bytes(os.urandom(3), byteorder="big")
723
1063
 
1064
+ # If talkback is enabled, open a local receiver for the audio the
1065
+ # controller will send back during the session, and report *its* real
1066
+ # port below instead of echoing the controller's own port back at it.
1067
+ # Per the HAP spec (section 11, "IP Cameras"), the "Accessory Address"
1068
+ # TLV in this response carries the accessory's own address/ports (the
1069
+ # "Controller Address" received above carries the controller's), so
1070
+ # echoing the controller's port here left HAP clients with nowhere
1071
+ # valid to send the talkback audio to.
1072
+ #
1073
+ # Stop any previous receiver for this session first, so a
1074
+ # re-sent SetupEndpoints for the same session ID doesn't leak its
1075
+ # receiver thread and UDP socket.
1076
+ self._close_talkback(self.sessions.get(session_id, {}))
1077
+ audio_backchannel = None
1078
+ audio_rtp_port = target_audio_port
1079
+ if self.support_talkback:
1080
+ audio_backchannel = TalkbackReceiver(
1081
+ srtp_key_and_salt=audio_master_key + audio_master_salt,
1082
+ on_payload=functools.partial(
1083
+ self._talkback_payload_received, session_id
1084
+ ),
1085
+ is_ipv6=bool(is_ipv6),
1086
+ )
1087
+ audio_backchannel.start()
1088
+ audio_rtp_port = audio_backchannel.local_port
1089
+
724
1090
  res_address_tlv = tlv.encode(
725
- SETUP_ADDR_INFO['ADDRESS_VER'], self.stream_address_isv6,
726
- SETUP_ADDR_INFO['ADDRESS'], self.stream_address.encode('utf-8'),
727
- SETUP_ADDR_INFO['VIDEO_RTP_PORT'], struct.pack('<H', target_video_port),
728
- SETUP_ADDR_INFO['AUDIO_RTP_PORT'], struct.pack('<H', target_audio_port))
1091
+ SETUP_ADDR_INFO["ADDRESS_VER"],
1092
+ self.stream_address_isv6,
1093
+ SETUP_ADDR_INFO["ADDRESS"],
1094
+ self.stream_address.encode("utf-8"),
1095
+ SETUP_ADDR_INFO["VIDEO_RTP_PORT"],
1096
+ struct.pack("<H", target_video_port),
1097
+ SETUP_ADDR_INFO["AUDIO_RTP_PORT"],
1098
+ struct.pack("<H", audio_rtp_port),
1099
+ )
729
1100
 
730
1101
  response_tlv = tlv.encode(
731
- SETUP_TYPES['SESSION_ID'], session_id.bytes,
732
- SETUP_TYPES['STATUS'], SETUP_STATUS['SUCCESS'],
733
- SETUP_TYPES['ADDRESS'], res_address_tlv,
734
- SETUP_TYPES['VIDEO_SRTP_PARAM'], video_srtp_tlv,
735
- SETUP_TYPES['AUDIO_SRTP_PARAM'], audio_srtp_tlv,
736
- SETUP_TYPES['VIDEO_SSRC'], struct.pack('<I', video_ssrc),
737
- SETUP_TYPES['AUDIO_SSRC'], struct.pack('<I', audio_ssrc),
738
- to_base64=True)
1102
+ SETUP_TYPES["SESSION_ID"],
1103
+ session_id.bytes,
1104
+ SETUP_TYPES["STATUS"],
1105
+ SETUP_STATUS["SUCCESS"],
1106
+ SETUP_TYPES["ADDRESS"],
1107
+ res_address_tlv,
1108
+ SETUP_TYPES["VIDEO_SRTP_PARAM"],
1109
+ video_srtp_tlv,
1110
+ SETUP_TYPES["AUDIO_SRTP_PARAM"],
1111
+ audio_srtp_tlv,
1112
+ SETUP_TYPES["VIDEO_SSRC"],
1113
+ struct.pack("<I", video_ssrc),
1114
+ SETUP_TYPES["AUDIO_SSRC"],
1115
+ struct.pack("<I", audio_ssrc),
1116
+ to_base64=True,
1117
+ )
739
1118
 
740
1119
  self.sessions[session_id] = {
741
- 'id': session_id,
742
- 'stream_idx': stream_idx,
743
- 'address': address,
744
- 'v_port': target_video_port,
745
- 'v_srtp_key': to_base64_str(video_master_key + video_master_salt),
746
- 'v_ssrc': video_ssrc,
747
- 'a_port': target_audio_port,
748
- 'a_srtp_key': to_base64_str(audio_master_key + audio_master_salt),
749
- 'a_ssrc': audio_ssrc
1120
+ "id": session_id,
1121
+ "stream_idx": stream_idx,
1122
+ "address": address,
1123
+ "v_port": target_video_port,
1124
+ "v_srtp_key": to_base64_str(video_master_key + video_master_salt),
1125
+ "v_ssrc": video_ssrc,
1126
+ "a_port": target_audio_port,
1127
+ "a_srtp_key": to_base64_str(audio_master_key + audio_master_salt),
1128
+ "a_ssrc": audio_ssrc,
1129
+ "audio_backchannel": audio_backchannel,
750
1130
  }
751
1131
 
752
- self._management[stream_idx].get_characteristic('SetupEndpoints').set_value(response_tlv)
1132
+ self._management[stream_idx].get_characteristic("SetupEndpoints").set_value(
1133
+ response_tlv
1134
+ )
1135
+
1136
+ async def run(self):
1137
+ """Start the HDS listener when recording transport is available."""
1138
+ await super().run()
1139
+ if self._recording_service is not None:
1140
+ await self._ensure_hds_listener()
753
1141
 
754
1142
  async def stop(self):
755
- """Stop all streaming sessions."""
756
- await asyncio.gather(*(
757
- self.stop_stream(session_info) for session_info in self.sessions.values()))
1143
+ """Stop all streaming sessions and the HDS listener."""
1144
+ await asyncio.gather(
1145
+ *(self.stop_stream(session_info) for session_info in self.sessions.values())
1146
+ )
1147
+ if self._hds_listener is not None:
1148
+ await self._hds_listener.stop()
1149
+ self._hds_listener = None
758
1150
 
759
1151
  # ### For client extensions ###
760
1152
 
@@ -816,28 +1208,28 @@ class Camera(Accessory):
816
1208
  :rtype: ``bool``
817
1209
  """
818
1210
  logger.debug(
819
- '[%s] Starting stream with the following parameters: %s',
820
- session_info['id'],
821
- stream_config
1211
+ "[%s] Starting stream with the following parameters: %s",
1212
+ session_info["id"],
1213
+ stream_config,
822
1214
  )
823
1215
 
824
1216
  cmd = self.start_stream_cmd.format(**stream_config).split()
825
- logger.debug('Executing start stream command: "%s"', ' '.join(cmd))
1217
+ logger.debug('Executing start stream command: "%s"', " ".join(cmd))
826
1218
  try:
827
- process = await asyncio.create_subprocess_exec(*cmd,
828
- stdout=asyncio.subprocess.DEVNULL,
829
- stderr=asyncio.subprocess.PIPE,
830
- limit=1024)
1219
+ process = await asyncio.create_subprocess_exec(
1220
+ *cmd,
1221
+ stdout=asyncio.subprocess.DEVNULL,
1222
+ stderr=asyncio.subprocess.PIPE,
1223
+ limit=1024,
1224
+ )
831
1225
  except Exception as e: # pylint: disable=broad-except
832
- logger.error('Failed to start streaming process because of error: %s', e)
1226
+ logger.error("Failed to start streaming process because of error: %s", e)
833
1227
  return False
834
1228
 
835
- session_info['process'] = process
1229
+ session_info["process"] = process
836
1230
 
837
1231
  logger.info(
838
- '[%s] Started stream process - PID %d',
839
- session_info['id'],
840
- process.pid
1232
+ "[%s] Started stream process - PID %d", session_info["id"], process.pid
841
1233
  )
842
1234
 
843
1235
  return True
@@ -853,25 +1245,25 @@ class Camera(Accessory):
853
1245
  - id - The session ID.
854
1246
  :type session_info: ``dict``
855
1247
  """
856
- session_id = session_info['id']
857
- ffmpeg_process = session_info.get('process')
1248
+ session_id = session_info["id"]
1249
+ ffmpeg_process = session_info.get("process")
858
1250
  if ffmpeg_process:
859
- logger.info('[%s] Stopping stream.', session_id)
1251
+ logger.info("[%s] Stopping stream.", session_id)
860
1252
  try:
861
1253
  ffmpeg_process.terminate()
862
- async with async_timeout.timeout(2.0):
1254
+ async with async_timeout(2.0):
863
1255
  _, stderr = await ffmpeg_process.communicate()
864
- logger.debug('Stream command stderr: %s', stderr)
1256
+ logger.debug("Stream command stderr: %s", stderr)
865
1257
  except asyncio.TimeoutError:
866
1258
  logger.error(
867
- 'Timeout while waiting for the stream process '
868
- 'to terminate. Trying with kill.'
1259
+ "Timeout while waiting for the stream process "
1260
+ "to terminate. Trying with kill."
869
1261
  )
870
1262
  ffmpeg_process.kill()
871
1263
  await ffmpeg_process.wait()
872
- logger.debug('Stream process stopped.')
1264
+ logger.debug("Stream process stopped.")
873
1265
  else:
874
- logger.warning('No process for session ID %s', session_id)
1266
+ logger.warning("No process for session ID %s", session_id)
875
1267
 
876
1268
  async def reconfigure_stream(self, session_info, stream_config):
877
1269
  """Reconfigure the stream so that it uses the given ``stream_config``.
@@ -894,5 +1286,5 @@ class Camera(Accessory):
894
1286
  :param image_size: ``dict`` describing the requested image size. Contains the
895
1287
  keys "image-width" and "image-height"
896
1288
  """
897
- with open(os.path.join(RESOURCE_DIR, 'snapshot.jpg'), 'rb') as fp:
1289
+ with open(os.path.join(RESOURCE_DIR, "snapshot.jpg"), "rb") as fp:
898
1290
  return fp.read()