iobroker.assistant 1.4.4 → 1.4.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (36) hide show
  1. package/README.md +7 -0
  2. package/admin/custom/.vite/manifest.json +1 -1
  3. package/admin/custom/assets/Components-BR57MZLJ.js +2 -0
  4. package/admin/custom/customComponents.js +1 -1
  5. package/admin/custom/i18n/de.json +3 -0
  6. package/admin/custom/i18n/en.json +3 -0
  7. package/admin/custom/i18n/es.json +3 -0
  8. package/admin/custom/i18n/fr.json +3 -0
  9. package/admin/custom/i18n/it.json +3 -0
  10. package/admin/custom/i18n/nl.json +3 -0
  11. package/admin/custom/i18n/pl.json +3 -0
  12. package/admin/custom/i18n/pt.json +3 -0
  13. package/admin/custom/i18n/ru.json +3 -0
  14. package/admin/custom/i18n/uk.json +3 -0
  15. package/admin/custom/i18n/zh-cn.json +3 -0
  16. package/admin/custom/index.html +1 -1
  17. package/admin/custom/mf-manifest.json +1 -1
  18. package/admin/custom/mf-stats.json +1 -1
  19. package/build/lib/voice/esphome.js +160 -19
  20. package/build/lib/voice/esphome.js.map +1 -1
  21. package/build/lib/voice/esphomeEntities.js +76 -6
  22. package/build/lib/voice/esphomeEntities.js.map +1 -1
  23. package/build/lib/voice/esphomeProto.js.map +1 -1
  24. package/build/lib/voice/flac.js +162 -0
  25. package/build/lib/voice/flac.js.map +1 -0
  26. package/build/lib/voice/mediaServer.js +8 -1
  27. package/build/lib/voice/mediaServer.js.map +1 -1
  28. package/build/lib/voice/replyFormat.js +158 -0
  29. package/build/lib/voice/replyFormat.js.map +1 -0
  30. package/build/lib/voice/stt.js +2 -3
  31. package/build/lib/voice/stt.js.map +1 -1
  32. package/build/main.js +153 -3
  33. package/build/main.js.map +1 -1
  34. package/io-package.json +14 -14
  35. package/package.json +1 -1
  36. package/admin/custom/assets/Components-CCl7INIF.js +0 -2
@@ -0,0 +1,158 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.LEGACY_FORMAT = exports.CONTENT_TYPES = void 0;
4
+ exports.chooseReplyFormat = chooseReplyFormat;
5
+ exports.resamplePcm = resamplePcm;
6
+ exports.monoToStereo = monoToStereo;
7
+ exports.encodeReply = encodeReply;
8
+ /**
9
+ * Which audio format an ESPHome satellite gets its spoken replies in.
10
+ *
11
+ * A media player announces the formats it takes (`ListEntitiesMediaPlayerResponse.supported_formats`, one per
12
+ * purpose: default playback and announcements). Home Assistant transcodes every reply to the announcement format,
13
+ * so that is the only one a firmware is tested with — and since ESPHome 2026.10 often the only one it can decode at
14
+ * all: the player is built with just the codecs its pipelines use. We do the same: the announcement format first,
15
+ * at its sample rate and channel count. A device that lists nothing (linux-voice-assistant, older firmware) keeps
16
+ * getting WAV as before.
17
+ */
18
+ const flac_1 = require("./flac");
19
+ const stt_1 = require("./stt");
20
+ /** Codecs written here, without any tool. */
21
+ const NATIVE = ['flac', 'wav'];
22
+ const EXTERNAL = ['mp3', 'opus'];
23
+ exports.CONTENT_TYPES = {
24
+ wav: 'audio/wav',
25
+ flac: 'audio/flac',
26
+ mp3: 'audio/mpeg',
27
+ // ESPHome takes Opus only as `audio/ogg` with an opus codecs parameter.
28
+ opus: 'audio/ogg; codecs=opus',
29
+ };
30
+ /** The format replies have always had: WAV at the rate of the TTS engine. */
31
+ exports.LEGACY_FORMAT = { codec: 'wav', sampleRate: 0, channels: 1, source: '' };
32
+ function describe(f) {
33
+ return `${f.format}${f.sampleRate ? ` ${f.sampleRate} Hz` : ''}${f.channels ? ` ×${f.channels}` : ''} (${f.purpose})`;
34
+ }
35
+ /**
36
+ * Pick the reply format from what the device's media players announced.
37
+ *
38
+ * @param formats every `supported_formats` entry of the device
39
+ * @param external whether MP3/Opus can be produced (ffmpeg)
40
+ */
41
+ function chooseReplyFormat(formats, external) {
42
+ if (!formats.length) {
43
+ return exports.LEGACY_FORMAT;
44
+ }
45
+ const usable = (f) => {
46
+ const codec = f.format.trim().toLowerCase();
47
+ return NATIVE.includes(codec) || (external && EXTERNAL.includes(codec)) ? codec : null;
48
+ };
49
+ // Announcements first (that is how a reply is played), our own codecs before ffmpeg ones.
50
+ const ordered = [
51
+ ...formats.filter(f => f.purpose === 'announcement'),
52
+ ...formats.filter(f => f.purpose !== 'announcement'),
53
+ ];
54
+ const pick = ordered.find(f => {
55
+ const codec = usable(f);
56
+ return codec !== null && NATIVE.includes(codec);
57
+ }) ?? ordered.find(f => usable(f) !== null);
58
+ if (!pick) {
59
+ // Nothing we can write (or `none` = the device takes anything): WAV, as before.
60
+ return { ...exports.LEGACY_FORMAT, source: ordered.map(describe).join(', ') };
61
+ }
62
+ return {
63
+ codec: usable(pick),
64
+ sampleRate: pick.sampleRate || 0,
65
+ channels: pick.channels === 2 ? 2 : 1,
66
+ source: describe(pick),
67
+ };
68
+ }
69
+ /** Filter taps per side at the lower of the two rates, and the number of precomputed sub-sample positions. */
70
+ const ZERO_CROSSINGS = 8;
71
+ const PHASES = 128;
72
+ /**
73
+ * Resample mono s16le PCM with a Hann-windowed sinc. Cheap enough for the voice path (a table per sub-sample
74
+ * position, ~20 taps when upsampling), and — unlike linear interpolation — it filters before it decimates, so a
75
+ * 24 kHz voice taken down to 16 kHz does not fold its sibilants back into the speech band.
76
+ */
77
+ function resamplePcm(pcm, from, to) {
78
+ const n = pcm.length >> 1;
79
+ if (from === to || !n || from <= 0 || to <= 0) {
80
+ return pcm;
81
+ }
82
+ const input = new Float32Array(n);
83
+ for (let i = 0; i < n; i++) {
84
+ input[i] = pcm.readInt16LE(i * 2);
85
+ }
86
+ const ratio = to / from;
87
+ // A little below the Nyquist frequency of the lower rate.
88
+ const cutoff = Math.min(1, ratio) * 0.95;
89
+ const half = Math.ceil(ZERO_CROSSINGS / cutoff);
90
+ const taps = 2 * half;
91
+ const table = new Float32Array((PHASES + 1) * taps);
92
+ for (let p = 0; p <= PHASES; p++) {
93
+ const frac = p / PHASES;
94
+ let sum = 0;
95
+ for (let k = 0; k < taps; k++) {
96
+ const d = k - half + 1 - frac; // distance of the input sample from the output position
97
+ const x = d * cutoff;
98
+ const sinc = x === 0 ? 1 : Math.sin(Math.PI * x) / (Math.PI * x);
99
+ const w = Math.abs(d) >= half ? 0 : 0.5 + 0.5 * Math.cos((Math.PI * d) / half);
100
+ table[p * taps + k] = sinc * w;
101
+ sum += sinc * w;
102
+ }
103
+ for (let k = 0; k < taps; k++) {
104
+ table[p * taps + k] /= sum; // unity gain at every position: no ripple on a constant level
105
+ }
106
+ }
107
+ const outLen = Math.max(1, Math.round(n * ratio));
108
+ const out = Buffer.alloc(outLen * 2);
109
+ for (let i = 0; i < outLen; i++) {
110
+ const center = i / ratio;
111
+ const base = Math.floor(center);
112
+ const row = Math.round((center - base) * PHASES) * taps;
113
+ const first = base - half + 1;
114
+ let acc = 0;
115
+ for (let k = 0; k < taps; k++) {
116
+ const j = first + k;
117
+ if (j >= 0 && j < n) {
118
+ acc += input[j] * table[row + k];
119
+ }
120
+ }
121
+ out.writeInt16LE(Math.max(-32768, Math.min(32767, Math.round(acc))), i * 2);
122
+ }
123
+ return out;
124
+ }
125
+ /** Duplicate mono s16le PCM into interleaved stereo. */
126
+ function monoToStereo(pcm) {
127
+ const n = pcm.length >> 1;
128
+ const out = Buffer.alloc(n * 4);
129
+ for (let i = 0; i < n; i++) {
130
+ const v = pcm.readInt16LE(i * 2);
131
+ out.writeInt16LE(v, i * 4);
132
+ out.writeInt16LE(v, i * 4 + 2);
133
+ }
134
+ return out;
135
+ }
136
+ /**
137
+ * Encode a mono reply in `format`. MP3/Opus go through `external`; everything else is written here.
138
+ * Throws when `external` is needed but missing or fails — the caller falls back to a native format.
139
+ */
140
+ async function encodeReply(pcm, sampleRate, format, external) {
141
+ const rate = format.sampleRate || sampleRate;
142
+ if (format.codec === 'mp3' || format.codec === 'opus') {
143
+ if (!external) {
144
+ throw new Error(`no encoder for ${format.codec}`);
145
+ }
146
+ const body = await external(pcm, sampleRate, {
147
+ codec: format.codec,
148
+ sampleRate: rate,
149
+ channels: format.channels,
150
+ });
151
+ return { body, contentType: exports.CONTENT_TYPES[format.codec] };
152
+ }
153
+ const resampled = resamplePcm(pcm, sampleRate, rate);
154
+ const samples = format.channels === 2 ? monoToStereo(resampled) : resampled;
155
+ const body = format.codec === 'flac' ? (0, flac_1.encodeFlac)(samples, rate, format.channels) : (0, stt_1.pcmToWav)(samples, rate, format.channels);
156
+ return { body, contentType: exports.CONTENT_TYPES[format.codec] };
157
+ }
158
+ //# sourceMappingURL=replyFormat.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"replyFormat.js","sourceRoot":"","sources":["../../../src/lib/voice/replyFormat.ts"],"names":[],"mappings":";;;AAoEA,8CA4BC;AAWD,kCA+CC;AAGD,oCASC;AAMD,kCAuBC;AAnMD;;;;;;;;;GASG;AACH,iCAAoC;AACpC,+BAAiC;AAgCjC,6CAA6C;AAC7C,MAAM,MAAM,GAAiB,CAAC,MAAM,EAAE,KAAK,CAAC,CAAC;AAC7C,MAAM,QAAQ,GAAiB,CAAC,KAAK,EAAE,MAAM,CAAC,CAAC;AAElC,QAAA,aAAa,GAA+B;IACrD,GAAG,EAAE,WAAW;IAChB,IAAI,EAAE,YAAY;IAClB,GAAG,EAAE,YAAY;IACjB,wEAAwE;IACxE,IAAI,EAAE,wBAAwB;CACjC,CAAC;AAEF,6EAA6E;AAChE,QAAA,aAAa,GAAgB,EAAE,KAAK,EAAE,KAAK,EAAE,UAAU,EAAE,CAAC,EAAE,QAAQ,EAAE,CAAC,EAAE,MAAM,EAAE,EAAE,EAAE,CAAC;AAEnG,SAAS,QAAQ,CAAC,CAAc;IAC5B,OAAO,GAAG,CAAC,CAAC,MAAM,GAAG,CAAC,CAAC,UAAU,CAAC,CAAC,CAAC,IAAI,CAAC,CAAC,UAAU,KAAK,CAAC,CAAC,CAAC,EAAE,GAAG,CAAC,CAAC,QAAQ,CAAC,CAAC,CAAC,KAAK,CAAC,CAAC,QAAQ,EAAE,CAAC,CAAC,CAAC,EAAE,KAAK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MAAM,OAAO,GAAG,MAAM,CAAC,QAAQ,KAAK,CAAC,CAAC,CAAC,CAAC,YAAY,CAAC,SAAS,CAAC,CAAC,CAAC,CAAC,SAAS,CAAC;IAC5E,MAAM,IAAI,GACN,MAAM,CAAC,KAAK,KAAK,MAAM,CAAC,CAAC,CAAC,IAAA,iBAAU,EAAC,OAAO,EAAE,IAAI,EAAE,MAAM,CAAC,QAAQ,CAAC,CAAC,CAAC,CAAC,IAAA,cAAQ,EAAC,OAAO,EAAE,IAAI,EAAE,MAAM,CAAC,QAAQ,CAAC,CAAC;IACpH,OAAO,EAAE,IAAI,EAAE,WAAW,EAAE,qBAAa,CAAC,MAAM,CAAC,KAAK,CAAC,EAAE,CAAC;AAC9D,CAAC","sourcesContent":["/**\n * Which audio format an ESPHome satellite gets its spoken replies in.\n *\n * A media player announces the formats it takes (`ListEntitiesMediaPlayerResponse.supported_formats`, one per\n * purpose: default playback and announcements). Home Assistant transcodes every reply to the announcement format,\n * so that is the only one a firmware is tested with — and since ESPHome 2026.10 often the only one it can decode at\n * all: the player is built with just the codecs its pipelines use. We do the same: the announcement format first,\n * at its sample rate and channel count. A device that lists nothing (linux-voice-assistant, older firmware) keeps\n * getting WAV as before.\n */\nimport { encodeFlac } from './flac';\nimport { pcmToWav } from './stt';\n\n/** One entry of `supported_formats`. */\nexport interface MediaFormat {\n /** `flac`, `mp3`, `wav`, `opus`, `none` … as the device names it. */\n format: string;\n /** 0 = no preference. */\n sampleRate: number;\n /** 0 = no preference. */\n channels: number;\n purpose: 'default' | 'announcement';\n sampleBytes: number;\n}\n\nexport type ReplyCodec = 'wav' | 'flac' | 'mp3' | 'opus';\n\nexport interface ReplyFormat {\n codec: ReplyCodec;\n /** Target rate; 0 keeps the rate of the TTS engine. */\n sampleRate: number;\n channels: 1 | 2;\n /** What the device asked for, for the log. */\n source: string;\n}\n\n/** Turns PCM into a codec we cannot write ourselves (MP3, Opus) — ffmpeg in the adapter. */\nexport type ExternalEncoder = (\n pcm: Buffer,\n sampleRate: number,\n target: { codec: 'mp3' | 'opus'; sampleRate: number; channels: number },\n) => Promise<Buffer>;\n\n/** Codecs written here, without any tool. */\nconst NATIVE: ReplyCodec[] = ['flac', 'wav'];\nconst EXTERNAL: ReplyCodec[] = ['mp3', 'opus'];\n\nexport const CONTENT_TYPES: Record<ReplyCodec, string> = {\n wav: 'audio/wav',\n flac: 'audio/flac',\n mp3: 'audio/mpeg',\n // ESPHome takes Opus only as `audio/ogg` with an opus codecs parameter.\n opus: 'audio/ogg; codecs=opus',\n};\n\n/** The format replies have always had: WAV at the rate of the TTS engine. */\nexport const LEGACY_FORMAT: ReplyFormat = { codec: 'wav', sampleRate: 0, channels: 1, source: '' };\n\nfunction describe(f: MediaFormat): string {\n return `${f.format}${f.sampleRate ? ` ${f.sampleRate} Hz` : ''}${f.channels ? ` ×${f.channels}` : ''} (${f.purpose})`;\n}\n\n/**\n * Pick the reply format from what the device's media players announced.\n *\n * @param formats every `supported_formats` entry of the device\n * @param external whether MP3/Opus can be produced (ffmpeg)\n */\nexport function chooseReplyFormat(formats: MediaFormat[], external: boolean): ReplyFormat {\n if (!formats.length) {\n return LEGACY_FORMAT;\n }\n const usable = (f: MediaFormat): ReplyCodec | null => {\n const codec = f.format.trim().toLowerCase() as ReplyCodec;\n return NATIVE.includes(codec) || (external && EXTERNAL.includes(codec)) ? codec : null;\n };\n // Announcements first (that is how a reply is played), our own codecs before ffmpeg ones.\n const ordered = [\n ...formats.filter(f => f.purpose === 'announcement'),\n ...formats.filter(f => f.purpose !== 'announcement'),\n ];\n const pick =\n ordered.find(f => {\n const codec = usable(f);\n return codec !== null && NATIVE.includes(codec);\n }) ?? ordered.find(f => usable(f) !== null);\n if (!pick) {\n // Nothing we can write (or `none` = the device takes anything): WAV, as before.\n return { ...LEGACY_FORMAT, source: ordered.map(describe).join(', ') };\n }\n return {\n codec: usable(pick) as ReplyCodec,\n sampleRate: pick.sampleRate || 0,\n channels: pick.channels === 2 ? 2 : 1,\n source: describe(pick),\n };\n}\n\n/** Filter taps per side at the lower of the two rates, and the number of precomputed sub-sample positions. */\nconst ZERO_CROSSINGS = 8;\nconst PHASES = 128;\n\n/**\n * Resample mono s16le PCM with a Hann-windowed sinc. Cheap enough for the voice path (a table per sub-sample\n * position, ~20 taps when upsampling), and — unlike linear interpolation — it filters before it decimates, so a\n * 24 kHz voice taken down to 16 kHz does not fold its sibilants back into the speech band.\n */\nexport function resamplePcm(pcm: Buffer, from: number, to: number): Buffer {\n const n = pcm.length >> 1;\n if (from === to || !n || from <= 0 || to <= 0) {\n return pcm;\n }\n const input = new Float32Array(n);\n for (let i = 0; i < n; i++) {\n input[i] = pcm.readInt16LE(i * 2);\n }\n const ratio = to / from;\n // A little below the Nyquist frequency of the lower rate.\n const cutoff = Math.min(1, ratio) * 0.95;\n const half = Math.ceil(ZERO_CROSSINGS / cutoff);\n const taps = 2 * half;\n const table = new Float32Array((PHASES + 1) * taps);\n for (let p = 0; p <= PHASES; p++) {\n const frac = p / PHASES;\n let sum = 0;\n for (let k = 0; k < taps; k++) {\n const d = k - half + 1 - frac; // distance of the input sample from the output position\n const x = d * cutoff;\n const sinc = x === 0 ? 1 : Math.sin(Math.PI * x) / (Math.PI * x);\n const w = Math.abs(d) >= half ? 0 : 0.5 + 0.5 * Math.cos((Math.PI * d) / half);\n table[p * taps + k] = sinc * w;\n sum += sinc * w;\n }\n for (let k = 0; k < taps; k++) {\n table[p * taps + k] /= sum; // unity gain at every position: no ripple on a constant level\n }\n }\n const outLen = Math.max(1, Math.round(n * ratio));\n const out = Buffer.alloc(outLen * 2);\n for (let i = 0; i < outLen; i++) {\n const center = i / ratio;\n const base = Math.floor(center);\n const row = Math.round((center - base) * PHASES) * taps;\n const first = base - half + 1;\n let acc = 0;\n for (let k = 0; k < taps; k++) {\n const j = first + k;\n if (j >= 0 && j < n) {\n acc += input[j] * table[row + k];\n }\n }\n out.writeInt16LE(Math.max(-32768, Math.min(32767, Math.round(acc))), i * 2);\n }\n return out;\n}\n\n/** Duplicate mono s16le PCM into interleaved stereo. */\nexport function monoToStereo(pcm: Buffer): Buffer {\n const n = pcm.length >> 1;\n const out = Buffer.alloc(n * 4);\n for (let i = 0; i < n; i++) {\n const v = pcm.readInt16LE(i * 2);\n out.writeInt16LE(v, i * 4);\n out.writeInt16LE(v, i * 4 + 2);\n }\n return out;\n}\n\n/**\n * Encode a mono reply in `format`. MP3/Opus go through `external`; everything else is written here.\n * Throws when `external` is needed but missing or fails — the caller falls back to a native format.\n */\nexport async function encodeReply(\n pcm: Buffer,\n sampleRate: number,\n format: ReplyFormat,\n external?: ExternalEncoder,\n): Promise<{ body: Buffer; contentType: string }> {\n const rate = format.sampleRate || sampleRate;\n if (format.codec === 'mp3' || format.codec === 'opus') {\n if (!external) {\n throw new Error(`no encoder for ${format.codec}`);\n }\n const body = await external(pcm, sampleRate, {\n codec: format.codec,\n sampleRate: rate,\n channels: format.channels,\n });\n return { body, contentType: CONTENT_TYPES[format.codec] };\n }\n const resampled = resamplePcm(pcm, sampleRate, rate);\n const samples = format.channels === 2 ? monoToStereo(resampled) : resampled;\n const body =\n format.codec === 'flac' ? encodeFlac(samples, rate, format.channels) : pcmToWav(samples, rate, format.channels);\n return { body, contentType: CONTENT_TYPES[format.codec] };\n}\n"]}
@@ -67,9 +67,8 @@ function hintsToPrompt(hints, maxChars = 800) {
67
67
  }
68
68
  return parts.join(', ');
69
69
  }
70
- /** Wrap raw mono 16-bit-signed-LE PCM into a minimal 44-byte WAV container. */
71
- function pcmToWav(pcm, sampleRate) {
72
- const numChannels = 1;
70
+ /** Wrap raw 16-bit-signed-LE PCM (mono, or interleaved stereo) into a minimal 44-byte WAV container. */
71
+ function pcmToWav(pcm, sampleRate, numChannels = 1) {
73
72
  const bitsPerSample = 16;
74
73
  const blockAlign = (numChannels * bitsPerSample) / 8;
75
74
  const byteRate = sampleRate * blockAlign;
@@ -1 +1 @@
1
- {"version":3,"file":"stt.js","sourceRoot":"","sources":["../../../src/lib/voice/stt.ts"],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AAC,KAAK,GAAG,KAAK,CAAC;IACvB,CAAC;IAED,KAAK,CAAC,UAAU,CAAC,GAAW,EAAE,UAAkB,EAAE,IAAY,EAAE,KAAgB;QAC5E,MAAM,IAAI,GAAG,MAAM,IAAA,eAAM,EAAC,QAAQ,CAAC,GAAG,EAAE,UAAU,CAAC,EAAE,WAAW,EAAE,EAAE,IAAI,EAAE,WAAW,EAAE,CAAC,CAAC;QACzF,mGAAmG;QACnG,kFAAkF;QAClF,MAAM,MAAM,GAAG,aAAa,CAAC,KAAK,CAAC,CAAC;QACpC,MAAM,GAAG,GAAG,MAAM,IAAI,CAAC,MAAM,CAAC,KAAK,CAAC,cAAc,CAAC,MAAM,CAAC;YACtD,IAAI;YACJ,KAAK,EAAE,IAAI,CAAC,KAAK;YACjB,0FAA0F;YAC1F,QAAQ,EAAE,CAAC,IAAI,IAAI,EAAE,CAAC,CAAC,KAAK,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC,IAAI,SAAS;YACjD,GAAG,CAAC,MAAM,CAAC,CAAC,CAAC,EAAE,MAAM,EAAE,CAAC,CAAC,CAAC,EAAE,CAAC;SAChC,CAAC,CAAC;QACH,OAAO,CAAC,GAAG,CAAC,IAAI,IAAI,EAAE,CAAC,CAAC,IAAI,EAAE,CAAC;IACnC,CAAC;CACJ;AAvBD,8BAuBC","sourcesContent":["/**\n * Speech-to-text engines. V1 ships the cloud engine (OpenAI Whisper); local engines\n * (Vosk / whisper.cpp / Wyoming) plug in behind the same `SttEngine` interface later.\n */\nimport OpenAI, { toFile } from 'openai';\n\nexport interface SttEngine {\n /**\n * Transcribe raw mono 16-bit PCM. `lang` is an ISO-639-1 hint ('' = auto-detect).\n *\n * `hints` is an optional domain vocabulary (device / room / scene names …) to bias recognition toward,\n * so the engine better transcribes those proper nouns. Only engines that support *soft* biasing use it\n * (OpenAI Whisper `prompt`, Azure phrase list); engines where a word list would be a hard constraint or\n * needs pre-registration (Vosk grammar, AWS custom vocabulary) ignore it.\n */\n transcribe(pcm: Buffer, sampleRate: number, lang: string, hints?: string[]): Promise<string>;\n /** Optional warm-up (install/download engine + model for `lang`) so the first request isn't slow. */\n prepare?(lang: string): Promise<void>;\n}\n\n/**\n * Join vocabulary hints into a Whisper `prompt` string (a soft bias toward these terms), de-duplicated and\n * length-bounded to stay within the model's ~224-token prompt budget. Returns '' when there are no hints.\n */\nexport function hintsToPrompt(hints: string[] | undefined, maxChars = 800): string {\n if (!hints?.length) {\n return '';\n }\n const seen = new Set<string>();\n const parts: string[] = [];\n let len = 0;\n for (const h of hints) {\n const term = (h || '').trim();\n const key = term.toLowerCase();\n if (!term || seen.has(key)) {\n continue;\n }\n if (len + term.length + 2 > maxChars) {\n break;\n }\n seen.add(key);\n parts.push(term);\n len += term.length + 2;\n }\n return parts.join(', ');\n}\n\n/** Wrap raw mono 16-bit-signed-LE PCM into a minimal 44-byte WAV container. */\nexport function pcmToWav(pcm: Buffer, sampleRate: number): Buffer {\n const numChannels = 1;\n const bitsPerSample = 16;\n const blockAlign = (numChannels * bitsPerSample) / 8;\n const byteRate = sampleRate * blockAlign;\n const header = Buffer.alloc(44);\n header.write('RIFF', 0);\n header.writeUInt32LE(36 + pcm.length, 4);\n header.write('WAVE', 8);\n header.write('fmt ', 12);\n header.writeUInt32LE(16, 16); // PCM fmt chunk size\n header.writeUInt16LE(1, 20); // audio format = PCM\n header.writeUInt16LE(numChannels, 22);\n header.writeUInt32LE(sampleRate, 24);\n header.writeUInt32LE(byteRate, 28);\n header.writeUInt16LE(blockAlign, 32);\n header.writeUInt16LE(bitsPerSample, 34);\n header.write('data', 36);\n header.writeUInt32LE(pcm.length, 40);\n return Buffer.concat([header, pcm]);\n}\n\n/** Cloud STT via the OpenAI transcription API (Whisper). */\nexport class OpenAiStt implements SttEngine {\n private readonly client: OpenAI;\n private readonly model: string;\n\n constructor(apiKey: string, model = 'whisper-1') {\n this.client = new OpenAI({ apiKey });\n this.model = model;\n }\n\n async transcribe(pcm: Buffer, sampleRate: number, lang: string, hints?: string[]): Promise<string> {\n const file = await toFile(pcmToWav(pcm, sampleRate), 'audio.wav', { type: 'audio/wav' });\n // A prompt biases Whisper toward the given domain vocabulary (device/room names) without excluding\n // other words — improves recognition of proper nouns the NLU then needs to match.\n const prompt = hintsToPrompt(hints);\n const res = await this.client.audio.transcriptions.create({\n file,\n model: this.model,\n // Whisper wants the bare ISO-639-1 code; strip any region (de-DE → de). '' → auto-detect.\n language: (lang || '').split('-')[0] || undefined,\n ...(prompt ? { prompt } : {}),\n });\n return (res.text || '').trim();\n }\n}\n"]}
1
+ {"version":3,"file":"stt.js","sourceRoot":"","sources":["../../../src/lib/voice/stt.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAwBA,sCAqBC;AAGD,4BAmBC;AAnED;;;GAGG;AACH,iDAAwC;AAgBxC;;;GAGG;AACH,SAAgB,aAAa,CAAC,KAA2B,EAAE,QAAQ,GAAG,GAAG;IACrE,IAAI,CAAC,KAAK,EAAE,MAAM,EAAE,CAAC;QACjB,OAAO,EAAE,CAAC;IACd,CAAC;IACD,MAAM,IAAI,GAAG,IAAI,GAAG,EAAU,CAAC;IAC/B,MAAM,KAAK,GAAa,EAAE,CAAC;IAC3B,IAAI,GAAG,GAAG,CAAC,CAAC;IACZ,KAAK,MAAM,CAAC,IAAI,KAAK,EAAE,CAAC;QACpB,MAAM,IAAI,GAAG,CAAC,CAAC,IAAI,EAAE,CAAC,CAAC,IAAI,EAAE,CAAC;QAC9B,MAAM,GAAG,GAAG,IAAI,CAAC,WAAW,EAAE,CAAC;QAC/B,IAAI,CAAC,IAAI,IAAI,IAAI,CAAC,GAAG,CAAC,GAAG,CAAC,EAAE,CAAC;YACzB,SAAS;QACb,CAAC;QACD,IAAI,GAAG,GAAG,IAAI,CAAC,MAAM,GAAG,CAAC,GAAG,QAAQ,EAAE,CAAC;YACnC,MAAM;QACV,CAAC;QACD,IAAI,CAAC,GAAG,CAAC,GAAG,CAAC,CAAC;QACd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\n * Speech-to-text engines. V1 ships the cloud engine (OpenAI Whisper); local engines\n * (Vosk / whisper.cpp / Wyoming) plug in behind the same `SttEngine` interface later.\n */\nimport OpenAI, { toFile } from 'openai';\n\nexport interface SttEngine {\n /**\n * Transcribe raw mono 16-bit PCM. `lang` is an ISO-639-1 hint ('' = auto-detect).\n *\n * `hints` is an optional domain vocabulary (device / room / scene names …) to bias recognition toward,\n * so the engine better transcribes those proper nouns. Only engines that support *soft* biasing use it\n * (OpenAI Whisper `prompt`, Azure phrase list); engines where a word list would be a hard constraint or\n * needs pre-registration (Vosk grammar, AWS custom vocabulary) ignore it.\n */\n transcribe(pcm: Buffer, sampleRate: number, lang: string, hints?: string[]): Promise<string>;\n /** Optional warm-up (install/download engine + model for `lang`) so the first request isn't slow. */\n prepare?(lang: string): Promise<void>;\n}\n\n/**\n * Join vocabulary hints into a Whisper `prompt` string (a soft bias toward these terms), de-duplicated and\n * length-bounded to stay within the model's ~224-token prompt budget. Returns '' when there are no hints.\n */\nexport function hintsToPrompt(hints: string[] | undefined, maxChars = 800): string {\n if (!hints?.length) {\n return '';\n }\n const seen = new Set<string>();\n const parts: string[] = [];\n let len = 0;\n for (const h of hints) {\n const term = (h || '').trim();\n const key = term.toLowerCase();\n if (!term || seen.has(key)) {\n continue;\n }\n if (len + term.length + 2 > maxChars) {\n break;\n }\n seen.add(key);\n parts.push(term);\n len += term.length + 2;\n }\n return parts.join(', ');\n}\n\n/** Wrap raw 16-bit-signed-LE PCM (mono, or interleaved stereo) into a minimal 44-byte WAV container. */\nexport function pcmToWav(pcm: Buffer, sampleRate: number, numChannels = 1): Buffer {\n const bitsPerSample = 16;\n const blockAlign = (numChannels * bitsPerSample) / 8;\n const byteRate = sampleRate * blockAlign;\n const header = Buffer.alloc(44);\n header.write('RIFF', 0);\n header.writeUInt32LE(36 + pcm.length, 4);\n header.write('WAVE', 8);\n header.write('fmt ', 12);\n header.writeUInt32LE(16, 16); // PCM fmt chunk size\n header.writeUInt16LE(1, 20); // audio format = PCM\n header.writeUInt16LE(numChannels, 22);\n header.writeUInt32LE(sampleRate, 24);\n header.writeUInt32LE(byteRate, 28);\n header.writeUInt16LE(blockAlign, 32);\n header.writeUInt16LE(bitsPerSample, 34);\n header.write('data', 36);\n header.writeUInt32LE(pcm.length, 40);\n return Buffer.concat([header, pcm]);\n}\n\n/** Cloud STT via the OpenAI transcription API (Whisper). */\nexport class OpenAiStt implements SttEngine {\n private readonly client: OpenAI;\n private readonly model: string;\n\n constructor(apiKey: string, model = 'whisper-1') {\n this.client = new OpenAI({ apiKey });\n this.model = model;\n }\n\n async transcribe(pcm: Buffer, sampleRate: number, lang: string, hints?: string[]): Promise<string> {\n const file = await toFile(pcmToWav(pcm, sampleRate), 'audio.wav', { type: 'audio/wav' });\n // A prompt biases Whisper toward the given domain vocabulary (device/room names) without excluding\n // other words — improves recognition of proper nouns the NLU then needs to match.\n const prompt = hintsToPrompt(hints);\n const res = await this.client.audio.transcriptions.create({\n file,\n model: this.model,\n // Whisper wants the bare ISO-639-1 code; strip any region (de-DE → de). '' → auto-detect.\n language: (lang || '').split('-')[0] || undefined,\n ...(prompt ? { prompt } : {}),\n });\n return (res.text || '').trim();\n }\n}\n"]}
package/build/main.js CHANGED
@@ -162,6 +162,10 @@ function valuesMatch(actual, expected) {
162
162
  }
163
163
  return String(actual).trim().toLowerCase() === String(expected).trim().toLowerCase();
164
164
  }
165
+ /** Whether an ESPHome entity id can be the last part of an ioBroker id (empty ones came from ESPHome 2026). */
166
+ function isControlId(objectId) {
167
+ return !!objectId && !/[^\p{Ll}\p{Lu}\p{Nd}_-]/u.test(objectId);
168
+ }
165
169
  /**
166
170
  * ioBroker role for a measurement, derived from its unit — a `value.temperature` shows up with the right
167
171
  * icon and in the right place in vis, where a bare `value` is just a number.
@@ -334,6 +338,8 @@ class Assistant extends adapter_core_1.Adapter {
334
338
  satControlsReady = new Map();
335
339
  /** Satellites whose `volume` state exists and is subscribed (see updateSatelliteVolume). */
336
340
  satVolumeEnsured = new Set();
341
+ /** ESPHome satellite id → the table address already written to its object (see markEsphomeSatellite). */
342
+ satEsphomeMarked = new Map();
337
343
  /** Native (ioBroker) satellite state-id → sender instance id, so we can push announcements back to it. */
338
344
  nativeSatFrom = new Map();
339
345
  /** Countdown timers / reminders (roadmap #2); mirrored into `timers.*` states. Null until onReady. */
@@ -588,6 +594,8 @@ class Assistant extends adapter_core_1.Adapter {
588
594
  async startEsphome(llmKey) {
589
595
  const cfg = this.config;
590
596
  const devices = (cfg.esphomeDevices || []).filter(d => d?.ip?.trim());
597
+ // Rows deleted from the table leave their satellite objects behind otherwise — forever offline in the list.
598
+ await this.removeStaleEsphomeSatellites(devices).catch(e => this.log.warn(`Could not clean up removed ESPHome satellites: ${e.message}`));
591
599
  if (!devices.length) {
592
600
  this.log.warn('ESPHome satellites are enabled, but no device is configured.');
593
601
  return;
@@ -643,9 +651,12 @@ class Assistant extends adapter_core_1.Adapter {
643
651
  mediaHost: (cfg.esphomeMediaHost || '').trim(),
644
652
  silenceMs: cfg.esphomeSilenceMs || 0,
645
653
  log: this.log,
646
- onStatus: (device, room, state) => {
647
- this.updateSatelliteState(device, room, state).catch(e => this.log.debug(`satellite state update failed: ${e.message}`));
654
+ onStatus: (device, room, state, address) => {
655
+ this.updateSatelliteState(device, room, state)
656
+ .then(() => this.markEsphomeSatellite(device, room, address))
657
+ .catch(e => this.log.debug(`satellite state update failed: ${e.message}`));
648
658
  },
659
+ encodeAudio: (pcm, sampleRate, target) => this.runFfmpegEncode(pcm, sampleRate, target),
649
660
  onWakeWords: (device, room, config) => {
650
661
  this.updateSatelliteWakeWords(device, room, config).catch(e => this.log.debug(`satellite wake word update failed: ${e.message}`));
651
662
  },
@@ -1100,6 +1111,93 @@ class Assistant extends adapter_core_1.Adapter {
1100
1111
  this.satDeviceById.set(id, device);
1101
1112
  return id;
1102
1113
  }
1114
+ /**
1115
+ * Note which table row an ESPHome satellite belongs to (`native.esphome` on `satellites.<id>`) and show its
1116
+ * address in the host column. That is what lets {@link removeStaleEsphomeSatellites} remove it once the row is
1117
+ * deleted — the id alone is the room or the device name and says nothing about the configuration.
1118
+ */
1119
+ async markEsphomeSatellite(device, room, address) {
1120
+ const id = await this.ensureSatelliteObjects(device, room);
1121
+ if (this.satEsphomeMarked.get(id) === address) {
1122
+ return;
1123
+ }
1124
+ this.satEsphomeMarked.set(id, address);
1125
+ const obj = await this.getObjectAsync(`satellites.${id}`);
1126
+ if (obj?.native?.esphome !== address) {
1127
+ await this.extendObjectAsync(`satellites.${id}`, { native: { esphome: address } });
1128
+ }
1129
+ await this.setStateAsync(`satellites.${id}.host`, { val: address, ack: true });
1130
+ }
1131
+ /**
1132
+ * Remove the objects of ESPHome satellites whose row was deleted from the table (or whose room changed, which
1133
+ * changes the id). Runs before the devices connect, so nothing is re-created meanwhile.
1134
+ *
1135
+ * A satellite marked by {@link markEsphomeSatellite} is matched by its address. One from an older version
1136
+ * carries no mark; it is recognised by `wakeWords` (only ESPHome satellites have it) and removed only when
1137
+ * every row has a room — otherwise a row without one could be it, under its device name.
1138
+ */
1139
+ async removeStaleEsphomeSatellites(devices) {
1140
+ const expected = new Map(devices.map(d => [(0, esphome_1.esphomeAddress)(d), d.room?.trim() ? this.satelliteStateId('', d.room) : null]));
1141
+ const allHaveRooms = [...expected.values()].every(id => id !== null);
1142
+ const roomIds = new Set([...expected.values()].filter((id) => !!id));
1143
+ const prefix = `${this.namespace}.satellites.`;
1144
+ const view = await this.getObjectViewAsync('system', 'device', {
1145
+ startkey: prefix,
1146
+ endkey: `${prefix}香`,
1147
+ });
1148
+ for (const row of view.rows) {
1149
+ const id = row.id.slice(prefix.length);
1150
+ if (!id || id.includes('.')) {
1151
+ continue;
1152
+ }
1153
+ const address = row.value?.native?.esphome;
1154
+ let reason = '';
1155
+ if (address) {
1156
+ if (!expected.has(address)) {
1157
+ reason = `${address} is no longer in the ESPHome satellites table`;
1158
+ }
1159
+ else {
1160
+ const want = expected.get(address);
1161
+ if (want && want !== id) {
1162
+ reason = `${address} is now in room ${want}`;
1163
+ }
1164
+ }
1165
+ }
1166
+ else if (allHaveRooms && !roomIds.has(id) && (await this.getObjectAsync(`satellites.${id}.wakeWords`))) {
1167
+ reason = 'no row of the ESPHome satellites table has this room any more';
1168
+ }
1169
+ if (reason) {
1170
+ this.log.info(`Satellite ${id} removed: ${reason}`);
1171
+ await this.forgetSatellite(id);
1172
+ }
1173
+ }
1174
+ }
1175
+ /** Delete a satellite's objects (Satellites tab). Refused while it is online: it would be re-created at once. */
1176
+ async deleteSatellite(id) {
1177
+ if (!id || /[^\w-]/.test(id)) {
1178
+ throw new Error(`invalid satellite id "${id}"`);
1179
+ }
1180
+ if (!(await this.getObjectAsync(`satellites.${id}`))) {
1181
+ throw new Error(`no satellite ${id}`);
1182
+ }
1183
+ const alive = await this.getStateAsync(`satellites.${id}.alive`);
1184
+ if (alive?.val === true) {
1185
+ throw new Error(`satellite ${id} is online`);
1186
+ }
1187
+ await this.forgetSatellite(id);
1188
+ this.log.info(`Satellite ${id} deleted`);
1189
+ }
1190
+ /** Drop the object tree of one satellite and everything cached about it. */
1191
+ async forgetSatellite(id) {
1192
+ await this.delObjectAsync(`satellites.${id}`, { recursive: true });
1193
+ this.satStatesEnsured.delete(id);
1194
+ this.satWakeWordStatesEnsured.delete(id);
1195
+ this.satVolumeEnsured.delete(id);
1196
+ this.satControlsReady.delete(id);
1197
+ this.satEsphomeMarked.delete(id);
1198
+ this.satDeviceById.delete(id);
1199
+ this.dndById.delete(id);
1200
+ }
1103
1201
  /**
1104
1202
  * Publish a satellite's wake-word configuration and let it be changed from ioBroker.
1105
1203
  *
@@ -1303,6 +1401,10 @@ class Assistant extends adapter_core_1.Adapter {
1303
1401
  native: {},
1304
1402
  });
1305
1403
  for (const entity of entities) {
1404
+ if (!isControlId(entity.objectId)) {
1405
+ this.log.debug(`Satellite ${device}: no usable id for "${entity.name}" (${entity.kind}) — skipped`);
1406
+ continue;
1407
+ }
1306
1408
  const id = `${base}.${entity.objectId}`;
1307
1409
  const name = entity.name || entity.objectId;
1308
1410
  if (entity.kind === 'mediaPlayer') {
@@ -1439,6 +1541,9 @@ class Assistant extends adapter_core_1.Adapter {
1439
1541
  }
1440
1542
  /** Write one entity's current value into its state(s). Always acked — this is the device talking. */
1441
1543
  async writeSatelliteControl(satId, entity) {
1544
+ if (!isControlId(entity.objectId)) {
1545
+ return; // never created (see buildSatelliteControls)
1546
+ }
1442
1547
  const base = `satellites.${satId}.controls.${entity.objectId}`;
1443
1548
  if (entity.kind === 'mediaPlayer') {
1444
1549
  const v = entity.value;
@@ -1904,7 +2009,35 @@ class Assistant extends adapter_core_1.Adapter {
1904
2009
  }
1905
2010
  });
1906
2011
  }
1907
- /** Invalidate the cached device/room/function listings when a room/function enum changes. */
2012
+ /**
2013
+ * Encode mono 16-bit PCM as MP3 or Opus (Ogg) via ffmpeg — for an ESPHome media player that was built with
2014
+ * nothing but that decoder. FLAC and WAV need no tool and are written in `replyFormat.ts`.
2015
+ */
2016
+ runFfmpegEncode(pcm, sampleRate, target) {
2017
+ return new Promise((resolve, reject) => {
2018
+ // prettier-ignore
2019
+ const input = ['-hide_banner', '-loglevel', 'error', '-f', 's16le', '-ar', String(sampleRate), '-ac', '1', '-i', 'pipe:0'];
2020
+ // prettier-ignore
2021
+ const output = target.codec === 'mp3'
2022
+ ? ['-c:a', 'libmp3lame', '-b:a', '128k', '-f', 'mp3']
2023
+ : ['-c:a', 'libopus', '-b:a', '64k', '-f', 'ogg'];
2024
+ // Opus runs at 48/24/16/12/8 kHz only; anything else would make libopus refuse.
2025
+ const rate = target.codec === 'opus' && ![48000, 24000, 16000, 12000, 8000].includes(target.sampleRate)
2026
+ ? 48000
2027
+ : target.sampleRate;
2028
+ const args = [...input, '-ar', String(rate), '-ac', String(target.channels), ...output, '-'];
2029
+ const proc = (0, node_child_process_1.spawn)('ffmpeg', args);
2030
+ const chunks = [];
2031
+ proc.stdout.on('data', (d) => chunks.push(d));
2032
+ proc.stderr.on('data', (d) => this.log.debug(`ffmpeg: ${String(d).trim()}`));
2033
+ proc.on('error', e => reject(new Error(`ffmpeg failed: ${e.message}`)));
2034
+ proc.on('close', code => code === 0 && chunks.length
2035
+ ? resolve(Buffer.concat(chunks))
2036
+ : reject(new Error(`ffmpeg exited with code ${code}`)));
2037
+ proc.stdin.on('error', () => { }); // ignore EPIPE if ffmpeg exits early
2038
+ proc.stdin.end(pcm);
2039
+ });
2040
+ }
1908
2041
  /** Vendor and key of the cloud LLM: speech of the same vendor (OpenAI, OpenRouter) reuses the key. */
1909
2042
  async speechLlmKey() {
1910
2043
  const provider = this.config.provider || 'openai';
@@ -2509,6 +2642,23 @@ class Assistant extends adapter_core_1.Adapter {
2509
2642
  }
2510
2643
  return;
2511
2644
  }
2645
+ // Satellites tab: forget a satellite that is gone. message = { id } (the state id under `satellites.`).
2646
+ if (obj.command === 'deleteSatellite') {
2647
+ const raw = obj.message?.id;
2648
+ const id = typeof raw === 'string' ? raw : '';
2649
+ let payload;
2650
+ try {
2651
+ await this.deleteSatellite(id);
2652
+ payload = { ok: true };
2653
+ }
2654
+ catch (e) {
2655
+ payload = { error: e.message };
2656
+ }
2657
+ if (obj.callback) {
2658
+ this.sendTo(obj.from, obj.command, payload, obj.callback);
2659
+ }
2660
+ return;
2661
+ }
2512
2662
  // Scripts: silence a ringing timer/alarm.
2513
2663
  if (obj.command === 'stopRinging') {
2514
2664
  const n = this.stopRinging();