Change locking boundaries for shared dict. Add a unit test.
[python_utils.git] / camera_utils.py
1 #!/usr/bin/env python3
2
3 """Utilities for dealing with webcam images."""
4
5 import logging
6 import platform
7 import subprocess
8 from typing import NamedTuple, Optional
9 import warnings
10
11 import cv2  # type: ignore
12 import numpy as np
13 import requests
14
15 import decorator_utils
16 import exceptions
17
18 logger = logging.getLogger(__name__)
19
20
21 class RawJpgHsv(NamedTuple):
22     """Raw image bytes, the jpeg image and the HSV (hue saturation value) image."""
23
24     raw: Optional[bytes]
25     jpg: Optional[np.ndarray]
26     hsv: Optional[np.ndarray]
27
28
29 class SanityCheckImageMetadata(NamedTuple):
30     """Is a Blue Iris image bad (big grey borders around it) or infrared?"""
31
32     is_bad_image: bool
33     is_infrared_image: bool
34
35
36 def sanity_check_image(hsv: np.ndarray) -> SanityCheckImageMetadata:
37     """See if a Blue Iris or Shinobi image is bad and infrared."""
38
39     def is_near(a, b) -> bool:
40         return abs(a - b) < 3
41
42     rows, cols, _ = hsv.shape
43     num_pixels = rows * cols
44     weird_orange_count = 0
45     hs_zero_count = 0
46     for r in range(rows):
47         for c in range(cols):
48             pixel = hsv[(r, c)]
49             if (
50                 is_near(pixel[0], 16)
51                 and is_near(pixel[1], 117)
52                 and is_near(pixel[2], 196)
53             ):
54                 weird_orange_count += 1
55             elif is_near(pixel[0], 0) and is_near(pixel[1], 0):
56                 hs_zero_count += 1
57     logger.debug(f"hszero#={hs_zero_count}, weird_orange={weird_orange_count}")
58     return SanityCheckImageMetadata(
59         hs_zero_count > (num_pixels * 0.75),
60         weird_orange_count > (num_pixels * 0.75),
61     )
62
63
64 @decorator_utils.retry_if_none(tries=2, delay_sec=1, backoff=1.1)
65 def fetch_camera_image_from_video_server(
66     camera_name: str, *, width: int = 256, quality: int = 70
67 ) -> Optional[bytes]:
68     """Fetch the raw webcam image from the video server."""
69     camera_name = camera_name.replace(".house", "")
70     camera_name = camera_name.replace(".cabin", "")
71     url = f"http://10.0.0.226:8080/Umtxxf1uKMBniFblqeQ9KRbb6DDzN4/jpeg/GKlT2FfiSQ/{camera_name}/s.jpg"
72     logger.debug(f'Fetching image from {url}')
73     try:
74         response = requests.get(url, stream=False, timeout=10.0)
75         if response.ok:
76             raw = response.content
77             logger.debug(f'Read {len(response.content)} byte image from HTTP server')
78             tmp = np.frombuffer(raw, dtype="uint8")
79             logger.debug(
80                 f'Translated raw content into {tmp.shape} {type(tmp)} with element type {type(tmp[0])}.'
81             )
82             jpg = cv2.imdecode(tmp, cv2.IMREAD_COLOR)
83             logger.debug(
84                 f'Decoded into {jpg.shape} jpeg {type(jpg)} with element type {type(jpg[0][0])}'
85             )
86             hsv = cv2.cvtColor(jpg, cv2.COLOR_BGR2HSV)
87             logger.debug(
88                 f'Converted JPG into HSV {hsv.shape} HSV {type(hsv)} with element type {type(hsv[0][0])}'
89             )
90             (_, is_bad_image) = sanity_check_image(hsv)
91             if not is_bad_image:
92                 return raw
93     except Exception as e:
94         logger.exception(e)
95     msg = f"Got a bad image or HTTP error from {url}; returning None."
96     logger.warning(msg)
97     warnings.warn(msg, stacklevel=2)
98     return None
99
100
101 def camera_name_to_hostname(camera_name: str) -> str:
102     """Map a camera name to a hostname
103
104     >>> camera_name_to_hostname('driveway')
105     'driveway.house'
106
107     >>> camera_name_to_hostname('cabin_driveway')
108     'driveway.cabin'
109
110     """
111     mapping = {
112         "driveway": "driveway.house",
113         "backyard": "backyard.house",
114         "frontdoor": "frontdoor.house",
115         "cabin_driveway": "driveway.cabin",
116     }
117     camera_name = mapping.get(camera_name, camera_name)
118     if "." not in camera_name:
119         hostname = platform.node()
120         suffix = hostname.split(".")[-1]
121         camera_name += f".{suffix}"
122     return camera_name
123
124
125 @decorator_utils.retry_if_none(tries=2, delay_sec=1, backoff=1.1)
126 def fetch_camera_image_from_rtsp_stream(
127     camera_name: str, *, width: int = 256
128 ) -> Optional[bytes]:
129     """Fetch the raw webcam image straight from the webcam's RTSP stream."""
130     hostname = camera_name_to_hostname(camera_name)
131     stream = f"rtsp://camera:IaLaIok@{hostname}:554/live"
132     logger.debug(f'Fetching image from RTSP stream {stream}')
133     try:
134         cmd = [
135             "/usr/bin/timeout",
136             "-k 9s",
137             "8s",
138             "/usr/local/bin/ffmpeg",
139             "-y",
140             "-i",
141             f"{stream}",
142             "-f",
143             "singlejpeg",
144             "-vframes",
145             "1",
146             "-vf",
147             f"scale={width}:-1",
148             "-",
149         ]
150         with subprocess.Popen(
151             cmd, stdout=subprocess.PIPE, stderr=subprocess.DEVNULL
152         ) as proc:
153             out, _ = proc.communicate(timeout=10)
154             return out
155     except Exception as e:
156         logger.exception(e)
157     msg = f"Failed to retrieve image via RTSP {stream}, returning None."
158     logger.warning(msg)
159     warnings.warn(msg, stacklevel=2)
160     return None
161
162
163 @decorator_utils.timeout(seconds=30, use_signals=False)
164 def _fetch_camera_image(
165     camera_name: str, *, width: int = 256, quality: int = 70
166 ) -> RawJpgHsv:
167     """Fetch a webcam image given the camera name."""
168     logger.debug("Trying to fetch camera image from video server")
169     raw = fetch_camera_image_from_video_server(
170         camera_name, width=width, quality=quality
171     )
172     if raw is None:
173         logger.debug("Reading from video server failed; trying direct RTSP stream")
174         raw = fetch_camera_image_from_rtsp_stream(camera_name, width=width)
175     if raw is not None and len(raw) > 0:
176         tmp = np.frombuffer(raw, dtype="uint8")
177         jpg = cv2.imdecode(tmp, cv2.IMREAD_COLOR)
178         hsv = cv2.cvtColor(jpg, cv2.COLOR_BGR2HSV)
179         return RawJpgHsv(
180             raw=raw,
181             jpg=jpg,
182             hsv=hsv,
183         )
184     msg = "Failed to retieve image from both video server and direct RTSP stream"
185     logger.warning(msg)
186     warnings.warn(msg, stacklevel=2)
187     return RawJpgHsv(None, None, None)
188
189
190 def fetch_camera_image(
191     camera_name: str, *, width: int = 256, quality: int = 70
192 ) -> RawJpgHsv:
193     try:
194         return _fetch_camera_image(camera_name, width=width, quality=quality)
195     except exceptions.TimeoutError:
196         logger.warning('Fetching camera image operation timed out.')
197         return RawJpgHsv(None, None, None)
198
199
200 if __name__ == '__main__':
201     import doctest
202
203     doctest.testmod()