"use strict";
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __export = (target, all) => {
  for (var name in all)
    __defProp(target, name, { get: all[name], enumerable: true });
};
var __copyProps = (to, from, except, desc) => {
  if (from && typeof from === "object" || typeof from === "function") {
    for (let key of __getOwnPropNames(from))
      if (!__hasOwnProp.call(to, key) && key !== except)
        __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
  }
  return to;
};
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
var stt_exports = {};
__export(stt_exports, {
  STT: () => STT,
  SpeechStream: () => SpeechStream
});
module.exports = __toCommonJS(stt_exports);
var import_rtc_node = require("@livekit/rtc-node");
var import_exceptions = require("../_exceptions.cjs");
var import_audio = require("../audio.cjs");
var import_log = require("../log.cjs");
var import_stream_channel = require("../stream/stream_channel.cjs");
var import_stt = require("../stt/index.cjs");
var import_types = require("../types.cjs");
var import_utils = require("../utils.cjs");
var import_io = require("../voice/io.cjs");
var import_api_protos = require("./api_protos.cjs");
var import_utils2 = require("./utils.cjs");
const DEFAULT_ENCODING = "pcm_s16le";
const DEFAULT_SAMPLE_RATE = 16e3;
const DEFAULT_BASE_URL = "wss://agent-gateway.livekit.cloud/v1";
const DEFAULT_CANCEL_TIMEOUT = 5e3;
class STT extends import_stt.STT {
  opts;
  streams = /* @__PURE__ */ new Set();
  #logger = (0, import_log.log)();
  constructor(opts) {
    super({ streaming: true, interimResults: true, alignedTranscript: "word" });
    const {
      model,
      language,
      baseURL,
      encoding = DEFAULT_ENCODING,
      sampleRate = DEFAULT_SAMPLE_RATE,
      apiKey,
      apiSecret,
      modelOptions = {}
    } = opts || {};
    const lkBaseURL = baseURL || process.env.LIVEKIT_INFERENCE_URL || DEFAULT_BASE_URL;
    const lkApiKey = apiKey || process.env.LIVEKIT_INFERENCE_API_KEY || process.env.LIVEKIT_API_KEY;
    if (!lkApiKey) {
      throw new Error("apiKey is required: pass apiKey or set LIVEKIT_API_KEY");
    }
    const lkApiSecret = apiSecret || process.env.LIVEKIT_INFERENCE_API_SECRET || process.env.LIVEKIT_API_SECRET;
    if (!lkApiSecret) {
      throw new Error("apiSecret is required: pass apiSecret or set LIVEKIT_API_SECRET");
    }
    this.opts = {
      model,
      language,
      encoding,
      sampleRate,
      baseURL: lkBaseURL,
      apiKey: lkApiKey,
      apiSecret: lkApiSecret,
      modelOptions
    };
  }
  get label() {
    return "inference.STT";
  }
  static fromModelString(modelString) {
    if (modelString.includes(":")) {
      const [model, language] = modelString.split(":");
      return new STT({ model, language });
    }
    return new STT({ model: modelString });
  }
  async _recognize(_) {
    throw new Error("LiveKit STT does not support batch recognition, use stream() instead");
  }
  updateOptions(opts) {
    this.opts = { ...this.opts, ...opts };
    for (const stream of this.streams) {
      stream.updateOptions(opts);
    }
  }
  stream(options) {
    const { language, connOptions = import_types.DEFAULT_API_CONNECT_OPTIONS } = options || {};
    const streamOpts = {
      ...this.opts,
      language: language ?? this.opts.language
    };
    const stream = new SpeechStream(this, streamOpts, connOptions);
    this.streams.add(stream);
    return stream;
  }
  async connectWs(timeout) {
    const params = {
      settings: {
        sample_rate: String(this.opts.sampleRate),
        encoding: this.opts.encoding,
        extra: this.opts.modelOptions
      }
    };
    if (this.opts.model && this.opts.model !== "auto") {
      params.model = this.opts.model;
    }
    if (this.opts.language) {
      params.settings.language = this.opts.language;
    }
    let baseURL = this.opts.baseURL;
    if (baseURL.startsWith("http://") || baseURL.startsWith("https://")) {
      baseURL = baseURL.replace("http", "ws");
    }
    const token = await (0, import_utils2.createAccessToken)(this.opts.apiKey, this.opts.apiSecret);
    const url = `${baseURL}/stt`;
    const headers = { Authorization: `Bearer ${token}` };
    const socket = await (0, import_utils2.connectWs)(url, headers, timeout);
    const msg = { ...params, type: "session.create" };
    socket.send(JSON.stringify(msg));
    return socket;
  }
}
class SpeechStream extends import_stt.SpeechStream {
  opts;
  requestId = (0, import_utils.shortuuid)("stt_request_");
  speaking = false;
  speechDuration = 0;
  reconnectEvent = new import_utils.Event();
  stt;
  connOptions;
  #logger = (0, import_log.log)();
  constructor(sttImpl, opts, connOptions) {
    super(sttImpl, opts.sampleRate, connOptions);
    this.opts = opts;
    this.stt = sttImpl;
    this.connOptions = connOptions;
  }
  get label() {
    return "inference.SpeechStream";
  }
  updateOptions(opts) {
    this.opts = { ...this.opts, ...opts };
    this.reconnectEvent.set();
  }
  async run() {
    while (true) {
      let ws = null;
      let closing = false;
      let finalReceived = false;
      const eventChannel = (0, import_stream_channel.createStreamChannel)();
      const resourceCleanup = () => {
        if (closing) return;
        closing = true;
        eventChannel.close();
        ws == null ? void 0 : ws.removeAllListeners();
        ws == null ? void 0 : ws.close();
      };
      const createWsListener = async (ws2, signal) => {
        return new Promise((resolve, reject) => {
          const onAbort = () => {
            resourceCleanup();
            reject(new Error("WebSocket connection aborted"));
          };
          signal.addEventListener("abort", onAbort, { once: true });
          ws2.on("message", (data) => {
            const json = JSON.parse(data.toString());
            eventChannel.write(json);
          });
          ws2.on("error", (e) => {
            this.#logger.error({ error: e }, "WebSocket error");
            resourceCleanup();
            reject(e);
          });
          ws2.on("close", (code) => {
            resourceCleanup();
            if (!closing) return this.#logger.error("WebSocket closed unexpectedly");
            if (finalReceived) return resolve();
            reject(
              new import_exceptions.APIStatusError({
                message: "LiveKit STT connection closed unexpectedly",
                options: { statusCode: code }
              })
            );
          });
        });
      };
      const send = async (socket, signal) => {
        const audioStream = new import_audio.AudioByteStream(
          this.opts.sampleRate,
          1,
          Math.floor(this.opts.sampleRate / 20)
          // 50ms
        );
        const abortPromise = new Promise((_, reject) => {
          if (signal.aborted) {
            return reject(new Error("Send aborted"));
          }
          const onAbort = () => reject(new Error("Send aborted"));
          signal.addEventListener("abort", onAbort, { once: true });
        });
        const iterator = this.input[Symbol.asyncIterator]();
        try {
          while (true) {
            const result = await Promise.race([iterator.next(), abortPromise]);
            if (result.done) break;
            const ev = result.value;
            let frames;
            if (ev === SpeechStream.FLUSH_SENTINEL) {
              frames = audioStream.flush();
            } else {
              const frame = ev;
              frames = audioStream.write(new Int16Array(frame.data).buffer);
            }
            for (const frame of frames) {
              this.speechDuration += frame.samplesPerChannel / frame.sampleRate;
              const base64 = Buffer.from(frame.data.buffer).toString("base64");
              const msg = { type: "input_audio", audio: base64 };
              socket.send(JSON.stringify(msg));
            }
          }
          closing = true;
          socket.send(JSON.stringify({ type: "session.finalize" }));
        } catch (e) {
          if (e.message === "Send aborted") {
            return;
          }
          throw e;
        }
      };
      const recv = async (signal) => {
        const serverEventStream = eventChannel.stream();
        const reader = serverEventStream.getReader();
        try {
          while (!this.closed && !signal.aborted) {
            const result = await reader.read();
            if (signal.aborted) return;
            if (result.done) return;
            const parseResult = await import_api_protos.sttServerEventSchema.safeParseAsync(result.value);
            if (!parseResult.success) {
              this.#logger.warn(
                { error: parseResult.error, rawData: result.value },
                "Failed to parse STT server event"
              );
              continue;
            }
            const event = parseResult.data;
            switch (event.type) {
              case "session.created":
              case "session.finalized":
                break;
              case "session.closed":
                finalReceived = true;
                resourceCleanup();
                break;
              case "interim_transcript":
                this.processTranscript(event, false);
                break;
              case "final_transcript":
                this.processTranscript(event, true);
                break;
              case "error":
                this.#logger.error({ error: event }, "Received error from LiveKit STT");
                resourceCleanup();
                throw new import_exceptions.APIError(`LiveKit STT returned error: ${JSON.stringify(event)}`);
            }
          }
        } finally {
          reader.releaseLock();
          try {
            await serverEventStream.cancel();
          } catch (e) {
            this.#logger.debug("Error cancelling serverEventStream (may already be cancelled):", e);
          }
        }
      };
      try {
        ws = await this.stt.connectWs(this.connOptions.timeoutMs);
        const controller = this.abortController;
        const sendTask = import_utils.Task.from(({ signal }) => send(ws, signal), controller);
        const wsListenerTask = import_utils.Task.from(({ signal }) => createWsListener(ws, signal), controller);
        const recvTask = import_utils.Task.from(({ signal }) => recv(signal), controller);
        const waitReconnectTask = import_utils.Task.from(
          ({ signal }) => Promise.race([this.reconnectEvent.wait(), (0, import_utils.waitForAbort)(signal)]),
          controller
        );
        try {
          await Promise.race([
            Promise.all([sendTask.result, wsListenerTask.result, recvTask.result]),
            waitReconnectTask.result
          ]);
          if (!waitReconnectTask.done) break;
          this.reconnectEvent.clear();
        } finally {
          await (0, import_utils.cancelAndWait)(
            [sendTask, wsListenerTask, recvTask, waitReconnectTask],
            DEFAULT_CANCEL_TIMEOUT
          );
          resourceCleanup();
        }
      } finally {
        resourceCleanup();
      }
    }
  }
  processTranscript(data, isFinal) {
    if (this.queue.closed) return;
    const requestId = data.session_id || this.requestId;
    const text = data.transcript;
    const language = data.language || this.opts.language || "en";
    if (!text && !isFinal) return;
    try {
      if (!this.speaking) {
        this.speaking = true;
        this.queue.put({ type: import_stt.SpeechEventType.START_OF_SPEECH });
      }
      const speechData = {
        language,
        startTime: this.startTimeOffset + data.start,
        endTime: this.startTimeOffset + data.start + data.duration,
        confidence: data.confidence,
        text,
        words: data.words.map(
          (word) => (0, import_io.createTimedString)({
            text: word.word,
            startTime: word.start + this.startTimeOffset,
            endTime: word.end + this.startTimeOffset,
            startTimeOffset: this.startTimeOffset,
            confidence: word.confidence
          })
        )
      };
      if (isFinal) {
        if (this.speechDuration > 0) {
          this.queue.put({
            type: import_stt.SpeechEventType.RECOGNITION_USAGE,
            requestId,
            recognitionUsage: { audioDuration: this.speechDuration }
          });
          this.speechDuration = 0;
        }
        this.queue.put({
          type: import_stt.SpeechEventType.FINAL_TRANSCRIPT,
          requestId,
          alternatives: [speechData]
        });
        if (this.speaking) {
          this.speaking = false;
          this.queue.put({ type: import_stt.SpeechEventType.END_OF_SPEECH });
        }
      } else {
        this.queue.put({
          type: import_stt.SpeechEventType.INTERIM_TRANSCRIPT,
          requestId,
          alternatives: [speechData]
        });
      }
    } catch (e) {
      if (e instanceof Error && e.message.includes("Queue is closed")) {
        this.#logger.warn(
          { err: e },
          "Queue closed during transcript processing (expected during disconnect)"
        );
      } else {
        this.#logger.error({ err: e }, "Error putting transcript to queue");
      }
    }
  }
}
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
  STT,
  SpeechStream
});
//# sourceMappingURL=stt.cjs.map