From b44f12690a73e62e866f940930141f56ff267aa9 Mon Sep 17 00:00:00 2001 From: starkillerOG Date: Wed, 11 Nov 2026 19:46:41 +0100 Subject: [PATCH] Fix Reolink playback for NVRs and Hubs (#191946) --- .../components/reolink/media_source.py | 6 +- homeassistant/components/reolink/views.py | 76 ++++++++ tests/components/reolink/test_views.py | 173 +++++++++++++++++- 3 files changed, 250 insertions(+), 5 deletions(-) diff --git a/homeassistant/components/reolink/media_source.py b/homeassistant/components/reolink/media_source.py index 6af6dbc20f39..2d2aef295e00 100644 --- a/homeassistant/components/reolink/media_source.py +++ b/homeassistant/components/reolink/media_source.py @@ -78,12 +78,10 @@ class ReolinkVODMediaSource(MediaSource): host = get_host(self.hass, config_entry_id) def get_vod_type() -> VodRequestType: - if filename.endswith((".mp4", ".vref")) or host.api.is_hub: - if host.api.is_nvr: - return VodRequestType.DOWNLOAD - return VodRequestType.PLAYBACK if host.api.is_nvr: return VodRequestType.NVR_DOWNLOAD + if filename.endswith((".mp4", ".vref")): + return VodRequestType.PLAYBACK return VodRequestType.RTMP vod_type = get_vod_type() diff --git a/homeassistant/components/reolink/views.py b/homeassistant/components/reolink/views.py index 8aa3ba831eed..59138f8ed9af 100644 --- a/homeassistant/components/reolink/views.py +++ b/homeassistant/components/reolink/views.py @@ -1,19 +1,25 @@ """Reolink Integration views.""" +import asyncio from base64 import urlsafe_b64decode, urlsafe_b64encode +from contextlib import aclosing +from datetime import datetime from http import HTTPStatus import logging +from typing import TYPE_CHECKING from aiohttp import ClientError, ClientTimeout, web from reolink_aio.enums import VodRequestType from reolink_aio.exceptions import ReolinkError +from homeassistant.components.ffmpeg import get_ffmpeg_manager from homeassistant.components.http import HomeAssistantView from homeassistant.components.media_source import Unresolvable from homeassistant.core import HomeAssistant, callback from homeassistant.helpers.aiohttp_client import async_get_clientsession from homeassistant.util.ssl import SSLCipherList +from .host import ReolinkHost from .util import get_host _LOGGER = logging.getLogger(__name__) @@ -55,6 +61,7 @@ class PlaybackProxyView(HomeAssistantView): ssl_cipher=SSLCipherList.INSECURE, ) self._vod_type: str | None = None + self._mp4_streams: dict[str, asyncio.Task] = {} async def get( self, @@ -83,6 +90,11 @@ class PlaybackProxyView(HomeAssistantView): _LOGGER.warning(err_str) return web.Response(body=err_str, status=HTTPStatus.BAD_REQUEST) + if vod_type == VodRequestType.NVR_DOWNLOAD.value: + return await self._async_stream_mp4( + request, host, ch, stream_res, filename_decoded + ) + try: _mime_type, reolink_url = await host.api.get_vod_source( ch, filename_decoded, stream_res, VodRequestType(vod_type) @@ -196,3 +208,67 @@ class PlaybackProxyView(HomeAssistantView): await response.write_eof() return response + + async def _async_stream_mp4( + self, + request: web.Request, + host: ReolinkHost, + channel: int, + stream_res: str, + filename: str, + ) -> web.StreamResponse: + """Stream a NVR recording as fragmented mp4 using the Baichuan protocol.""" + start_time, end_time = filename.split("_", 1) + mp4_stream = host.api.baichuan.stream_mp4( + channel, + datetime.strptime(start_time, "%Y%m%d%H%M%S"), + datetime.strptime(end_time, "%Y%m%d%H%M%S"), + stream_res, + get_ffmpeg_manager(self.hass).binary, + ) + _LOGGER.debug( + "Opening Baichuan VOD stream from %s: %s", + host.api.camera_name(channel), + filename, + ) + + # the NVR allows only one download at a time, stop the previous playback + if (previous := self._mp4_streams.get(host.unique_id)) is not None: + _LOGGER.debug( + "Reolink %s: Cancelling previous Baichuan recording stream", + host.api.nvr_name, + ) + previous.cancel() + task = asyncio.current_task() + if TYPE_CHECKING: + assert task is not None + self._mp4_streams[host.unique_id] = task + + try: + # aclosing: stop ffmpeg and the download directly when the client disconnects + async with aclosing(mp4_stream): + # get the first part before sending the headers, to be able to return an error status + try: + first_part = await anext(mp4_stream, b"") + except ReolinkError as err: + _LOGGER.warning("Reolink playback proxy error: %s", str(err)) + return web.Response(body=str(err), status=HTTPStatus.BAD_REQUEST) + + response = web.StreamResponse(headers={"Content-Type": "video/mp4"}) + await response.prepare(request) + await response.write(first_part) + try: + async for part in mp4_stream: + await response.write(part) + except ReolinkError as err: + _LOGGER.warning( + "Reolink playback error while streaming mp4 from %s: %s", + host.api.camera_name(channel), + str(err), + ) + + await response.write_eof() + return response + finally: + if self._mp4_streams.get(host.unique_id) is task: + del self._mp4_streams[host.unique_id] diff --git a/tests/components/reolink/test_views.py b/tests/components/reolink/test_views.py index 91e0311ad238..3df029b9319e 100644 --- a/tests/components/reolink/test_views.py +++ b/tests/components/reolink/test_views.py @@ -1,5 +1,8 @@ """Tests for the Reolink views platform.""" +import asyncio +from collections.abc import AsyncGenerator +from datetime import datetime from http import HTTPStatus import logging from typing import Any, cast @@ -10,7 +13,7 @@ import pytest from pytest_homeassistant.common import MockConfigEntry from pytest_homeassistant.typing import ClientSessionGenerator from reolink_aio.enums import VodRequestType -from reolink_aio.exceptions import ReolinkError +from reolink_aio.exceptions import ReolinkError, UnexpectedDataError from homeassistant.components.reolink.views import async_generate_playback_proxy_url from homeassistant.core import HomeAssistant @@ -32,6 +35,10 @@ TEST_VOD_TYPE = VodRequestType.PLAYBACK.value TEST_MIME_TYPE_MP4 = "video/mp4" TEST_URL = "http://test_url&token=test" TEST_ERROR = "TestError" +TEST_NVR_START = "20231114131200" +TEST_NVR_END = "20231114131700" +TEST_NVR_FILE_NAME = f"{TEST_NVR_START}_{TEST_NVR_END}" +TEST_NVR_VOD_TYPE = VodRequestType.NVR_DOWNLOAD.value def get_mock_session( @@ -263,3 +270,167 @@ async def test_playback_connect_error( response = cast(ClientResponse, await http_client.get(proxy_url)) assert response.status == HTTPStatus.BAD_REQUEST + + +@pytest.mark.parametrize( + "stream_res", + [ + pytest.param("sub", id="sub"), + pytest.param("main", id="main"), + pytest.param("autotrack_sub", id="autotrack_sub"), + pytest.param("telephoto_main", id="telephoto_main"), + ], +) +async def test_playback_baichuan( + hass: HomeAssistant, + reolink_host: MagicMock, + config_entry: MockConfigEntry, + hass_client: ClientSessionGenerator, + stream_res: str, +) -> None: + """Test NVR playback proxy URL using the Baichuan mp4 stream.""" + + async def stream_mp4(*args: Any) -> AsyncGenerator[bytes]: + yield b"test" + yield b"test" + + reolink_host.baichuan.stream_mp4 = MagicMock(side_effect=stream_mp4) + + assert await hass.config_entries.async_setup(config_entry.entry_id) + await hass.async_block_till_done() + + proxy_url = async_generate_playback_proxy_url( + config_entry.entry_id, + TEST_CHANNEL, + TEST_NVR_FILE_NAME, + stream_res, + TEST_NVR_VOD_TYPE, + ) + + http_client = await hass_client() + response = cast(ClientResponse, await http_client.get(proxy_url)) + + assert await response.content.read() == b"testtest" + assert response.status == 200 + assert response.content_type == TEST_MIME_TYPE_MP4 + reolink_host.baichuan.stream_mp4.assert_called_once_with( + int(TEST_CHANNEL), + datetime(2023, 11, 14, 13, 12, 0), + datetime(2023, 11, 14, 13, 17, 0), + stream_res, + "ffmpeg", + ) + reolink_host.get_vod_source.assert_not_called() + + +async def test_playback_baichuan_start_error( + hass: HomeAssistant, + reolink_host: MagicMock, + config_entry: MockConfigEntry, + hass_client: ClientSessionGenerator, +) -> None: + """Test NVR playback proxy URL with an error before the first mp4 data.""" + + async def stream_mp4(*args: Any) -> AsyncGenerator[bytes]: + raise UnexpectedDataError(TEST_ERROR) + yield b"" # pylint: disable=unreachable + + reolink_host.baichuan.stream_mp4 = MagicMock(side_effect=stream_mp4) + + assert await hass.config_entries.async_setup(config_entry.entry_id) + await hass.async_block_till_done() + + proxy_url = async_generate_playback_proxy_url( + config_entry.entry_id, + TEST_CHANNEL, + TEST_NVR_FILE_NAME, + TEST_STREAM, + TEST_NVR_VOD_TYPE, + ) + + http_client = await hass_client() + response = cast(ClientResponse, await http_client.get(proxy_url)) + + assert await response.content.read() == bytes(TEST_ERROR, "utf-8") + assert response.status == HTTPStatus.BAD_REQUEST + + +async def test_playback_baichuan_stream_error( + hass: HomeAssistant, + reolink_host: MagicMock, + config_entry: MockConfigEntry, + hass_client: ClientSessionGenerator, + caplog: pytest.LogCaptureFixture, +) -> None: + """Test NVR playback proxy URL with an error while streaming the mp4.""" + + async def stream_mp4(*args: Any) -> AsyncGenerator[bytes]: + yield b"test" + raise UnexpectedDataError(TEST_ERROR) + + reolink_host.baichuan.stream_mp4 = MagicMock(side_effect=stream_mp4) + + assert await hass.config_entries.async_setup(config_entry.entry_id) + await hass.async_block_till_done() + + proxy_url = async_generate_playback_proxy_url( + config_entry.entry_id, + TEST_CHANNEL, + TEST_NVR_FILE_NAME, + TEST_STREAM, + TEST_NVR_VOD_TYPE, + ) + + http_client = await hass_client() + response = cast(ClientResponse, await http_client.get(proxy_url)) + + assert await response.content.read() == b"test" + assert response.status == 200 + assert "Reolink playback error while streaming mp4" in caplog.text + + +async def test_playback_baichuan_stop_previous( + hass: HomeAssistant, + reolink_host: MagicMock, + config_entry: MockConfigEntry, + hass_client: ClientSessionGenerator, +) -> None: + """Test a new NVR playback stops the previous one, the NVR allows only one download.""" + first_closed = asyncio.Event() + + async def first_stream(*args: Any) -> AsyncGenerator[bytes]: + try: + yield b"first" + await asyncio.Event().wait() + finally: + first_closed.set() + + async def second_stream(*args: Any) -> AsyncGenerator[bytes]: + yield b"second" + + reolink_host.baichuan.stream_mp4 = MagicMock( + side_effect=[first_stream(), second_stream()] + ) + + assert await hass.config_entries.async_setup(config_entry.entry_id) + await hass.async_block_till_done() + + proxy_url = async_generate_playback_proxy_url( + config_entry.entry_id, + TEST_CHANNEL, + TEST_NVR_FILE_NAME, + TEST_STREAM, + TEST_NVR_VOD_TYPE, + ) + + http_client = await hass_client() + first_response = cast(ClientResponse, await http_client.get(proxy_url)) + assert first_response.status == 200 + assert not first_closed.is_set() + + second_response = cast(ClientResponse, await http_client.get(proxy_url)) + + assert await second_response.content.read() == b"second" + assert second_response.status == 200 + assert first_closed.is_set() + first_response.close()