Debian Codegraph @

haffmpeg/core.py

raw symbols SCIP
1 """Base functionality of ffmpeg HA wrapper."""
2 import asyncio
3 import logging
4 import re
5 import shlex
6 from typing import List, Optional, Set
7
8 from .timeout import asyncio_timeout
9
10 _LOGGER = logging.getLogger(__name__)
11
12 FFMPEG_STDOUT = "stdout"
13 FFMPEG_STDERR = "stderr"
14
15 _BACKGROUND_TASKS: Set[asyncio.Task] = set()
16
17
18 class HAFFmpeg:
19 """HA FFmpeg process async.
20
21 Object is iterable or use the process property to call from Popen object.
22 """
23
24 def __init__(self, ffmpeg_bin: str):
25 """Base initialize."""
26 self._loop = asyncio.get_running_loop()
27 self._ffmpeg = ffmpeg_bin
28 self._argv = None
29 self._proc: Optional["asyncio.subprocess.Process"] = None
30
31 @property
32 def process(self) -> "asyncio.subprocess.Process":
33 """Return a Popen object or None of not running."""
34 return self._proc
35
36 @property
37 def is_running(self) -> bool:
38 """Return True if ffmpeg is running."""
39 if self._proc is None or self._proc.returncode is not None:
40 return False
41 return True
42
43 def _generate_ffmpeg_cmd(
44 self,
45 cmd: List[str],
46 input_source: Optional[str],
47 output: Optional[str],
48 extra_cmd: Optional[str] = None,
49 ) -> None:
50 """Generate ffmpeg command line."""
51 self._argv = [self._ffmpeg]
52
53 # start command init
54 if input_source is not None:
55 self._put_input(input_source)
56 self._argv.extend(cmd)
57
58 # exists a extra cmd from customer
59 if extra_cmd is not None:
60 self._argv.extend(shlex.split(extra_cmd))
61
62 self._merge_filters()
63 self._put_output(output)
64
65 def _put_input(self, input_source: str) -> None:
66 """Put input string to ffmpeg command."""
67 input_cmd = shlex.split(str(input_source))
68 if len(input_cmd) > 1:
69 self._argv.extend(input_cmd)
70 else:
71 self._argv.extend(["-i", input_source])
72
73 def _put_output(self, output: Optional[str]) -> None:
74 """Put output string to ffmpeg command."""
75 if output is None:
76 self._argv.extend(["-f", "null", "-"])
77 return
78
79 output_cmd = shlex.split(str(output))
80 if len(output_cmd) > 1:
81 self._argv.extend(output_cmd)
82 else:
83 self._argv.append(output)
84
85 def _merge_filters(self) -> None:
86 """Merge all filter config in command line."""
87 for opts in (["-filter:a", "-af"], ["-filter:v", "-vf"]):
88 filter_list = []
89 new_argv = []
90 cmd_iter = iter(self._argv)
91 for element in cmd_iter:
92 if element in opts:
93 filter_list.insert(0, next(cmd_iter))
94 else:
95 new_argv.append(element)
96
97 # update argv if changes
98 if filter_list:
99 new_argv.extend([opts[0], ",".join(filter_list)])
100 self._argv = new_argv.copy()
101
102 def _clear(self) -> None:
103 """Clear member variable after close."""
104 self._argv = None
105 self._proc = None
106
107 async def open(
108 self,
109 cmd: List[str],
110 input_source: Optional[str],
111 output: Optional[str] = "-",
112 extra_cmd: Optional[str] = None,
113 stdout_pipe: bool = True,
114 stderr_pipe: bool = False,
115 ) -> bool:
116 """Start a ffmpeg instance and pipe output."""
117 stdout = asyncio.subprocess.PIPE if stdout_pipe else asyncio.subprocess.DEVNULL
118 stderr = asyncio.subprocess.PIPE if stderr_pipe else asyncio.subprocess.DEVNULL
119
120 if self.is_running:
121 _LOGGER.warning("FFmpeg is already running!")
122 return True
123
124 # set command line
125 self._generate_ffmpeg_cmd(cmd, input_source, output, extra_cmd)
126
127 # start ffmpeg
128 _LOGGER.debug("Start FFmpeg with %s", str(self._argv))
129 try:
130 self._proc = await asyncio.create_subprocess_exec(
131 *self._argv,
132 bufsize=0,
133 stdin=asyncio.subprocess.PIPE,
134 stdout=stdout,
135 stderr=stderr,
136 close_fds=False,
137 )
138 except Exception as err: # pylint: disable=broad-except
139 _LOGGER.exception("FFmpeg fails %s", err)
140 self._clear()
141 return False
142
143 return self._proc is not None
144
145 async def close(self, timeout=5) -> None:
146 """Stop a ffmpeg instance."""
147 if not self.is_running:
148 _LOGGER.debug("FFmpeg isn't running!")
149 return
150
151 # Can't use communicate because we attach the output to a streamreader
152 # send stop to ffmpeg
153 try:
154 self._proc.stdin.write(b"q")
155 async with asyncio_timeout(timeout):
156 await self._proc.wait()
157 _LOGGER.debug("Close FFmpeg process")
158
159 except (asyncio.TimeoutError, ValueError):
160 _LOGGER.warning("Timeout while waiting of FFmpeg")
161 self.kill()
162
163 finally:
164 self._clear()
165
166 def kill(self) -> None:
167 """Kill ffmpeg job."""
168 self._proc.kill()
169 background_task = asyncio.create_task(self._proc.communicate())
170 _BACKGROUND_TASKS.add(background_task)
171 background_task.add_done_callback(_BACKGROUND_TASKS.remove)
172
173 async def get_reader(self, source=FFMPEG_STDOUT) -> asyncio.StreamReader:
174 """Create and return streamreader."""
175 if source == FFMPEG_STDOUT:
176 return self._proc.stdout
177 return self._proc.stderr
178
179
180 class HAFFmpegWorker(HAFFmpeg):
181 """Read FFmpeg output to queue."""
182
183 def __init__(self, ffmpeg_bin: str):
184 """Init noise sensor."""
185 super().__init__(ffmpeg_bin)
186
187 self._queue = asyncio.Queue()
188 self._input = None
189 self._read_task = None
190
191 async def close(self, timeout: int = 5) -> None:
192 """Stop a ffmpeg instance.
193
194 Return a coroutine
195 """
196 if self._read_task is not None and not self._read_task.cancelled():
197 self._read_task.cancel()
198
199 return await super().close(timeout)
200
201 async def _process_lines(self, pattern: Optional[str] = None) -> None:
202 """Read line from pipe they match with pattern."""
203 if pattern is not None:
204 cmp = re.compile(pattern)
205
206 _LOGGER.debug("Start working with pattern '%s'.", pattern)
207
208 # read lines
209 while self.is_running:
210 try:
211 line = await self._input.readline()
212 if not line:
213 break
214 line = line.decode()
215 except Exception: # pylint: disable=broad-except
216 break
217
218 match = True if pattern is None else cmp.search(line)
219 if match:
220 _LOGGER.debug("Process: %s", line)
221 await self._queue.put(line)
222
223 try:
224 await self._proc.wait()
225 finally:
226 await self._queue.put(None)
227 _LOGGER.debug("Stopped reading ffmpeg output.")
228
229 async def _worker_process(self) -> None:
230 """Process output line."""
231 raise NotImplementedError()
232
233 async def start_worker(
234 self,
235 cmd: List[str],
236 input_source: str,
237 output: Optional[str] = None,
238 extra_cmd: Optional[str] = None,
239 pattern: Optional[str] = None,
240 reading: str = FFMPEG_STDERR,
241 ) -> None:
242 """Start ffmpeg do process data from output."""
243 if self.is_running:
244 _LOGGER.warning("Can't start worker. It is allready running!")
245 return
246
247 if reading == FFMPEG_STDERR:
248 stdout = False
249 stderr = True
250 else:
251 stdout = True
252 stderr = False
253
254 # start ffmpeg and reading to queue
255 await self.open(
256 cmd=cmd,
257 input_source=input_source,
258 output=output,
259 extra_cmd=extra_cmd,
260 stdout_pipe=stdout,
261 stderr_pipe=stderr,
262 )
263
264 self._input = await self.get_reader(reading)
265
266 # start background processing
267 self._read_task = self._loop.create_task(self._process_lines(pattern))
268 self._loop.create_task(self._worker_process())