| 1 |
"""For HA varios tools.""" |
| 2 |
import asyncio |
| 3 |
import logging |
| 4 |
import re |
| 5 |
from typing import Optional |
| 6 |
|
| 7 |
from .core import HAFFmpeg |
| 8 |
from .timeout import asyncio_timeout |
| 9 |
|
| 10 |
_LOGGER = logging.getLogger(__name__) |
| 11 |
|
| 12 |
IMAGE_JPEG = "mjpeg" |
| 13 |
IMAGE_PNG = "png" |
| 14 |
|
| 15 |
|
| 16 |
class ImageFrame(HAFFmpeg): |
| 17 |
"""Implement a single image capture from a stream.""" |
| 18 |
|
| 19 |
async def get_image( |
| 20 |
self, |
| 21 |
input_source: str, |
| 22 |
output_format: str = IMAGE_JPEG, |
| 23 |
extra_cmd: Optional[str] = None, |
| 24 |
timeout: int = 15, |
| 25 |
) -> Optional[bytes]: |
| 26 |
"""Open FFmpeg process as capture 1 frame.""" |
| 27 |
command = ["-an", "-frames:v", "1", "-c:v", output_format] |
| 28 |
|
| 29 |
|
| 30 |
is_open = await self.open( |
| 31 |
cmd=command, |
| 32 |
input_source=input_source, |
| 33 |
output="-f image2pipe -", |
| 34 |
extra_cmd=extra_cmd, |
| 35 |
) |
| 36 |
|
| 37 |
|
| 38 |
if not is_open: |
| 39 |
_LOGGER.warning("Error starting FFmpeg.") |
| 40 |
return None |
| 41 |
|
| 42 |
|
| 43 |
|
| 44 |
try: |
| 45 |
async with asyncio_timeout(timeout): |
| 46 |
image, _ = await self._proc.communicate() |
| 47 |
return image |
| 48 |
|
| 49 |
except (asyncio.TimeoutError, ValueError): |
| 50 |
_LOGGER.warning("Timeout reading image.") |
| 51 |
self.kill() |
| 52 |
return None |
| 53 |
|
| 54 |
finally: |
| 55 |
await self.close(0) |
| 56 |
|
| 57 |
|
| 58 |
class FFVersion(HAFFmpeg): |
| 59 |
"""Retrieve FFmpeg version information.""" |
| 60 |
|
| 61 |
async def get_version(self, timeout: int = 15) -> Optional[str]: |
| 62 |
"""Execute FFmpeg process and parse the version information. |
| 63 |
|
| 64 |
Return full FFmpeg version string. Such as 3.4.2-tessus |
| 65 |
""" |
| 66 |
command = ["-version"] |
| 67 |
|
| 68 |
|
| 69 |
is_open = await self.open(cmd=command, input_source=None, output="") |
| 70 |
|
| 71 |
|
| 72 |
if not is_open: |
| 73 |
_LOGGER.warning("Error starting FFmpeg.") |
| 74 |
return |
| 75 |
|
| 76 |
|
| 77 |
try: |
| 78 |
async with asyncio_timeout(timeout): |
| 79 |
output, _ = await self._proc.communicate() |
| 80 |
|
| 81 |
result = re.search(r"ffmpeg version (\S*)", output.decode()) |
| 82 |
if result is not None: |
| 83 |
return result.group(1) |
| 84 |
|
| 85 |
except (asyncio.TimeoutError, ValueError): |
| 86 |
_LOGGER.warning("Timeout reading stdout.") |
| 87 |
self.kill() |
| 88 |
|
| 89 |
finally: |
| 90 |
await self.close(0) |
| 91 |
|
| 92 |
return None |