Skip to content

Add HomeKit Secure Video recording to HomeKit cameras - #190676

Merged
bdraco merged 26 commits into
home-assistant:devfrom
RaHehl:homekit-recording-ffmpeg-recipe
Nov 13, 2026
Merged

bdraco merged 26 commits into
home-assistant:devfrom
RaHehl:homekit-recording-ffmpeg-recipe

Conversation

@RaHehl

@RaHehl RaHehl commented Nov 5, 2026 •

Copy link
Copy Markdown
Contributor

Proposed change

This adds HomeKit Secure Video recording to HomeKit cameras in accessory mode. I added the recording support to HAP-python for this (ikalchev/HAP-python#493 and its follow-ups).

Opt-in per camera with the camera mode in the options flow, needs a linked motion sensor. On a recording request, ffmpeg encodes the stream to H.264 as selected by the home hub, or copies native H.264, and sends it as fragmented MP4. Turning the camera off in the Home app also stops live video and snapshots, and a running recording ends when the hub changes the recording or audio permission. A prebuffer is not included and could be a follow-up.

Type of change

  • Dependency upgrade
  • Bugfix (non-breaking change which fixes an issue)
  • New integration (thank you!)
  • New feature (which adds functionality to an existing integration)
  • Deprecation (breaking change to happen in the future)
  • Breaking change (fix/feature causing existing functionality to break)
  • Code quality improvements to existing code or addition of tests

Additional information

#190234 builds on the same API but also changes stream, camera and go2rtc; this PR stays inside HomeKit.

Tested with Apple Home, a home hub and a UniFi Protect G4 Dome sending H.264 with native H.264 enabled: motion on the camera's sensor produced a recording in the Home app, closed normally by the hub. Transcoding an H.265 source did not finish within the hub's time limit, because without a prebuffer the first fragment waits for the camera's next keyframe. That case is left for a follow-up.

Checklist

  • I understand the code I am submitting and can explain how it works.
  • The code change is tested and works locally.
  • Local tests pass. Your PR cannot be merged unless tests pass
  • There is no commented out code in this PR.
  • I have followed the development checklist
  • I have followed the perfect PR recommendations
  • The code has been formatted using Ruff (ruff format homeassistant tests)
  • Tests have been added to verify that the new code works.
  • Any generated code has been carefully reviewed for correctness and compliance with project standards.

If user exposed functionality or configuration variables are added/changed:

If the code communicates with devices, web services, or third-party tools:

  • The manifest file has all fields filled out correctly.
    Updated and included derived files by running: python3 -m script.hassfest.
  • New or updated dependencies have been added to requirements_all.txt.
    Updated by running python3 -m script.gen_requirements_all.
  • For the updated dependencies a diff between library versions and ideally a link to the changelog/release notes is added to the PR description.

To help with the load of incoming pull requests:

A camera in accessory mode can record to HomeKit Secure Video when its
motion sensor detects motion. The option is set per camera in the options
flow. Each recording runs one ffmpeg that encodes what the home hub
selects, or copies the camera stream. Diagnostics show the recording
state.
Copilot AI balanced review requested due to automatic review settings November 5, 2026 16:27
@home-assistant home-assistant Bot added cla-signed has-tests integration: homekit new-feature Top 100 Integration is ranked within the top 100 by usage Top 200 Integration is ranked within the top 200 by usage Top 50 Integration is ranked within the top 50 by usage labels Nov 5, 2026
@home-assistant

home-assistant Bot commented Nov 5, 2026

Copy link
Copy Markdown
Contributor

Hey there @bdraco, mind taking a look at this pull request as it has been labeled with an integration (homekit) you are listed as a code owner for? Thanks!

Code owner commands

Code owners of homekit can trigger bot actions by commenting:

  • @home-assistant close Closes the pull request.
  • @home-assistant mark-draft Mark the pull request as draft.
  • @home-assistant ready-for-review Remove the draft status from the pull request.
  • @home-assistant rename Awesome new title Renames the pull request.
  • @home-assistant reopen Reopen the pull request.
  • @home-assistant unassign homekit Removes the current integration label and assignees on the pull request, add the integration domain after the command.
  • @home-assistant update-branch Update the pull request branch with the base branch.
  • @home-assistant add-label needs-more-information Add a label (needs-more-information, problem in dependency, problem in custom component, problem in config, problem in device, feature-request) to the pull request.
  • @home-assistant remove-label needs-more-information Remove a label (needs-more-information, problem in dependency, problem in custom component, problem in config, problem in device, feature-request) on the pull request.

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 Changes recommended

The unawaited stream.kill() call can leave ffmpeg running and recording cleanup blocked indefinitely in process.wait(), while the synchronous test mock masks the failure.

1 open issue
What changed in this PR

Adds opt-in HomeKit Secure Video recording for cameras exposed as standalone accessories, triggered by a linked motion sensor. The feature depends on an upcoming HAP-python release and does not provide prebuffering.

Changes:

  • Adds per-camera recording configuration to the options flow.
  • Implements ffmpeg recording, transport lifecycle handling, and diagnostics.
  • Adds tests for configuration, recording behavior, failures, and cleanup.
File Description
tests/​components/​homekit/​test_type_cameras.py Tests recording arguments, lifecycle, failures, and diagnostics.
tests/​components/​homekit/​test_diagnostics.py Tests recording state in integration diagnostics.
tests/​components/​homekit/​test_config_flow.py Tests enabling and disabling recording through options.
homeassistant/​components/​homekit/​type_cameras.py Implements recording streams and transport management.
homeassistant/​components/​homekit/​strings.json Adds recording option text and requirements.
homeassistant/​components/​homekit/​diagnostics.py Includes recording diagnostics for enabled cameras.
homeassistant/​components/​homekit/​const.py Defines the recording setting and disabled default.
homeassistant/​components/​homekit/​config_flow.py Adds the recording selector for accessory-mode cameras.

Review effort: Balanced

Copilot AI balanced review requested due to automatic review settings November 5, 2026 17:31
@RaHehl

RaHehl commented Nov 5, 2026

Copy link
Copy Markdown
Contributor Author

Tested locally with HAP-python from RaHehl/HAP-python@hksv-ha-preview (c175792) and a home hub: a camera in accessory mode records on motion, the clips show up in the Home app, and face recognition works on them. The recording state survives a restart of Home Assistant.

The second commit fixes an error that was logged when a recording ended (two readers on the ffmpeg stderr).

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 Changes recommended

Unsanitized ffmpeg stderr can expose camera passwords and URL access tokens in debug logs and retained recording error or stall messages.

1 open issue
1 resolved since last review

Review effort: Balanced

Copilot AI balanced review requested due to automatic review settings November 5, 2026 17:41
@halibsbot

halibsbot commented Nov 5, 2026 •

Copy link
Copy Markdown

Previous review — superseded by a newer review below.

@halibsbot halibsbot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Tip

No blocking issues found — ready to merge.

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🔵 Needs a closer look

HKSV depends on six unreleased HAP-python changes, while mocked tests leave negotiation, recording completion, cleanup, and privacy controls requiring human end-to-end validation with a real HomeKit hub and ffmpeg.

No open issues 🎉

1 resolved since last review

Review effort: Balanced

@RaHehl

RaHehl commented Nov 5, 2026

Copy link
Copy Markdown
Contributor Author

2, 3 and 4 are in c21a055. 1 is handled in HAP-python (ikalchev/HAP-python#502): a start still binding when a stop comes in closes its own listener. 5 is intended, the service set only follows the configuration so the accessory database does not change at runtime.

Copilot AI balanced review requested due to automatic review settings November 5, 2026 18:03

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🔵 Needs a closer look

The stderr handling can discard a legitimate error after an oversized line, hiding the failure’s cause, and needs targeted draining plus a regression test for both lines arriving together.

No open issues 🎉

1 resolved since last review

Review effort: Balanced

Copilot AI balanced review requested due to automatic review settings November 7, 2026 22:13
@halibsbot

halibsbot commented Nov 7, 2026 •

Copy link
Copy Markdown

PR Review — Add HomeKit Secure Video recording to HomeKit cameras

Merge-ready once the HAP-python bump in #191104 lands. The two stderr findings from the last review are fixed in 15a0101, and the two suggestions below remain.

What the PR does well:

  • _async_collect_stderr now calls readuntil() and handles LimitOverrunError. Calling readexactly(err.consumed) handles both cases correctly. If the newline is already in the buffer, only the bare \n is skipped and the next real ffmpeg line is kept. If the newline has not arrived yet, the tail of the overlong line is skipped. The parametrized test covers both cases.
  • _async_recording_failed now waits for stderr to drain before checking the return code, so "ended without video" also reports the last ffmpeg lines.
  • These earlier fixes are still in place: URL redaction, one warning per failure kind, stopping the stderr reader before kill(), refusing streams and snapshots while the camera is off, ending a recording when the hub changes its permissions, recording offered only in accessory mode, and the error for a bare -vf with no filter.

Remaining suggestions (non-blocking):

  • _async_end_session has no try/finally, so a failed teardown leaves the stream slot unfreed.
  • Errors from the stop-transport task, and non-OSError errors from the start task, go unreported on an in-place reload.

Not raised again:

  • Options-flow validation of the motion sensor: dismissed by @RaHehl ("The motion sensor is linked at runtime... so the flow cannot check it").
  • Recording staying advertised when the listener cannot bind: dismissed earlier by @RaHehl.
  • The manifest bump: it belongs to Bump HAP-python to 5.2.0 #191104, per @RaHehl.

✅ Resolved since last review (2)

Previously-flagged issues verified fixed
  • homeassistant/components/homekit/type_cameras.py:900 skip_line can drop a real stderr line after an overlong line
  • homeassistant/components/homekit/type_cameras.py:886 "ended without video" is logged before stderr is drained

🟢 Suggestions

1. End-session task skips freeing the slot if teardown raises
homeassistant/components/homekit/type_cameras.py:774-780

Suggested fix: put stop_stream and _close_talkback in a try/finally so the ownership check and set_streaming_available always run.

homekit_camera_active_changed starts this as a background task and never awaits it. If proxy.async_stop(), stream.close() or _close_talkback raises, the task stops early:

  • The slot stays STREAMING until the controller sends its stop.
  • The error only shows up as an unhandled task exception, with no entity context.

This was still open at 15a0101. Not blocking: the controller's own stop request frees the slot eventually.

    async def _async_end_session(self, session_info: dict[str, Any]) -> None:
        """End a live stream, the controller removes the session with its stop."""
        await self.stop_stream(session_info)
        self._close_talkback(session_info)
        # The controller may have started a new session on this slot meanwhile.
        if self.sessions.get(session_info["id"]) is session_info:
            self.set_streaming_available(session_info["stream_idx"])
2. Stop-transport errors go unreported on an in-place reload
homeassistant/components/homekit/type_cameras.py:704-709

Suggested fix: catch and log OSError in _async_stop_recording_transport, the same way _async_start_recording_transport does.

An in-place reload only calls async_stop(). Only stop() awaits _recording_transport_stop, so on a reload nothing does. If stop_recording_transport fails, the error only appears as a generic background-task error. If the listener stays bound, the next start logs "Address in use" with nothing pointing back to the cause.

There is a related gap: asyncio.wait never retrieves the exception of the start task. A non-OSError failure from start_recording_transport can therefore stay silent until garbage collection.

This was still open at 15a0101.

if self._recording_transport_start:
    await asyncio.wait({self._recording_transport_start})
await self.stop_recording_transport()

Checklist

  • No credential leakage in logs
  • Resource cleanup on error and cancel paths — suggestion #1, suggestion #2
  • No shell injection in ffmpeg args
  • Failure logging stays visible
  • Malformed stream source handled without traceback
  • New branches covered by tests
  • PR template complete

Silent Failure Analysis

🟡 **3. MEDIUM** — capability advertised after its backing transport failed
homeassistant/components/homekit/type_cameras.py:703-720

Risk: When the HDS listener fails to bind, secure_video stays True and CameraRecordingManagement is still advertised, so the hub keeps selecting a recording config that can never be delivered. Any non-OSError from the start task is never retrieved, because asyncio.wait() does not read results, so it is not logged at all.

try:
    await self.start_recording_transport()
except OSError as err:
    _LOGGER.error("[%s] HomeKit Secure Video cannot listen for recordings: %s", ...)
...
await asyncio.wait({self._recording_transport_start})

Fix: Catch the remaining exceptions too (_LOGGER.exception), and record the failure state (for example self._recording_problem or a flag shown in diagnostics), or mark recording inactive so the failure shows somewhere besides one startup log line.

🟡 **4. MEDIUM** — fire-and-forget background task
homeassistant/components/homekit/type_cameras.py:760-780

Risk: _async_end_session is never awaited or checked. If stop_stream (for example proxy.async_stop()) or _close_talkback raises, the error only shows as a 'Task exception was never retrieved' message when the task is garbage-collected, and set_streaming_available is skipped, so the stream slot stays in STREAMING.

for session_info in list(self.sessions.values()):
    if "stream" in session_info:
        self.hass.async_create_background_task(
            self._async_end_session(session_info), ...)

Fix: Wrap the body of _async_end_session in try/except with _LOGGER.exception, and free the slot in a finally (still behind the same-session check) so a failed stop cannot leave the slot stuck.

🟡 **5. MEDIUM** — unretrieved task exception
homeassistant/components/homekit/type_cameras.py:862-866

Risk: asyncio.wait() never calls result(), so if _async_collect_stderr crashes (for example an unexpected reader error), the exception is dropped and the failure logs that rely on the stderr deque silently lose their ffmpeg context.

stderr_task.cancel()
await asyncio.wait({stderr_task})
...
await asyncio.wait({stderr_task}, timeout=RECORDING_STDERR_DRAIN_SECONDS)

Fix: Once the task is done and not cancelled, check stderr_task.exception() and log it, or catch and log unexpected exceptions inside _async_collect_stderr.


Automated review by Kōan (Claude) HEAD=15a0101 47s

@halibsbot halibsbot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Tip

No blocking issues found — ready to merge.

@RaHehl

RaHehl commented Nov 7, 2026

Copy link
Copy Markdown
Contributor Author

On the remaining two: stop_stream already catches errors from closing and killing ffmpeg, and the controller's own stop frees the slot, so a try/finally would only mark a slot free while ffmpeg may still run. Errors in the transport tasks are logged by Home Assistant as background task errors, and a failed bind is logged and shows as transport_port: None in diagnostics.

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🔵 Needs a closer look

Mocked HDS and ffmpeg tests and native-H.264-only device coverage leave privacy-sensitive cancellation during permission changes or reloads, plus transcoded and hardware-encoded delivery, requiring human validation.

No open issues 🎉

Review effort: Balanced

@RaHehl
RaHehl marked this pull request as ready for review November 7, 2026 22:18
@RaHehl
RaHehl requested a review from bdraco as a code owner November 7, 2026 22:18
@home-assistant

home-assistant Bot commented Nov 10, 2026 •

Copy link
Copy Markdown
Contributor

👋 Hi! Thanks for contributing to Home Assistant.

This is your PR dashboard which flags anything you need to address before your PR can be reviewed. Once everything is green, you can press the 'Ready for review' button at the bottom of the page to notify reviewers to take a look.

More information about this dashboard

This dashboard automatically updates on every change to this PR and reevaluates the rules as you go. Until everything has been addressed, the bot will keep the PR in draft.

Skip a check that doesn't apply

If you think a check doesn't apply to your PR (or the rule is bugged), comment @home-assistant ignore "<check name>" "<reason>". The check name as shown in the table above. This will mark the check as ignored and let you put your PR in 'Ready for review'; @home-assistant unignore "<check name>" restores the rule.

Bot commands

Reply with @home-assistant <command>. Several commands can be stacked, one per line:

  • update — Re-runs the bot's checks on the issue or pull request.
  • ignore — Waives a dashboard check: ignore "<check name>" "<reason>". (author) — e.g. @home-assistant ignore "Merge conflicts" "Broken rule, no merge conflicts present"
  • unignore — Restores a waived dashboard check: unignore "<check name>". (author) — e.g. @home-assistant unignore "Merge conflicts"
  • unassign — Removes the given integration domain's label and its code owners from the assignees. (author or code owners) — e.g. @home-assistant unassign "opensky"
  • close — Closes the issue or pull request. (code owners)
  • reopen — Reopens the issue or pull request. (code owners)
  • rename — Renames the issue or pull request: rename "<new title>". (code owners) — e.g. @home-assistant rename "A more descriptive title"
  • add-label — Adds a label (needs-more-information, problem in dependency, problem in custom component, problem in config, problem in device, feature-request) to the issue or pull request. (code owners) — e.g. @home-assistant add-label "needs-more-information"
  • remove-label — Removes a label (needs-more-information, problem in dependency, problem in custom component, problem in config, problem in device, feature-request) from the issue or pull request. (code owners) — e.g. @home-assistant remove-label "needs-more-information"
  • mark-draft — Marks the pull request as draft. (code owners)
  • update-branch — Updates the pull request branch with the base branch. (code owners)

Checks

✨ Everything's in order!

5 checks passed (5 skipped)
Status Check Details
✅ Forbidden files No forbidden files.
✅ Merge conflicts Merge status is being recalculated by GitHub.
✅ Merge target This PR targets dev.
✅ Type of change Type of change: new-feature
✅ CLA Everyone involved has signed the CLA.
➖ New integration validation Not a new-integration PR.
➖ Single new platform No new platforms added.
➖ Documentation Not a new integration or platform — no documentation PR required.
➖ Code owner approval Touches no platinum integration — no code-owner approval required.
➖ Blocking: awaiting-frontend awaiting-frontend label not set — nothing to block.

@halibsbot

Copy link
Copy Markdown

Note

No code changes since the last review (15a0101) — skipping. Push new commits or re-request a review to run again.

Copilot AI balanced review requested due to automatic review settings November 11, 2026 07:32

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟢 Approval recommended

No active review issues are reported for the opt-in HomeKit Secure Video recording change.

No open issues 🎉

Review effort: Balanced

Copilot AI balanced review requested due to automatic review settings November 11, 2026 07:51
@RaHehl

RaHehl commented Nov 11, 2026

Copy link
Copy Markdown
Contributor Author

Changed the Secure Video switch to a camera mode select, so H.265 can be added later as a third mode without migrating options:

Mode Live view Recording
standard H.264 none
secure_video H.264 H.264 (this PR)
hksv3 (later) H.265, up to 3 streams not yet

With up to 3 streams (high, medium, low) the Home app picks the quality per view and connection, e.g. full resolution at home, a smaller stream remote or in the camera grid, all copied from the camera without transcoding. This already works locally on top of this PR.

HKSV 3 recording doesn't work in any project yet (homebridge/hap-nodejs#1132, Scrypted). I tried it too: Apple's server accepts the segments and playlists, but the client never gets them, so the clips don't play.

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🔵 Needs a closer look

Human assessment is needed because shutdown cancellation during camera listener startup can leave a listener open and untracked despite the later wait in Camera.stop().

No open issues 🎉

Review effort: Balanced

@matthiasdebaat

Copy link
Copy Markdown
Member

Thanks for working on this! Tested it on my own setup.

Setup

  • Home Assistant OS on an N100, Home Assistant 2026.11.1 with this PR applied on top as a custom integration (HAP-python 5.2.0)
  • UniFi Protect G4 Doorbell Pro (1600x1200, 20 fps), accessory mode, native H.264 (copy), audio on
  • Linked motion sensor is the UniFi Protect event entity (event.*_motion_detection), linked doorbell sensor event.*_doorbell
  • Apple TV as home hub

What works

  • Recording: motion creates a clip in the Home app timeline that plays back fine
  • Doorbell press: notification with snapshot
  • Live view with audio. By eye it starts as fast as Scrypted
  • Load on the N100 is not noticeably higher while streaming or recording
  • No HomeKit or pyhap warnings or errors in the logs

Diagnostics after enabling recording: active: true, audio_active: true. The hub selected 1920x1080 at 30 fps, 2000 kbps, 4 second fragments, AAC audio. The camera sends 1600x1200 at 20 fps with copy, and recordings still worked.

Notes

  • When pairing, the Home app suggests "Stream & Allow Recording". Before I enabled Secure Video, choosing it failed with a generic "Error updating setting". Nothing pointed me to the option in Home Assistant, so users might think HKSV is broken. Could it be on by default for new cameras in accessory mode with a linked motion sensor and native H.264?
  • Audio is a separate opt-in, so recordings get a silent track unless you also enable audio.
  • Because I applied the PR on 2026.11.1, the camera options showed the existing "Camera mode" choice instead of the new Secure Video selector. Selecting HomeKit Secure Video there enabled recording. Probably not relevant on dev.
  • Push to talk on the doorbell does nothing, which I understand is out of scope here.

Not tested

  • Turning the camera off and changing recording or audio permissions during a recording
  • Recording after a restart
  • How much of the start of a clip is missing without a prebuffer, compared to Scrypted

@bdraco
bdraco merged commit 08920ec into home-assistant:dev Nov 13, 2026
36 checks passed
@balloob balloob added the noteworthy Marks a PR as noteworthy and should be in the release notes (in case it normally would not appear) label Nov 14, 2026
@github-actions github-actions Bot locked and limited conversation to collaborators Nov 15, 2026
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.

Labels

cla-signed has-tests integration: homekit new-feature noteworthy Marks a PR as noteworthy and should be in the release notes (in case it normally would not appear) Quality Scale: No score Top 50 Integration is ranked within the top 50 by usage Top 100 Integration is ranked within the top 100 by usage Top 200 Integration is ranked within the top 200 by usage

Projects

None yet

Development

Successfully merging this pull request may close these issues.

6 participants