2023-07-01 15:18:33 +02:00
|
|
|
"""Handle creating audio events."""
|
|
|
|
|
|
|
|
import datetime
|
|
|
|
import logging
|
|
|
|
import multiprocessing as mp
|
|
|
|
import signal
|
|
|
|
import threading
|
2023-07-26 12:51:45 +02:00
|
|
|
import time
|
2023-07-01 15:18:33 +02:00
|
|
|
from types import FrameType
|
2023-07-14 02:52:33 +02:00
|
|
|
from typing import Optional, Tuple
|
2023-07-01 15:18:33 +02:00
|
|
|
|
|
|
|
import numpy as np
|
|
|
|
import requests
|
|
|
|
from setproctitle import setproctitle
|
|
|
|
|
2023-07-14 02:52:33 +02:00
|
|
|
from frigate.comms.inter_process import InterProcessCommunicator
|
2023-07-01 15:18:33 +02:00
|
|
|
from frigate.config import CameraConfig, FrigateConfig
|
|
|
|
from frigate.const import (
|
|
|
|
AUDIO_DURATION,
|
|
|
|
AUDIO_FORMAT,
|
|
|
|
AUDIO_MAX_BIT_RANGE,
|
2023-07-17 13:07:15 +02:00
|
|
|
AUDIO_MIN_CONFIDENCE,
|
2023-07-01 15:18:33 +02:00
|
|
|
AUDIO_SAMPLE_RATE,
|
|
|
|
FRIGATE_LOCALHOST,
|
|
|
|
)
|
|
|
|
from frigate.ffmpeg_presets import parse_preset_input
|
|
|
|
from frigate.log import LogPipe
|
|
|
|
from frigate.object_detection import load_labels
|
|
|
|
from frigate.types import FeatureMetricsTypes
|
2023-07-06 16:28:50 +02:00
|
|
|
from frigate.util.builtin import get_ffmpeg_arg_list
|
|
|
|
from frigate.util.services import listen
|
2023-07-01 15:18:33 +02:00
|
|
|
from frigate.video import start_or_restart_ffmpeg, stop_ffmpeg
|
|
|
|
|
|
|
|
try:
|
|
|
|
from tflite_runtime.interpreter import Interpreter
|
|
|
|
except ModuleNotFoundError:
|
|
|
|
from tensorflow.lite.python.interpreter import Interpreter
|
|
|
|
|
|
|
|
logger = logging.getLogger(__name__)
|
|
|
|
|
|
|
|
|
2023-07-26 12:51:45 +02:00
|
|
|
def get_ffmpeg_command(input_args: list[str], input_path: str) -> list[str]:
|
2023-07-01 15:18:33 +02:00
|
|
|
return get_ffmpeg_arg_list(
|
|
|
|
f"ffmpeg {{}} -i {{}} -f {AUDIO_FORMAT} -ar {AUDIO_SAMPLE_RATE} -ac 1 -y {{}}".format(
|
|
|
|
" ".join(input_args),
|
|
|
|
input_path,
|
2023-07-26 12:51:45 +02:00
|
|
|
"pipe:",
|
2023-07-01 15:18:33 +02:00
|
|
|
)
|
|
|
|
)
|
|
|
|
|
|
|
|
|
|
|
|
def listen_to_audio(
|
|
|
|
config: FrigateConfig,
|
2023-07-16 14:42:56 +02:00
|
|
|
recordings_info_queue: mp.Queue,
|
2023-07-01 15:18:33 +02:00
|
|
|
process_info: dict[str, FeatureMetricsTypes],
|
2023-07-14 02:52:33 +02:00
|
|
|
inter_process_communicator: InterProcessCommunicator,
|
2023-07-01 15:18:33 +02:00
|
|
|
) -> None:
|
|
|
|
stop_event = mp.Event()
|
|
|
|
audio_threads: list[threading.Thread] = []
|
|
|
|
|
|
|
|
def exit_process() -> None:
|
|
|
|
for thread in audio_threads:
|
|
|
|
thread.join()
|
|
|
|
|
|
|
|
logger.info("Exiting audio detector...")
|
|
|
|
|
|
|
|
def receiveSignal(signalNumber: int, frame: Optional[FrameType]) -> None:
|
|
|
|
stop_event.set()
|
|
|
|
exit_process()
|
|
|
|
|
|
|
|
signal.signal(signal.SIGTERM, receiveSignal)
|
|
|
|
signal.signal(signal.SIGINT, receiveSignal)
|
|
|
|
|
|
|
|
threading.current_thread().name = "process:audio_manager"
|
|
|
|
setproctitle("frigate.audio_manager")
|
|
|
|
listen()
|
|
|
|
|
|
|
|
for camera in config.cameras.values():
|
|
|
|
if camera.enabled and camera.audio.enabled_in_config:
|
2023-07-14 02:52:33 +02:00
|
|
|
audio = AudioEventMaintainer(
|
2023-07-15 02:05:14 +02:00
|
|
|
camera,
|
|
|
|
recordings_info_queue,
|
|
|
|
process_info,
|
|
|
|
stop_event,
|
|
|
|
inter_process_communicator,
|
2023-07-14 02:52:33 +02:00
|
|
|
)
|
2023-07-01 15:18:33 +02:00
|
|
|
audio_threads.append(audio)
|
|
|
|
audio.start()
|
|
|
|
|
|
|
|
|
|
|
|
class AudioTfl:
|
2023-09-01 14:00:11 +02:00
|
|
|
def __init__(self, stop_event: mp.Event, num_threads=2):
|
2023-07-01 15:18:33 +02:00
|
|
|
self.stop_event = stop_event
|
2023-09-01 14:00:11 +02:00
|
|
|
self.num_threads = num_threads
|
|
|
|
self.labels = load_labels("/audio-labelmap.txt", prefill=521)
|
2023-07-01 15:18:33 +02:00
|
|
|
self.interpreter = Interpreter(
|
|
|
|
model_path="/cpu_audio_model.tflite",
|
2023-09-01 14:00:11 +02:00
|
|
|
num_threads=self.num_threads,
|
2023-07-01 15:18:33 +02:00
|
|
|
)
|
|
|
|
|
|
|
|
self.interpreter.allocate_tensors()
|
|
|
|
|
|
|
|
self.tensor_input_details = self.interpreter.get_input_details()
|
|
|
|
self.tensor_output_details = self.interpreter.get_output_details()
|
|
|
|
|
|
|
|
def _detect_raw(self, tensor_input):
|
|
|
|
self.interpreter.set_tensor(self.tensor_input_details[0]["index"], tensor_input)
|
|
|
|
self.interpreter.invoke()
|
|
|
|
detections = np.zeros((20, 6), np.float32)
|
|
|
|
|
|
|
|
res = self.interpreter.get_tensor(self.tensor_output_details[0]["index"])[0]
|
|
|
|
non_zero_indices = res > 0
|
|
|
|
class_ids = np.argpartition(-res, 20)[:20]
|
|
|
|
class_ids = class_ids[np.argsort(-res[class_ids])]
|
|
|
|
class_ids = class_ids[non_zero_indices[class_ids]]
|
|
|
|
scores = res[class_ids]
|
|
|
|
boxes = np.full((scores.shape[0], 4), -1, np.float32)
|
|
|
|
count = len(scores)
|
|
|
|
|
|
|
|
for i in range(count):
|
2023-09-01 14:00:11 +02:00
|
|
|
if scores[i] < AUDIO_MIN_CONFIDENCE or i == 20:
|
2023-07-01 15:18:33 +02:00
|
|
|
break
|
|
|
|
detections[i] = [
|
|
|
|
class_ids[i],
|
|
|
|
float(scores[i]),
|
|
|
|
boxes[i][0],
|
|
|
|
boxes[i][1],
|
|
|
|
boxes[i][2],
|
|
|
|
boxes[i][3],
|
|
|
|
]
|
|
|
|
|
|
|
|
return detections
|
|
|
|
|
2023-07-17 13:07:15 +02:00
|
|
|
def detect(self, tensor_input, threshold=AUDIO_MIN_CONFIDENCE):
|
2023-07-01 15:18:33 +02:00
|
|
|
detections = []
|
|
|
|
|
|
|
|
if self.stop_event.is_set():
|
|
|
|
return detections
|
|
|
|
|
|
|
|
raw_detections = self._detect_raw(tensor_input)
|
|
|
|
|
|
|
|
for d in raw_detections:
|
|
|
|
if d[1] < threshold:
|
|
|
|
break
|
|
|
|
detections.append(
|
|
|
|
(self.labels[int(d[0])], float(d[1]), (d[2], d[3], d[4], d[5]))
|
|
|
|
)
|
|
|
|
return detections
|
|
|
|
|
|
|
|
|
|
|
|
class AudioEventMaintainer(threading.Thread):
|
|
|
|
def __init__(
|
|
|
|
self,
|
|
|
|
camera: CameraConfig,
|
2023-07-16 14:42:56 +02:00
|
|
|
recordings_info_queue: mp.Queue,
|
2023-07-01 15:18:33 +02:00
|
|
|
feature_metrics: dict[str, FeatureMetricsTypes],
|
|
|
|
stop_event: mp.Event,
|
2023-07-14 02:52:33 +02:00
|
|
|
inter_process_communicator: InterProcessCommunicator,
|
2023-07-01 15:18:33 +02:00
|
|
|
) -> None:
|
|
|
|
threading.Thread.__init__(self)
|
|
|
|
self.name = f"{camera.name}_audio_event_processor"
|
|
|
|
self.config = camera
|
2023-07-15 02:05:14 +02:00
|
|
|
self.recordings_info_queue = recordings_info_queue
|
2023-07-01 15:18:33 +02:00
|
|
|
self.feature_metrics = feature_metrics
|
2023-07-14 02:52:33 +02:00
|
|
|
self.inter_process_communicator = inter_process_communicator
|
2023-10-07 16:18:34 +02:00
|
|
|
self.detections: dict[dict[str, any]] = {}
|
2023-07-01 15:18:33 +02:00
|
|
|
self.stop_event = stop_event
|
2023-09-01 14:00:11 +02:00
|
|
|
self.detector = AudioTfl(stop_event, self.config.audio.num_threads)
|
2023-07-01 15:18:33 +02:00
|
|
|
self.shape = (int(round(AUDIO_DURATION * AUDIO_SAMPLE_RATE)),)
|
|
|
|
self.chunk_size = int(round(AUDIO_DURATION * AUDIO_SAMPLE_RATE * 2))
|
2023-07-26 12:51:45 +02:00
|
|
|
self.logger = logging.getLogger(f"audio.{self.config.name}")
|
2023-07-01 15:18:33 +02:00
|
|
|
self.ffmpeg_cmd = get_ffmpeg_command(
|
|
|
|
get_ffmpeg_arg_list(self.config.ffmpeg.global_args)
|
|
|
|
+ parse_preset_input("preset-rtsp-audio-only", 1),
|
|
|
|
[i.path for i in self.config.ffmpeg.inputs if "audio" in i.roles][0],
|
|
|
|
)
|
|
|
|
self.logpipe = LogPipe(f"ffmpeg.{self.config.name}.audio")
|
|
|
|
self.audio_listener = None
|
|
|
|
|
|
|
|
def detect_audio(self, audio) -> None:
|
|
|
|
if not self.feature_metrics[self.config.name]["audio_enabled"].value:
|
|
|
|
return
|
|
|
|
|
2023-07-14 02:52:33 +02:00
|
|
|
audio_as_float = audio.astype(np.float32)
|
2023-07-15 02:05:14 +02:00
|
|
|
rms, dBFS = self.calculate_audio_levels(audio_as_float)
|
2023-07-01 15:18:33 +02:00
|
|
|
|
2023-07-08 14:16:24 +02:00
|
|
|
# only run audio detection when volume is above min_volume
|
|
|
|
if rms >= self.config.audio.min_volume:
|
2023-07-15 02:05:14 +02:00
|
|
|
# add audio info to recordings queue
|
|
|
|
self.recordings_info_queue.put(
|
|
|
|
(self.config.name, datetime.datetime.now().timestamp(), dBFS)
|
|
|
|
)
|
|
|
|
|
|
|
|
# create waveform relative to max range and look for detections
|
2023-07-08 14:16:24 +02:00
|
|
|
waveform = (audio / AUDIO_MAX_BIT_RANGE).astype(np.float32)
|
|
|
|
model_detections = self.detector.detect(waveform)
|
2023-07-01 15:18:33 +02:00
|
|
|
|
2023-07-08 14:16:24 +02:00
|
|
|
for label, score, _ in model_detections:
|
|
|
|
if label not in self.config.audio.listen:
|
|
|
|
continue
|
|
|
|
|
2023-08-06 19:19:28 +02:00
|
|
|
if score > dict((self.config.audio.filters or {}).get(label, {})).get(
|
2023-07-17 13:07:15 +02:00
|
|
|
"threshold", 0.8
|
|
|
|
):
|
|
|
|
self.handle_detection(label, score)
|
2023-07-01 15:18:33 +02:00
|
|
|
|
|
|
|
self.expire_detections()
|
|
|
|
|
2023-07-14 02:52:33 +02:00
|
|
|
def calculate_audio_levels(self, audio_as_float: np.float32) -> Tuple[float, float]:
|
|
|
|
# Calculate RMS (Root-Mean-Square) which represents the average signal amplitude
|
|
|
|
# Note: np.float32 isn't serializable, we must use np.float64 to publish the message
|
2023-07-15 02:05:14 +02:00
|
|
|
rms = np.sqrt(np.mean(np.absolute(np.square(audio_as_float))))
|
2023-07-14 02:52:33 +02:00
|
|
|
|
|
|
|
# Transform RMS to dBFS (decibels relative to full scale)
|
|
|
|
dBFS = 20 * np.log10(np.abs(rms) / AUDIO_MAX_BIT_RANGE)
|
|
|
|
|
|
|
|
self.inter_process_communicator.queue.put(
|
|
|
|
(f"{self.config.name}/audio/dBFS", float(dBFS))
|
|
|
|
)
|
|
|
|
self.inter_process_communicator.queue.put(
|
|
|
|
(f"{self.config.name}/audio/rms", float(rms))
|
|
|
|
)
|
|
|
|
|
|
|
|
return float(rms), float(dBFS)
|
|
|
|
|
2023-07-01 15:18:33 +02:00
|
|
|
def handle_detection(self, label: str, score: float) -> None:
|
|
|
|
if self.detections.get(label):
|
|
|
|
self.detections[label][
|
|
|
|
"last_detection"
|
|
|
|
] = datetime.datetime.now().timestamp()
|
|
|
|
else:
|
2023-07-15 02:06:00 +02:00
|
|
|
self.inter_process_communicator.queue.put(
|
|
|
|
(f"{self.config.name}/audio/{label}", "ON")
|
|
|
|
)
|
|
|
|
|
2023-07-01 15:18:33 +02:00
|
|
|
resp = requests.post(
|
|
|
|
f"{FRIGATE_LOCALHOST}/api/events/{self.config.name}/{label}/create",
|
2023-07-17 13:07:15 +02:00
|
|
|
json={"duration": None, "score": score, "source_type": "audio"},
|
2023-07-01 15:18:33 +02:00
|
|
|
)
|
|
|
|
|
|
|
|
if resp.status_code == 200:
|
2023-07-08 14:16:24 +02:00
|
|
|
event_id = resp.json()["event_id"]
|
2023-07-01 15:18:33 +02:00
|
|
|
self.detections[label] = {
|
|
|
|
"id": event_id,
|
|
|
|
"label": label,
|
|
|
|
"last_detection": datetime.datetime.now().timestamp(),
|
|
|
|
}
|
|
|
|
|
|
|
|
def expire_detections(self) -> None:
|
|
|
|
now = datetime.datetime.now().timestamp()
|
|
|
|
|
|
|
|
for detection in self.detections.values():
|
2023-07-01 23:33:47 +02:00
|
|
|
if not detection:
|
|
|
|
continue
|
|
|
|
|
2023-07-01 15:18:33 +02:00
|
|
|
if (
|
|
|
|
now - detection.get("last_detection", now)
|
|
|
|
> self.config.audio.max_not_heard
|
|
|
|
):
|
2023-07-15 02:06:00 +02:00
|
|
|
self.inter_process_communicator.queue.put(
|
|
|
|
(f"{self.config.name}/audio/{detection['label']}", "OFF")
|
|
|
|
)
|
|
|
|
|
2023-07-03 16:50:25 +02:00
|
|
|
resp = requests.put(
|
2023-07-01 15:18:33 +02:00
|
|
|
f"{FRIGATE_LOCALHOST}/api/events/{detection['id']}/end",
|
|
|
|
json={
|
|
|
|
"end_time": detection["last_detection"]
|
|
|
|
+ self.config.record.events.post_capture
|
|
|
|
},
|
|
|
|
)
|
2023-07-15 02:06:00 +02:00
|
|
|
|
2023-07-03 16:50:25 +02:00
|
|
|
if resp.status_code == 200:
|
|
|
|
self.detections[detection["label"]] = None
|
|
|
|
else:
|
2023-07-26 12:51:45 +02:00
|
|
|
self.logger.warn(
|
2023-07-03 16:50:25 +02:00
|
|
|
f"Failed to end audio event {detection['id']} with status code {resp.status_code}"
|
|
|
|
)
|
2023-07-01 15:18:33 +02:00
|
|
|
|
2023-07-26 12:51:45 +02:00
|
|
|
def start_or_restart_ffmpeg(self) -> None:
|
2023-07-01 15:18:33 +02:00
|
|
|
self.audio_listener = start_or_restart_ffmpeg(
|
2023-07-26 12:51:45 +02:00
|
|
|
self.ffmpeg_cmd,
|
|
|
|
self.logger,
|
|
|
|
self.logpipe,
|
|
|
|
self.chunk_size,
|
|
|
|
self.audio_listener,
|
2023-07-01 15:18:33 +02:00
|
|
|
)
|
|
|
|
|
|
|
|
def read_audio(self) -> None:
|
2023-07-26 12:51:45 +02:00
|
|
|
def log_and_restart() -> None:
|
|
|
|
if self.stop_event.is_set():
|
|
|
|
return
|
|
|
|
|
|
|
|
time.sleep(self.config.ffmpeg.retry_interval)
|
|
|
|
self.logpipe.dump()
|
|
|
|
self.start_or_restart_ffmpeg()
|
2023-07-01 15:18:33 +02:00
|
|
|
|
|
|
|
try:
|
2023-07-26 12:51:45 +02:00
|
|
|
chunk = self.audio_listener.stdout.read(self.chunk_size)
|
|
|
|
|
|
|
|
if not chunk:
|
|
|
|
if self.audio_listener.poll() is not None:
|
|
|
|
self.logger.error("ffmpeg process is not running, restarting...")
|
|
|
|
log_and_restart()
|
|
|
|
return
|
|
|
|
|
|
|
|
return
|
|
|
|
|
|
|
|
audio = np.frombuffer(chunk, dtype=np.int16)
|
2023-07-01 15:18:33 +02:00
|
|
|
self.detect_audio(audio)
|
2023-08-05 12:47:56 +02:00
|
|
|
except Exception as e:
|
|
|
|
self.logger.error(f"Error reading audio data from ffmpeg process: {e}")
|
2023-07-26 12:51:45 +02:00
|
|
|
log_and_restart()
|
2023-07-01 15:18:33 +02:00
|
|
|
|
|
|
|
def run(self) -> None:
|
2023-07-26 12:51:45 +02:00
|
|
|
self.start_or_restart_ffmpeg()
|
2023-07-01 15:18:33 +02:00
|
|
|
|
|
|
|
while not self.stop_event.is_set():
|
|
|
|
self.read_audio()
|
|
|
|
|
2023-07-26 12:51:45 +02:00
|
|
|
stop_ffmpeg(self.audio_listener, self.logger)
|
2023-07-01 15:18:33 +02:00
|
|
|
self.logpipe.close()
|