Debian Codegraph @

haffmpeg/sensor.py

raw symbols SCIP
1 """For HA sensor components."""
2 import asyncio
3 import logging
4 import re
5 from time import time
6 from typing import Callable, Coroutine, Optional
7
8 from .core import FFMPEG_STDOUT, HAFFmpegWorker
9 from .timeout import asyncio_timeout
10
11 _LOGGER = logging.getLogger(__name__)
12
13
14 class SensorNoise(HAFFmpegWorker):
15 """Implement a noise detection on a autio stream."""
16
17 STATE_NONE = 0
18 STATE_NOISE = 1
19 STATE_END = 2
20 STATE_DETECT = 3
21
22 def __init__(self, ffmpeg_bin: str, callback: Callable):
23 """Init noise sensor."""
24 super().__init__(ffmpeg_bin)
25
26 self._callback = callback
27 self._peak = -30
28 self._time_duration = 1
29 self._time_reset = 2
30
31 def set_options(
32 self, time_duration: int = 1, time_reset: int = 2, peak: int = -30
33 ) -> None:
34 """Set option parameter for noise sensor."""
35 self._time_duration = time_duration
36 self._time_reset = time_reset
37 self._peak = peak
38
39 def open_sensor(
40 self,
41 input_source: str,
42 output_dest: Optional[str] = None,
43 extra_cmd: Optional[str] = None,
44 ) -> Coroutine:
45 """Open FFmpeg process for read autio stream.
46
47 Return a coroutine.
48 """
49 command = ["-vn", "-filter:a", f"silencedetect=n={self._peak}dB:d=1"]
50
51 # run ffmpeg, read output
52 return self.start_worker(
53 cmd=command,
54 input_source=input_source,
55 output=output_dest,
56 extra_cmd=extra_cmd,
57 pattern="silence",
58 )
59
60 async def _worker_process(self) -> None:
61 """This function processing data."""
62 state = self.STATE_DETECT
63 timeout = self._time_duration
64
65 self._loop.call_soon(self._callback, False)
66
67 re_start = re.compile("silence_start")
68 re_end = re.compile("silence_end")
69
70 # process queue data
71 while True:
72 try:
73 _LOGGER.debug("Reading State: %d, timeout: %s", state, timeout)
74 async with asyncio_timeout(timeout):
75 data = await self._queue.get()
76 timeout = None
77 if data is None:
78 self._loop.call_soon(self._callback, None)
79 return
80 except asyncio.TimeoutError:
81 _LOGGER.debug("Blocking timeout")
82 # noise
83 if state == self.STATE_DETECT:
84 # noise detected
85 self._loop.call_soon(self._callback, True)
86 state = self.STATE_NOISE
87
88 elif state == self.STATE_END:
89 # no noise
90 self._loop.call_soon(self._callback, False)
91 state = self.STATE_NONE
92
93 timeout = None
94 continue
95
96 if re_start.search(data):
97 if state == self.STATE_NOISE:
98 # stop noise detection
99 state = self.STATE_END
100 timeout = self._time_reset
101 elif state == self.STATE_DETECT:
102 # reset if only a peak
103 state = self.STATE_NONE
104 continue
105
106 if re_end.search(data):
107 if state == self.STATE_NONE:
108 # detect noise begin
109 state = self.STATE_DETECT
110 timeout = self._time_duration
111 elif state == self.STATE_END:
112 # back to noise status
113 state = self.STATE_NOISE
114 continue
115
116 _LOGGER.warning("Unknown data from queue!")
117
118
119 class SensorMotion(HAFFmpegWorker):
120 """Implement motion detection with ffmpeg scene detection."""
121
122 STATE_NONE = 0
123 STATE_REPEAT = 1
124 STATE_MOTION = 2
125
126 MATCH = r"\d,.*\d,.*\d,.*\d,.*\d,.*\w"
127
128 def __init__(self, ffmpeg_bin: str, callback: Callable):
129 """Init motion sensor."""
130 super().__init__(ffmpeg_bin)
131
132 self._callback = callback
133 self._changes = 10
134 self._time_reset = 60
135 self._time_repeat = 0
136 self._repeat = 0
137
138 def set_options(
139 self,
140 time_reset: int = 60,
141 time_repeat: int = 0,
142 repeat: int = 0,
143 changes: int = 10,
144 ) -> None:
145 """Set option parameter for noise sensor."""
146 self._time_reset = time_reset
147 self._time_repeat = time_repeat
148 self._repeat = repeat
149 self._changes = changes
150
151 async def open_sensor(
152 self, input_source: str, extra_cmd: Optional[str] = None
153 ) -> Coroutine:
154 """Open FFmpeg process a video stream for motion detection.
155
156 Return a coroutine.
157 """
158 command = [
159 "-an",
160 "-filter:v",
161 f"select=gt(scene\\,{self._changes / 100})",
162 ]
163
164 # run ffmpeg, read output
165 return await self.start_worker(
166 cmd=command,
167 input_source=input_source,
168 output="-f framemd5 -",
169 extra_cmd=extra_cmd,
170 pattern=self.MATCH,
171 reading=FFMPEG_STDOUT,
172 )
173
174 async def _worker_process(self) -> None:
175 """This function processing data."""
176 state = self.STATE_NONE
177 timeout = None
178
179 self._loop.call_soon(self._callback, False)
180
181 # for repeat feature
182 re_frame = 0
183 re_time = 0
184
185 re_data = re.compile(self.MATCH)
186
187 # process queue data
188 while True:
189 try:
190 _LOGGER.debug("Reading State: %d, timeout: %s", state, timeout)
191 async with asyncio_timeout(timeout):
192 data = await self._queue.get()
193 if data is None:
194 self._loop.call_soon(self._callback, None)
195 return
196 except asyncio.TimeoutError:
197 _LOGGER.debug("Blocking timeout")
198 # reset motion detection
199 if state == self.STATE_MOTION:
200 state = self.STATE_NONE
201 self._loop.call_soon(self._callback, False)
202 timeout = None
203 # reset repeate state
204 if state == self.STATE_REPEAT:
205 state = self.STATE_NONE
206 timeout = None
207 continue
208
209 frames = re_data.search(data)
210 if frames:
211 # repeat not used
212 if self._repeat == 0 and state == self.STATE_NONE:
213 state = self.STATE_MOTION
214 self._loop.call_soon(self._callback, True)
215 timeout = self._time_reset
216
217 # repeat feature is on / first motion
218 if state == self.STATE_NONE:
219 state = self.STATE_REPEAT
220 timeout = self._time_repeat
221 re_frame = 0
222 re_time = time()
223
224 elif state == self.STATE_REPEAT:
225 re_frame += 1
226
227 # REPEAT ready?
228 if re_frame >= self._repeat:
229 state = self.STATE_MOTION
230 self._loop.call_soon(self._callback, True)
231 timeout = self._time_reset
232 else:
233 past = time() - re_time
234 timeout -= past
235
236 # REPEAT time down
237 if timeout <= 0:
238 _LOGGER.debug("Reset repeat to none")
239 state = self.STATE_NONE
240 timeout = None
241
242 continue
243
244 _LOGGER.warning("Unknown data from queue!")