homebridge-alexa 0.10.0 → 0.11.0-beta.0
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.
- package/CHANGELOG.md +12 -0
- package/README.md +26 -1
- package/Troubleshooting.md +30 -0
- package/config.schema.json +24 -0
- package/package.json +8 -5
- package/src/lib/alexaActions.js +71 -0
- package/src/lib/alexaMessages.js +45 -1
- package/src/lib/camera/bridge.js +297 -0
- package/src/lib/camera/bridge.test.js +135 -0
- package/src/lib/camera/camera.test.js +225 -0
- package/src/lib/camera/errors.js +10 -0
- package/src/lib/camera/hapStream.js +212 -0
- package/src/lib/camera/sessions.js +115 -0
- package/src/lib/camera/tlv.js +70 -0
- package/src/lib/camera/transcoder.js +152 -0
- package/src/lib/camera/transcoder.test.js +43 -0
- package/src/lib/parse/Accessory.js +26 -0
- package/src/lib/parse/Cameras.test.js +58 -0
- package/src/lib/parse/Homebridge.js +1 -0
- package/src/lib/parse/Service.js +42 -1
- package/src/lib/parse/messages.js +14 -0
- package/src/plugin.js +6 -0
package/CHANGELOG.md
CHANGED
|
@@ -2,6 +2,18 @@
|
|
|
2
2
|
|
|
3
3
|
All notable changes to this project will be documented in this file. This project uses [Semantic Versioning](https://semver.org/).
|
|
4
4
|
|
|
5
|
+
## 0.11.0 (unreleased)
|
|
6
|
+
|
|
7
|
+
#### New Features
|
|
8
|
+
|
|
9
|
+
- **Cameras and video doorbells (experimental)** – A new setting, `cameras`, shows HomeKit cameras live on an Echo Show or Fire TV ("Alexa, show the Driveway camera"). Each camera becomes one Alexa camera, and a doorbell with a camera becomes one video doorbell that keeps its existing Alexa device, so doorbell routines keep working. Video is passed through untouched over WebRTC. Audio is one-way: Opus is passed through, and AAC-ELD is converted to Opus with Homebridge's ffmpeg. A new `cameraIceServers` setting adds STUN / TURN servers for routers that need them.
|
|
10
|
+
|
|
11
|
+
#### Changes
|
|
12
|
+
|
|
13
|
+
- **Node.js 22 or later is now required.**
|
|
14
|
+
- New dependencies: `werift` (WebRTC) and `ffmpeg-for-homebridge`.
|
|
15
|
+
- Node.js 20 is dropped from the CI test matrix.
|
|
16
|
+
|
|
5
17
|
## 0.10.0 (2026-10-23)
|
|
6
18
|
|
|
7
19
|
## [Version 0.10.0](https://github.com/northernman54/homebridge-alexa/compare/0.9.3...0.10.0)
|
package/README.md
CHANGED
|
@@ -73,6 +73,7 @@ Country availability - The plugin is available in these countries, English (AU),
|
|
|
73
73
|
* [Contact and Motion Sensors](#contact-and-motion-sensors)
|
|
74
74
|
* [Smoke, Carbon Monoxide and Leak Sensors](#smoke-carbon-monoxide-and-leak-sensors)
|
|
75
75
|
* [Door bell devices](#door-bell-devices)
|
|
76
|
+
* [Cameras (experimental)](#cameras-experimental)
|
|
76
77
|
* [Installation of homebridge-alexa](#installation-of-homebridge-alexa)
|
|
77
78
|
* [Service Availability and Issues](#service-availability-and-issues)
|
|
78
79
|
* [Homebridge cloud service monitoring ( homebridge.ca )](#homebridge-cloud-service-monitoring--homebridgeca-)
|
|
@@ -129,6 +130,7 @@ This only supports accessories connected via a homebridge plugin, any 'Homekit'
|
|
|
129
130
|
* HomeKit Television ( Initial support only On/Off, Inputs and Volume Control )
|
|
130
131
|
* Garage Doors and Window Coverings/Blinds
|
|
131
132
|
* Door bells
|
|
133
|
+
* Cameras and video doorbells - live view on Echo Show and Fire TV ( experimental, requires `cameras` option, see [Cameras](#cameras-experimental) )
|
|
132
134
|
|
|
133
135
|
### Supported as Other Types
|
|
134
136
|
|
|
@@ -143,7 +145,6 @@ This only supports accessories connected via a homebridge plugin, any 'Homekit'
|
|
|
143
145
|
|
|
144
146
|
## Unsupported device types
|
|
145
147
|
|
|
146
|
-
* Camera's ( for use with an Alexa show etc )
|
|
147
148
|
* Eve devices
|
|
148
149
|
* Security Systems
|
|
149
150
|
|
|
@@ -329,6 +330,30 @@ These are the remote buttons
|
|
|
329
330
|
|
|
330
331
|
* Their is no voice control of door bells, only the ability to have Alexa announce when the door bell is triggered. For a sample here is my [Door Bell](https://youtu.be/PhGbc_TO8pk) being rang.
|
|
331
332
|
|
|
333
|
+
## Cameras (experimental)
|
|
334
|
+
|
|
335
|
+
Live view of HomeKit cameras on an Echo Show or Fire TV. Turn on **Cameras (experimental)** under Advanced Settings in the plugin settings ( `"cameras": true` in config.json ), restart Homebridge and ask Alexa to discover devices.
|
|
336
|
+
|
|
337
|
+
* `Alexa, show the Driveway camera` - shows the live view on an Echo Show
|
|
338
|
+
* `Alexa, show the Driveway camera on Fire TV`
|
|
339
|
+
* `Alexa, hide the Driveway camera` or `Alexa, stop`
|
|
340
|
+
|
|
341
|
+
What you get:
|
|
342
|
+
|
|
343
|
+
* Each camera becomes one Alexa camera. A doorbell with a camera becomes one video doorbell, which keeps the doorbell's existing Alexa device, so doorbell routines keep working. When the doorbell is pressed an Echo Show can pop up the live view.
|
|
344
|
+
* Video is passed through as the camera sends it, so the live view adds no load on your Homebridge server.
|
|
345
|
+
* One-way audio. Cameras that offer Opus audio are passed through; cameras that offer only AAC-ELD are converted to Opus with Homebridge's own ffmpeg ( `ffmpeg-for-homebridge`, installed with this plugin ). If no usable ffmpeg is found, the live view has no sound.
|
|
346
|
+
|
|
347
|
+
Requirements and limits:
|
|
348
|
+
|
|
349
|
+
* Node.js 22 or later.
|
|
350
|
+
* Cameras using the standard HomeKit camera support that every Homebridge camera plugin uses today, such as homebridge-camera-ffmpeg and homebridge-unifi-protect, streaming H.264 video. Cameras using the new iOS 27 camera form ( HEVC only ) are not exposed to Alexa.
|
|
351
|
+
* Live view only: no talk back, no pan / tilt / zoom, no recordings or snapshots.
|
|
352
|
+
* Your Homebridge server must be able to reach the internet over UDP. A public STUN server is used to get through your router. If live view never starts, your router may need a TURN server, which you can add under **Camera STUN / TURN servers**.
|
|
353
|
+
* Turning a camera's streaming off in the Home app also stops Alexa's live view.
|
|
354
|
+
|
|
355
|
+
See [Troubleshooting - Cameras](Troubleshooting.md#cameras) if live view doesn't work, and [docs/Cameras.md](docs/Cameras.md) for how it works.
|
|
356
|
+
|
|
332
357
|
# Installation of homebridge-alexa
|
|
333
358
|
|
|
334
359
|
Installation and configuration instructions are [here](Installation.md).
|
package/Troubleshooting.md
CHANGED
|
@@ -32,6 +32,11 @@
|
|
|
32
32
|
* [Unsuccessful event message ( No event gateway token )](#unsuccessful-event-message--no-event-gateway-token-)
|
|
33
33
|
* [Successful event message being sent to Alexa](#successful-event-message-being-sent-to-alexa)
|
|
34
34
|
* [[Alexa] ERROR: Event gateway token refresh error: 400](#alexa-error--event-gateway-token-refresh-error-400)
|
|
35
|
+
* [Cameras](#cameras)
|
|
36
|
+
* [Cameras don't appear in the Alexa app](#cameras-dont-appear-in-the-alexa-app)
|
|
37
|
+
* [Live view keeps loading, then fails](#live-view-keeps-loading-then-fails)
|
|
38
|
+
* [Live view has no sound](#live-view-has-no-sound)
|
|
39
|
+
* [Camera debug logs](#camera-debug-logs)
|
|
35
40
|
<!--te-->
|
|
36
41
|
|
|
37
42
|
# Initial Setup
|
|
@@ -212,3 +217,28 @@ Feb 16 14:29:05 raj homebridge[2088]: 2019-02-16T19:29:05.107Z alexaLocal Sendin
|
|
|
212
217
|
## [Alexa] ERROR: Event gateway token refresh error: 400
|
|
213
218
|
|
|
214
219
|
Your event gateway authorization needs a manual refresh, this is required in order to utilize events from Motion and Contact sensors in routines. In the Amazon Alexa app, please "Disable Skill" and "Enable" the skill, and re-enter your password.
|
|
220
|
+
|
|
221
|
+
# Cameras
|
|
222
|
+
|
|
223
|
+
## Cameras don't appear in the Alexa app
|
|
224
|
+
|
|
225
|
+
* Check `cameras` is turned on ( **Cameras (experimental)** under Advanced Settings ), restart Homebridge and ask Alexa to discover devices again.
|
|
226
|
+
* Only cameras using the standard HomeKit camera support are exposed. Cameras in the new iOS 27 form ( HEVC only ) are not.
|
|
227
|
+
* A video doorbell shows as one device with the doorbell's name, not as a separate camera.
|
|
228
|
+
|
|
229
|
+
## Live view keeps loading, then fails
|
|
230
|
+
|
|
231
|
+
* `Camera streaming is turned off in the Home app` - turn the camera's streaming back on in the Home app.
|
|
232
|
+
* `Homebridge instance not found` - the Homebridge running the camera wasn't found on the network; check it is running in insecure mode, like every other device.
|
|
233
|
+
* `Camera did not answer in time` - the camera plugin took longer than Alexa allows ( about 5 seconds ) to start. Try again; check the camera plugin's own logs.
|
|
234
|
+
* `Too many camera sessions` - at most 4 live views run at once.
|
|
235
|
+
* No error, but the picture never starts - Alexa couldn't reach your Homebridge server through your router. Add a TURN server under **Camera STUN / TURN servers** ( `cameraIceServers` ), for example one from your own coturn server or a hosted TURN service.
|
|
236
|
+
|
|
237
|
+
## Live view has no sound
|
|
238
|
+
|
|
239
|
+
* Audio is one-way only; there is no talk back.
|
|
240
|
+
* A camera that sends AAC-ELD audio needs ffmpeg to convert it. `ffmpeg-for-homebridge` normally installs one, but npm 12 and later block its download unless install scripts are allowed. Without it the plugin uses an `ffmpeg` on your PATH if it has libopus, and otherwise shows video without sound. Reinstalling with `npm install-scripts approve ffmpeg-for-homebridge` ( or installing ffmpeg ) restores sound.
|
|
241
|
+
|
|
242
|
+
## Camera debug logs
|
|
243
|
+
|
|
244
|
+
Start Homebridge with `DEBUG=alexa:camera:*` to log each live view: the camera's audio codecs, when the answer was sent to Alexa, the WebRTC connection state, and packet counts when the view ends. The logs contain your network addresses, so check them before posting them in an issue.
|
package/config.schema.json
CHANGED
|
@@ -87,6 +87,28 @@
|
|
|
87
87
|
"functionBody": "return model.CloudTransport !== 'wss';"
|
|
88
88
|
}
|
|
89
89
|
},
|
|
90
|
+
"cameras": {
|
|
91
|
+
"title": "<b>Cameras (experimental)</b>",
|
|
92
|
+
"type": "boolean",
|
|
93
|
+
"description": "Expose HomeKit cameras to Alexa for live view on Echo Show and Fire TV. A doorbell with a camera becomes one video doorbell. Live view with one-way audio (AAC-ELD audio is converted to Opus with Homebridge's ffmpeg). Requires Node.js 22 or later.",
|
|
94
|
+
"placeholder": false
|
|
95
|
+
},
|
|
96
|
+
"cameraIceServers": {
|
|
97
|
+
"title": "Camera STUN / TURN servers",
|
|
98
|
+
"description": "ICE servers for camera live view, used to reach Alexa from behind your router. Defaults to a public Google STUN server. Add a TURN server if live view fails to connect.",
|
|
99
|
+
"type": "array",
|
|
100
|
+
"condition": {
|
|
101
|
+
"functionBody": "return model.cameras === true;"
|
|
102
|
+
},
|
|
103
|
+
"items": {
|
|
104
|
+
"type": "object",
|
|
105
|
+
"properties": {
|
|
106
|
+
"urls": { "title": "URL", "type": "string", "placeholder": "stun:stun.l.google.com:19302", "required": true },
|
|
107
|
+
"username": { "title": "Username", "type": "string" },
|
|
108
|
+
"credential": { "title": "Credential", "type": "string" }
|
|
109
|
+
}
|
|
110
|
+
}
|
|
111
|
+
},
|
|
90
112
|
"mergeServiceName": {
|
|
91
113
|
"title": "<b>Alternate device naming approach</b>",
|
|
92
114
|
"type": "boolean",
|
|
@@ -316,6 +338,8 @@
|
|
|
316
338
|
"refresh",
|
|
317
339
|
"filter",
|
|
318
340
|
"mergeServiceName",
|
|
341
|
+
"cameras",
|
|
342
|
+
"cameraIceServers",
|
|
319
343
|
"blind",
|
|
320
344
|
"door"
|
|
321
345
|
]
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "homebridge-alexa",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.11.0-beta.0",
|
|
4
4
|
"description": "Control your Homebridge devices with Amazon Alexa.",
|
|
5
5
|
"main": "src/plugin.js",
|
|
6
6
|
"scripts": {
|
|
@@ -27,7 +27,7 @@
|
|
|
27
27
|
},
|
|
28
28
|
"engines": {
|
|
29
29
|
"homebridge": "^1.6.0 || ^2.0.0-beta.0",
|
|
30
|
-
"node": ">=
|
|
30
|
+
"node": ">=22"
|
|
31
31
|
},
|
|
32
32
|
"keywords": [
|
|
33
33
|
"alexa",
|
|
@@ -53,9 +53,11 @@
|
|
|
53
53
|
"axios": "^1.7.9",
|
|
54
54
|
"bottleneck": "2.19.5",
|
|
55
55
|
"debug": "4.4.3",
|
|
56
|
+
"ffmpeg-for-homebridge": "^2.2.2",
|
|
56
57
|
"hap-node-client": "^0.2.9",
|
|
57
58
|
"is-my-json-valid": "2.20.6",
|
|
58
|
-
"mqtt": "5.15.0"
|
|
59
|
+
"mqtt": "5.15.0",
|
|
60
|
+
"werift": "0.28.0"
|
|
59
61
|
},
|
|
60
62
|
"author": "NorthernMan54",
|
|
61
63
|
"license": "Apache-2.0",
|
|
@@ -77,6 +79,7 @@
|
|
|
77
79
|
"fsevents": true,
|
|
78
80
|
"@parcel/watcher": true,
|
|
79
81
|
"unrs-resolver": true,
|
|
80
|
-
"nodemon": true
|
|
82
|
+
"nodemon": true,
|
|
83
|
+
"ffmpeg-for-homebridge@2.2.2": true
|
|
81
84
|
}
|
|
82
|
-
}
|
|
85
|
+
}
|
package/src/lib/alexaActions.js
CHANGED
|
@@ -4,10 +4,15 @@ var alexaMessages = require('./alexaMessages.js');
|
|
|
4
4
|
var messages = require('./parse/messages');
|
|
5
5
|
var debug = require('debug')('alexaActions');
|
|
6
6
|
var alexaLocal = require('./alexaLocal.js');
|
|
7
|
+
var CameraSessions = require('./camera/sessions.js').CameraSessions;
|
|
8
|
+
var HapCameraStream = require('./camera/hapStream.js').HapCameraStream;
|
|
9
|
+
var CameraError = require('./camera/errors.js').CameraError;
|
|
10
|
+
var cameraBridge = require('./camera/bridge.js');
|
|
7
11
|
const process = require('process');
|
|
8
12
|
|
|
9
13
|
var homebridge;
|
|
10
14
|
var hbDevices;
|
|
15
|
+
var cameraSessions;
|
|
11
16
|
|
|
12
17
|
module.exports = {
|
|
13
18
|
alexaDiscovery: alexaDiscovery,
|
|
@@ -28,6 +33,7 @@ module.exports = {
|
|
|
28
33
|
alexaInputController: alexaInputController,
|
|
29
34
|
alexaRangeController: alexaRangeController,
|
|
30
35
|
alexaModeController: alexaModeController,
|
|
36
|
+
alexaRTCSessionController: alexaRTCSessionController,
|
|
31
37
|
destroy: destroy,
|
|
32
38
|
setHomebridge: setHomebridge
|
|
33
39
|
};
|
|
@@ -54,6 +60,9 @@ function hapDiscovery(options) {
|
|
|
54
60
|
// Used for testing
|
|
55
61
|
|
|
56
62
|
function destroy() {
|
|
63
|
+
if (cameraSessions) {
|
|
64
|
+
cameraSessions.endAll();
|
|
65
|
+
}
|
|
57
66
|
homebridge.destroy();
|
|
58
67
|
}
|
|
59
68
|
|
|
@@ -466,6 +475,68 @@ function alexaLockController(message, callback) {
|
|
|
466
475
|
}.bind(this));
|
|
467
476
|
}
|
|
468
477
|
|
|
478
|
+
function getCameraSessions(options) {
|
|
479
|
+
if (!cameraSessions) {
|
|
480
|
+
cameraSessions = new CameraSessions({
|
|
481
|
+
log: options.log,
|
|
482
|
+
createBridge: function (context) {
|
|
483
|
+
return cameraBridge.createBridge(Object.assign({ options: { iceServers: options.cameraIceServers } }, context));
|
|
484
|
+
},
|
|
485
|
+
createStream: async function (camera) {
|
|
486
|
+
const instance = homebridge.mdnsCache()[camera.deviceID];
|
|
487
|
+
if (!instance) {
|
|
488
|
+
throw new CameraError('ENDPOINT_UNREACHABLE', 'Homebridge instance not found ' + camera.deviceID);
|
|
489
|
+
}
|
|
490
|
+
return new HapCameraStream({ host: instance.host, port: instance.port, pin: options.pin, camera: camera });
|
|
491
|
+
}
|
|
492
|
+
});
|
|
493
|
+
}
|
|
494
|
+
return cameraSessions;
|
|
495
|
+
}
|
|
496
|
+
|
|
497
|
+
function alexaRTCSessionController(message, callback) {
|
|
498
|
+
const action = message.directive.header.name;
|
|
499
|
+
const endpointId = message.directive.endpoint.endpointId;
|
|
500
|
+
const payload = message.directive.payload || {};
|
|
501
|
+
const sessions = getCameraSessions(this);
|
|
502
|
+
var camera, work, eventName;
|
|
503
|
+
try {
|
|
504
|
+
camera = JSON.parse(message.directive.endpoint.cookie["Camera"]);
|
|
505
|
+
} catch (e) {
|
|
506
|
+
this.log.error("alexaRTCSessionController missing camera cookie", endpointId, e.message);
|
|
507
|
+
callback(e, alexaMessages.alexaErrorResponse(message, "INVALID_VALUE", "Endpoint is not a camera"));
|
|
508
|
+
return;
|
|
509
|
+
}
|
|
510
|
+
switch (action) {
|
|
511
|
+
case "InitiateSessionWithOffer":
|
|
512
|
+
eventName = "AnswerGeneratedForSession";
|
|
513
|
+
if (!payload.offer || payload.offer.format !== "SDP") {
|
|
514
|
+
work = Promise.reject(new CameraError("INVALID_DIRECTIVE", "Offer must be SDP"));
|
|
515
|
+
} else {
|
|
516
|
+
work = sessions.initiate({ sessionId: payload.sessionId, endpointId: endpointId, camera: camera, offer: payload.offer.value })
|
|
517
|
+
.then(answer => ({ "answer": { "format": "SDP", "value": answer } }));
|
|
518
|
+
}
|
|
519
|
+
break;
|
|
520
|
+
case "SessionConnected":
|
|
521
|
+
eventName = "SessionConnected";
|
|
522
|
+
work = sessions.connected(payload.sessionId).then(() => ({ "sessionId": payload.sessionId }));
|
|
523
|
+
break;
|
|
524
|
+
case "SessionDisconnected":
|
|
525
|
+
eventName = "SessionDisconnected";
|
|
526
|
+
work = sessions.end(payload.sessionId).then(() => ({ "sessionId": payload.sessionId }));
|
|
527
|
+
break;
|
|
528
|
+
default:
|
|
529
|
+
work = Promise.reject(new CameraError("INVALID_DIRECTIVE", "Unsupported directive " + action));
|
|
530
|
+
}
|
|
531
|
+
work.then(function (response) {
|
|
532
|
+
this.log(message.directive.header.namespace, action, camera.deviceID, endpointId);
|
|
533
|
+
callback(null, alexaMessages.alexaEventResponse(message, "Alexa.RTCSessionController", eventName, response));
|
|
534
|
+
}.bind(this), function (err) {
|
|
535
|
+
this.log.error(message.directive.header.namespace, action, camera.deviceID, endpointId, "ERROR: " + err.message);
|
|
536
|
+
callback(err, alexaMessages.alexaErrorResponse(message, err.type || "ENDPOINT_UNREACHABLE", err.message));
|
|
537
|
+
}.bind(this));
|
|
538
|
+
}
|
|
539
|
+
|
|
469
540
|
function alexaChannelController(message, callback) {
|
|
470
541
|
// debug("Directive", JSON.stringify(message));
|
|
471
542
|
/* = Version 1.0
|
package/src/lib/alexaMessages.js
CHANGED
|
@@ -6,9 +6,53 @@ var debug = require('debug')('alexaMessages');
|
|
|
6
6
|
module.exports = {
|
|
7
7
|
alexaResponse: alexaResponse,
|
|
8
8
|
alexaStateResponse: alexaStateResponse,
|
|
9
|
-
eventMessage: eventMessage
|
|
9
|
+
eventMessage: eventMessage,
|
|
10
|
+
alexaEventResponse: alexaEventResponse,
|
|
11
|
+
alexaErrorResponse: alexaErrorResponse
|
|
10
12
|
};
|
|
11
13
|
|
|
14
|
+
/**
|
|
15
|
+
* A response to a directive that answers with its own event, such as Alexa.RTCSessionController's AnswerGeneratedForSession.
|
|
16
|
+
*/
|
|
17
|
+
function alexaEventResponse(message, namespace, name, payload) {
|
|
18
|
+
return {
|
|
19
|
+
"event": {
|
|
20
|
+
"header": {
|
|
21
|
+
"namespace": namespace,
|
|
22
|
+
"name": name,
|
|
23
|
+
"messageId": messages.createMessageId(),
|
|
24
|
+
"correlationToken": message.directive.header.correlationToken,
|
|
25
|
+
"payloadVersion": "3"
|
|
26
|
+
},
|
|
27
|
+
"endpoint": {
|
|
28
|
+
"endpointId": message.directive.endpoint.endpointId
|
|
29
|
+
},
|
|
30
|
+
"payload": payload
|
|
31
|
+
}
|
|
32
|
+
};
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
function alexaErrorResponse(message, type, errorMessage) {
|
|
36
|
+
return {
|
|
37
|
+
"event": {
|
|
38
|
+
"header": {
|
|
39
|
+
"namespace": "Alexa",
|
|
40
|
+
"name": "ErrorResponse",
|
|
41
|
+
"messageId": message.directive.header.messageId,
|
|
42
|
+
"correlationToken": message.directive.header.correlationToken,
|
|
43
|
+
"payloadVersion": "3"
|
|
44
|
+
},
|
|
45
|
+
"endpoint": {
|
|
46
|
+
"endpointId": message.directive.endpoint.endpointId
|
|
47
|
+
},
|
|
48
|
+
"payload": {
|
|
49
|
+
"type": type,
|
|
50
|
+
"message": errorMessage
|
|
51
|
+
}
|
|
52
|
+
}
|
|
53
|
+
};
|
|
54
|
+
}
|
|
55
|
+
|
|
12
56
|
function alexaResponse(message, hbResponse, err, value) {
|
|
13
57
|
var now = new Date();
|
|
14
58
|
var response;
|
|
@@ -0,0 +1,297 @@
|
|
|
1
|
+
// The media bridge turns a camera's SRTP stream into the WebRTC session Alexa offered.
|
|
2
|
+
//
|
|
3
|
+
// camera --SRTP H.264--> UDP socket --decrypt--> werift track --DTLS-SRTP--> Alexa
|
|
4
|
+
//
|
|
5
|
+
// createBridge({ sessionId, stream, log, options }) returns:
|
|
6
|
+
// answer(offerSdp) -> Promise<string> SDP answer with every ICE candidate (Alexa doesn't trickle).
|
|
7
|
+
// connected() -> Promise<void> Alexa reports the WebRTC session is up.
|
|
8
|
+
// close() -> Promise<void> Release media resources. The session manager stops the HAP stream itself.
|
|
9
|
+
//
|
|
10
|
+
// H.264 passes through untouched: no transcoding. Opus audio passes through too when the camera offers it.
|
|
11
|
+
// AAC-ELD audio is converted to Opus with Homebridge's ffmpeg; without a usable ffmpeg such a camera streams
|
|
12
|
+
// video alone, its audio m-line answered inactive.
|
|
13
|
+
const dgram = require('dgram');
|
|
14
|
+
const crypto = require('crypto');
|
|
15
|
+
const debug = require('debug')('alexa:camera:bridge');
|
|
16
|
+
const { CameraError } = require('./errors.js');
|
|
17
|
+
const { AacEldToOpus } = require('./transcoder.js');
|
|
18
|
+
|
|
19
|
+
const GATHER_TIMEOUT = 2500; // ICE gathering budget inside Alexa's 6 second answer deadline
|
|
20
|
+
const CANDIDATE_GRACE = 100; // other interfaces' candidates of the same type arrive within a few ms
|
|
21
|
+
const RTCP_INTERVAL = 1000; // HAP cameras end a stream they get no RTCP for
|
|
22
|
+
const DEFAULT_ICE_SERVERS = [{ urls: 'stun:stun.l.google.com:19302' }];
|
|
23
|
+
const DEFAULT_VIDEO = { width: 1280, height: 720, fps: 30, bitrate: 1500, mtu: 1200 };
|
|
24
|
+
|
|
25
|
+
let werift;
|
|
26
|
+
function loadWerift() {
|
|
27
|
+
if (!werift) {
|
|
28
|
+
werift = require('werift');
|
|
29
|
+
}
|
|
30
|
+
return werift;
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
// The local address the camera's host routes back to.
|
|
34
|
+
function localAddressFor(host) {
|
|
35
|
+
return new Promise((resolve, reject) => {
|
|
36
|
+
const socket = dgram.createSocket('udp4');
|
|
37
|
+
socket.on('error', reject);
|
|
38
|
+
socket.connect(9, host, () => {
|
|
39
|
+
const address = socket.address().address;
|
|
40
|
+
socket.close();
|
|
41
|
+
resolve(address);
|
|
42
|
+
});
|
|
43
|
+
});
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
function bindSocket(address) {
|
|
47
|
+
return new Promise((resolve, reject) => {
|
|
48
|
+
const socket = dgram.createSocket('udp4');
|
|
49
|
+
socket.once('error', reject);
|
|
50
|
+
socket.bind(0, address, () => {
|
|
51
|
+
socket.removeListener('error', reject);
|
|
52
|
+
resolve(socket);
|
|
53
|
+
});
|
|
54
|
+
});
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
class WebRTCBridge {
|
|
58
|
+
constructor({ sessionId, stream, log = () => { }, options = {} }) {
|
|
59
|
+
this.sessionId = sessionId;
|
|
60
|
+
this.stream = stream;
|
|
61
|
+
this.log = log;
|
|
62
|
+
// An empty list from the config UI means "not set". hostOnly (tests, a LAN-only setup) uses no servers at all.
|
|
63
|
+
this.iceServers = options.hostOnly ? [] : (options.iceServers && options.iceServers.length ? options.iceServers : DEFAULT_ICE_SERVERS);
|
|
64
|
+
this.video = Object.assign({}, DEFAULT_VIDEO, options.video);
|
|
65
|
+
this.stats = { packets: 0, bytes: 0, dropped: 0, keyframes: 0, audioPackets: 0 };
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
_createPeer() {
|
|
69
|
+
const { RTCPeerConnection, RTCRtpCodecParameters, MediaStreamTrack } = loadWerift();
|
|
70
|
+
this.pc = new RTCPeerConnection({
|
|
71
|
+
iceServers: this.iceServers,
|
|
72
|
+
iceUseDefaultStunServer: false,
|
|
73
|
+
iceUseIpv6: false, // Alexa takes IPv4 candidates only
|
|
74
|
+
iceUseLinkLocalAddress: false,
|
|
75
|
+
bundlePolicy: 'max-bundle',
|
|
76
|
+
codecs: {
|
|
77
|
+
video: [new RTCRtpCodecParameters({
|
|
78
|
+
mimeType: 'video/H264',
|
|
79
|
+
clockRate: 90000,
|
|
80
|
+
rtcpFeedback: [{ type: 'nack' }, { type: 'nack', parameter: 'pli' }, { type: 'ccm', parameter: 'fir' }, { type: 'goog-remb' }],
|
|
81
|
+
parameters: 'level-asymmetry-allowed=1;packetization-mode=1;profile-level-id=42e01f',
|
|
82
|
+
})],
|
|
83
|
+
audio: [new RTCRtpCodecParameters({ mimeType: 'audio/opus', clockRate: 48000, channels: 2 })],
|
|
84
|
+
},
|
|
85
|
+
});
|
|
86
|
+
this.track = new MediaStreamTrack({ kind: 'video' });
|
|
87
|
+
this.audioTrack = new MediaStreamTrack({ kind: 'audio' });
|
|
88
|
+
// Alexa doesn't trickle, so the answer waits for the candidate that matters most: a relay when a TURN
|
|
89
|
+
// server is configured, else a server-reflexive one when a STUN server is, else only host candidates.
|
|
90
|
+
const urls = this.iceServers.flatMap((server) => [].concat(server.urls));
|
|
91
|
+
this.wantedCandidate = urls.some((url) => /^turns?:/.test(url)) ? 'relay' : urls.some((url) => /^stun:/.test(url)) ? 'srflx' : undefined;
|
|
92
|
+
this.candidateArrived = new Promise((resolve) => {
|
|
93
|
+
this.pc.onIceCandidate.subscribe((candidate) => {
|
|
94
|
+
if (candidate && this.wantedCandidate && candidate.candidate.includes(` typ ${this.wantedCandidate}`)) {
|
|
95
|
+
resolve();
|
|
96
|
+
}
|
|
97
|
+
});
|
|
98
|
+
});
|
|
99
|
+
this.pc.connectionStateChange.subscribe((state) => {
|
|
100
|
+
debug('connection', this.sessionId, state);
|
|
101
|
+
if (state === 'failed') {
|
|
102
|
+
this.log('Camera WebRTC connection failed', this.sessionId);
|
|
103
|
+
}
|
|
104
|
+
});
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
async _waitForCandidates() {
|
|
108
|
+
if (this.pc.iceGatheringState === 'complete' || !this.wantedCandidate) {
|
|
109
|
+
return;
|
|
110
|
+
}
|
|
111
|
+
let timer;
|
|
112
|
+
await Promise.race([
|
|
113
|
+
this.candidateArrived.then(() => new Promise((resolve) => setTimeout(resolve, CANDIDATE_GRACE))),
|
|
114
|
+
new Promise((resolve) => this.pc.iceGatheringStateChange.subscribe((state) => state === 'complete' && resolve())),
|
|
115
|
+
new Promise((resolve) => { timer = setTimeout(resolve, GATHER_TIMEOUT); }),
|
|
116
|
+
]);
|
|
117
|
+
clearTimeout(timer);
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
async answer(offerSdp) {
|
|
121
|
+
const started = Date.now();
|
|
122
|
+
this._createPeer();
|
|
123
|
+
await this.pc.setRemoteDescription({ type: 'offer', sdp: offerSdp });
|
|
124
|
+
const transceivers = this.pc.getTransceivers();
|
|
125
|
+
const video = transceivers.find((t) => t.kind === 'video');
|
|
126
|
+
if (!video) {
|
|
127
|
+
throw new CameraError('INVALID_DIRECTIVE', 'Offer has no video');
|
|
128
|
+
}
|
|
129
|
+
video.setDirection('sendonly');
|
|
130
|
+
await video.sender.replaceTrack(this.track);
|
|
131
|
+
|
|
132
|
+
// HAP needs an audio codec the camera offers in every START; only Opus can go on to Alexa untouched.
|
|
133
|
+
const codecs = await this.stream.audioCodecs().catch((err) => {
|
|
134
|
+
debug('audio codecs unreadable', this.sessionId, err.message);
|
|
135
|
+
return [];
|
|
136
|
+
});
|
|
137
|
+
const opus = codecs.find((c) => c.codec === 'opus');
|
|
138
|
+
const chosen = opus || codecs[0] || { codec: 'opus', sampleRates: [] };
|
|
139
|
+
this.audio = { codec: chosen.codec, sampleRate: Math.max(...chosen.sampleRates.filter((r) => r <= 24), 0) || 16 };
|
|
140
|
+
const audio = transceivers.find((t) => t.kind === 'audio');
|
|
141
|
+
const aacEld = codecs.find((c) => c.codec === 'aac-eld');
|
|
142
|
+
this.transcodeAudio = Boolean(audio && !opus && aacEld && AacEldToOpus.available());
|
|
143
|
+
if (this.audio.codec === 'aac-eld') {
|
|
144
|
+
this.audio.sampleRate = 16; // the one AAC-ELD config HAP cameras share; see transcoder.js
|
|
145
|
+
}
|
|
146
|
+
this.forwardAudio = Boolean(audio && (opus || this.transcodeAudio));
|
|
147
|
+
if (this.forwardAudio) {
|
|
148
|
+
audio.setDirection('sendonly');
|
|
149
|
+
await audio.sender.replaceTrack(this.audioTrack);
|
|
150
|
+
} else {
|
|
151
|
+
transceivers.filter((t) => t.kind === 'audio').forEach((t) => t.setDirection('inactive'));
|
|
152
|
+
if (codecs.length && !opus) {
|
|
153
|
+
debug('camera audio can\'t be converted without ffmpeg, streaming video only', this.sessionId, codecs.map((c) => c.codec).join(','));
|
|
154
|
+
}
|
|
155
|
+
}
|
|
156
|
+
video.sender.onPictureLossIndication.subscribe(() => debug('PLI from Alexa', this.sessionId));
|
|
157
|
+
|
|
158
|
+
// Start the camera while ICE gathers, so video is flowing when Alexa connects.
|
|
159
|
+
const [, answer] = await Promise.all([this._startCamera(), this.pc.createAnswer()]);
|
|
160
|
+
await this.pc.setLocalDescription(answer);
|
|
161
|
+
await this._waitForCandidates();
|
|
162
|
+
const sdp = this.pc.localDescription.sdp;
|
|
163
|
+
debug('answer ready', this.sessionId, Date.now() - started, 'ms', (sdp.match(/a=candidate/g) || []).length, 'candidates');
|
|
164
|
+
return sdp;
|
|
165
|
+
}
|
|
166
|
+
|
|
167
|
+
async _startCamera() {
|
|
168
|
+
const { SrtpSession, SrtcpSession, RtpPacket, isRtcp } = loadWerift();
|
|
169
|
+
const address = await localAddressFor(this.stream.host);
|
|
170
|
+
this.socket = await bindSocket(address);
|
|
171
|
+
const port = this.socket.address().port;
|
|
172
|
+
const key = crypto.randomBytes(16);
|
|
173
|
+
const salt = crypto.randomBytes(14);
|
|
174
|
+
let audioPort = port;
|
|
175
|
+
if (this.transcodeAudio) {
|
|
176
|
+
this.transcoder = new AacEldToOpus({ log: this.log });
|
|
177
|
+
audioPort = await this.transcoder.prepare(address);
|
|
178
|
+
}
|
|
179
|
+
const camera = await this.stream.setup({ address, videoPort: port, audioPort, srtpKey: key, srtpSalt: salt });
|
|
180
|
+
this.camera = camera;
|
|
181
|
+
|
|
182
|
+
// The camera encrypts with the key we sent; we send RTCP with the key it answered with.
|
|
183
|
+
// Video and audio each get their own SRTP context.
|
|
184
|
+
const keys = { localMasterKey: camera.srtpKey, localMasterSalt: camera.srtpSalt, remoteMasterKey: key, remoteMasterSalt: salt };
|
|
185
|
+
const audioKeys = { localMasterKey: camera.audioSrtpKey, localMasterSalt: camera.audioSrtpSalt, remoteMasterKey: key, remoteMasterSalt: salt };
|
|
186
|
+
this.srtp = new SrtpSession({ keys, profile: 1 });
|
|
187
|
+
this.srtcp = new SrtcpSession({ keys, profile: 1 });
|
|
188
|
+
this.audioSrtp = new SrtpSession({ keys: audioKeys, profile: 1 });
|
|
189
|
+
this.audioSrtcp = new SrtcpSession({ keys: audioKeys, profile: 1 });
|
|
190
|
+
this.socket.on('message', (msg) => {
|
|
191
|
+
try {
|
|
192
|
+
if (isRtcp(msg)) {
|
|
193
|
+
return; // Camera sender reports aren't needed: werift writes its own toward Alexa
|
|
194
|
+
}
|
|
195
|
+
if (msg.length >= 12 && msg.readUInt32BE(8) === camera.audioSsrc) {
|
|
196
|
+
if (this.forwardAudio && !this.transcodeAudio) {
|
|
197
|
+
const audioPacket = RtpPacket.deSerialize(this.audioSrtp.decrypt(msg));
|
|
198
|
+
this.stats.audioPackets++;
|
|
199
|
+
this.stats.lastAudioSequence = audioPacket.header.sequenceNumber;
|
|
200
|
+
this.audioTrack.writeRtp(audioPacket);
|
|
201
|
+
}
|
|
202
|
+
return;
|
|
203
|
+
}
|
|
204
|
+
const packet = RtpPacket.deSerialize(this.srtp.decrypt(msg));
|
|
205
|
+
this.stats.packets++;
|
|
206
|
+
this.stats.bytes += msg.length;
|
|
207
|
+
this.stats.lastSequence = packet.header.sequenceNumber;
|
|
208
|
+
if (isKeyframe(packet.payload)) {
|
|
209
|
+
this.stats.keyframes++;
|
|
210
|
+
}
|
|
211
|
+
this.track.writeRtp(packet);
|
|
212
|
+
} catch (err) {
|
|
213
|
+
this.stats.dropped++;
|
|
214
|
+
if (this.stats.dropped === 1) {
|
|
215
|
+
debug('dropping camera packets', this.sessionId, err.message);
|
|
216
|
+
}
|
|
217
|
+
}
|
|
218
|
+
});
|
|
219
|
+
this.socket.on('error', (err) => debug('camera socket error', this.sessionId, err.message));
|
|
220
|
+
|
|
221
|
+
if (this.transcodeAudio) {
|
|
222
|
+
this.transcoder.start({
|
|
223
|
+
cameraAddress: camera.address, srtpKey: key, srtpSalt: salt, payloadType: 110,
|
|
224
|
+
onRtp: (packet) => {
|
|
225
|
+
this.stats.audioPackets++;
|
|
226
|
+
this.audioTrack.writeRtp(packet);
|
|
227
|
+
},
|
|
228
|
+
});
|
|
229
|
+
}
|
|
230
|
+
await this.stream.start(Object.assign({}, this.video, { audio: this.audio }));
|
|
231
|
+
// Each RTCP stream gets its own sender SSRC: two SRTCP contexts sharing one would repeat packet
|
|
232
|
+
// indexes, which a camera decrypting both with one context drops as replays.
|
|
233
|
+
this.rtcpSsrc = crypto.randomBytes(4).readUInt32BE();
|
|
234
|
+
this.audioRtcpSsrc = (this.rtcpSsrc + 1) >>> 0;
|
|
235
|
+
this.rtcpTimer = setInterval(() => this._sendReceiverReport(), RTCP_INTERVAL);
|
|
236
|
+
this.rtcpTimer.unref();
|
|
237
|
+
}
|
|
238
|
+
|
|
239
|
+
_sendReceiverReport() {
|
|
240
|
+
const { RtcpRrPacket, RtcpReceiverInfo } = loadWerift();
|
|
241
|
+
const report = (ssrc, highestSequence, sender = this.rtcpSsrc) => new RtcpRrPacket({
|
|
242
|
+
ssrc: sender,
|
|
243
|
+
reports: [new RtcpReceiverInfo({ ssrc, fractionLost: 0, packetsLost: 0, highestSequence: highestSequence || 0, jitter: 0, lsr: 0, dlsr: 0 })],
|
|
244
|
+
}).serialize();
|
|
245
|
+
this.socket.send(this.srtcp.encrypt(report(this.camera.ssrc, this.stats.lastSequence)), this.camera.videoPort, this.camera.address);
|
|
246
|
+
if (this.stats.audioPackets && !this.transcodeAudio) { // ffmpeg reports on the audio it converts
|
|
247
|
+
this.socket.send(this.audioSrtcp.encrypt(report(this.camera.audioSsrc, this.stats.lastAudioSequence, this.audioRtcpSsrc)), this.camera.audioPort, this.camera.address);
|
|
248
|
+
}
|
|
249
|
+
}
|
|
250
|
+
|
|
251
|
+
async connected() {
|
|
252
|
+
debug('connected', this.sessionId, this.stats);
|
|
253
|
+
}
|
|
254
|
+
|
|
255
|
+
async close() {
|
|
256
|
+
clearInterval(this.rtcpTimer);
|
|
257
|
+
if (this.transcoder) {
|
|
258
|
+
this.transcoder.stop();
|
|
259
|
+
}
|
|
260
|
+
if (this.socket) {
|
|
261
|
+
this.socket.close();
|
|
262
|
+
this.socket = undefined;
|
|
263
|
+
}
|
|
264
|
+
if (this.track) {
|
|
265
|
+
this.track.stop();
|
|
266
|
+
this.audioTrack.stop();
|
|
267
|
+
}
|
|
268
|
+
if (this.pc) {
|
|
269
|
+
await this.pc.close();
|
|
270
|
+
}
|
|
271
|
+
debug('closed', this.sessionId, this.stats);
|
|
272
|
+
}
|
|
273
|
+
}
|
|
274
|
+
|
|
275
|
+
// An IDR slice, alone or in a STAP-A or the first FU-A fragment.
|
|
276
|
+
function isKeyframe(payload) {
|
|
277
|
+
if (!payload || payload.length < 2) {
|
|
278
|
+
return false;
|
|
279
|
+
}
|
|
280
|
+
const type = payload[0] & 0x1f;
|
|
281
|
+
if (type === 5) return true;
|
|
282
|
+
if (type === 28) return (payload[1] & 0x80) !== 0 && (payload[1] & 0x1f) === 5;
|
|
283
|
+
if (type === 24) {
|
|
284
|
+
for (let i = 1; i + 2 < payload.length;) {
|
|
285
|
+
const size = payload.readUInt16BE(i);
|
|
286
|
+
if ((payload[i + 2] & 0x1f) === 5) return true;
|
|
287
|
+
i += 2 + size;
|
|
288
|
+
}
|
|
289
|
+
}
|
|
290
|
+
return false;
|
|
291
|
+
}
|
|
292
|
+
|
|
293
|
+
function createBridge(context) {
|
|
294
|
+
return new WebRTCBridge(context);
|
|
295
|
+
}
|
|
296
|
+
|
|
297
|
+
module.exports = { createBridge, WebRTCBridge, isKeyframe };
|