"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    var desc = Object.getOwnPropertyDescriptor(m, k);
    if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
      desc = { enumerable: true, get: function() { return m[k]; } };
    }
    Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
    Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
    o["default"] = v;
});
var __importStar = (this && this.__importStar) || (function () {
    var ownKeys = function(o) {
        ownKeys = Object.getOwnPropertyNames || function (o) {
            var ar = [];
            for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
            return ar;
        };
        return ownKeys(o);
    };
    return function (mod) {
        if (mod && mod.__esModule) return mod;
        var result = {};
        if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
        __setModuleDefault(result, mod);
        return result;
    };
})();
Object.defineProperty(exports, "__esModule", { value: true });
exports.createVad = createVad;
/**
 * Copyright (C) 2025 by Fonoster Inc (https://fonoster.com)
 * http://github.com/fonoster/fonoster
 *
 * This file is part of Fonoster
 *
 * Licensed under the MIT License (the "License");
 * you may not use this file except in compliance with
 * the License. You may obtain a copy of the License at
 *
 *    https://opensource.org/licenses/MIT
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
const path_1 = require("path");
const logger_1 = require("@fonoster/logger");
const ort = __importStar(require("onnxruntime-node"));
const chunkToFloat32Array_1 = require("../vad/chunkToFloat32Array");
const SileroVadModel_1 = require("./SileroVadModel");
const logger = (0, logger_1.getLogger)({ service: "autopilot", filePath: __filename });
const FULL_FRAME_SIZE = 1024; // 64ms @ 16kHz
const BUFFER_SIZE = 512; // 32ms @ 16kHz
async function createVad(params) {
    const { pathToModel, activationThreshold, deactivationThreshold, debounceFrames } = params;
    const effectivePath = pathToModel || (0, path_1.join)(__dirname, "..", "..", "silero_vad_v5.onnx");
    const silero = await SileroVadModel_1.SileroVadModel.new(ort, effectivePath);
    let sampleBuffer = [];
    let isSpeechActive = false;
    let framesSinceStateChange = 0;
    // Reset internal state after a state change.
    const resetState = () => {
        isSpeechActive = false;
        framesSinceStateChange = 0;
        // Clear any pending audio samples to avoid using outdated values.
        sampleBuffer = [];
        silero.resetState();
        logger.silly("State reset -- sampleBuffer cleared");
    };
    return async function process(chunk, callback) {
        // Convert the incoming chunk to normalized Float32 samples (using chunkToFloat32Array)
        const float32Array = (0, chunkToFloat32Array_1.chunkToFloat32Array)(chunk);
        sampleBuffer.push(...float32Array);
        // Wait until we've collected a full frame worth of samples.
        while (sampleBuffer.length >= FULL_FRAME_SIZE) {
            const fullFrame = sampleBuffer.slice(0, FULL_FRAME_SIZE);
            sampleBuffer = sampleBuffer.slice(FULL_FRAME_SIZE);
            // Use the last BUFFER_SIZE samples from the full frame.
            const frame = fullFrame.slice(fullFrame.length - BUFFER_SIZE);
            const result = await silero.process(new Float32Array(frame));
            const rawScore = result.isSpeech;
            logger.silly("Frame processing", {
                rawScore,
                isSpeechActive,
                framesSinceStateChange,
                pendingSamples: sampleBuffer.length
            });
            framesSinceStateChange++;
            if (isSpeechActive) {
                // If already in speech, check if the score has dropped below deactivationThreshold
                if (rawScore < deactivationThreshold &&
                    framesSinceStateChange >= debounceFrames) {
                    callback("SPEECH_END");
                    resetState();
                    logger.silly("Speech end detected", { rawScore });
                    continue;
                }
            }
            else {
                // If currently not speaking, check if the score is above activationThreshold
                if (rawScore > activationThreshold &&
                    framesSinceStateChange >= debounceFrames) {
                    isSpeechActive = true;
                    framesSinceStateChange = 0;
                    callback("SPEECH_START");
                    logger.silly("Speech start detected", { rawScore });
                }
            }
        }
    };
}
