audio_cpp 0.1.0

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.
@@ -0,0 +1,182 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "ffi"
4
+
5
+ module AudioCpp
6
+ # One task (asr, tts, diar, ...) in one mode on one backend, kept warm across
7
+ # runs. Create it from Model#session.
8
+ #
9
+ # A Session is not meant to be shared between threads: it carries state
10
+ # between calls (a stream in flight, prepared graphs). Its native calls take
11
+ # its Model's lock, so misuse serialises instead of corrupting memory, and
12
+ # sessions of one Model never run concurrently (see Model). Long calls
13
+ # release the GVL, so other Ruby threads keep running meanwhile.
14
+ class Session
15
+ attr_reader :model, :task, :mode, :backend, :threads
16
+
17
+ # @api private
18
+ def self.open(model, **settings)
19
+ session = new(model, **settings)
20
+ return session unless block_given?
21
+
22
+ begin
23
+ yield session
24
+ ensure
25
+ session.close
26
+ end
27
+ end
28
+
29
+ # @api private: use Model#session.
30
+ def initialize(model, task:, mode:, backend:, device:, threads:, impl:, options:)
31
+ @model = model
32
+ @task = AudioCpp.validate_task(task)
33
+ @mode = mode
34
+ @backend = backend
35
+ @threads = threads
36
+ pointer = model.synchronize { create(model, device, impl, options) }
37
+ @handle = Handle.new(pointer, Native.method(:audiocpp_session_free))
38
+ end
39
+
40
+ def family
41
+ synchronize { Native.utf8(Native.audiocpp_session_family(pointer)) }
42
+ end
43
+
44
+ # Runs one request and returns a Result. The building blocks of the
45
+ # task-specific helpers below:
46
+ #
47
+ # - `audio:` a WAV path, an Audio or an Array of 16 kHz mono samples
48
+ # - `text:` and `language:` the text to speak and its language; for audio
49
+ # input `language:` alone is the language hint (audiocpp_cli --language)
50
+ # - `voice:` a built-in voice or a cached voice id (--voice-id)
51
+ # - `options:` request options (--request-option); Array values are sent as
52
+ # list options
53
+ def run(audio: nil, text: nil, language: nil, voice: nil, options: {})
54
+ input = audio && Audio.coerce(audio)
55
+ synchronize do
56
+ Request.open(audio: input, text: text, language: language, voice: voice, options: options) do |request|
57
+ out = FFI::MemoryPointer.new(:pointer)
58
+ status = Native.audiocpp_session_run(pointer, request, out)
59
+ result = out.read_pointer
60
+ begin
61
+ Native.check!(status, "audiocpp_session_run")
62
+ Result.read(result, sample_rate: input&.sample_rate)
63
+ ensure
64
+ Native.audiocpp_result_free(result)
65
+ end
66
+ end
67
+ end
68
+ end
69
+
70
+ # Speech to text. `input` is a WAV path, an Audio or an Array of 16 kHz
71
+ # mono samples. `timestamps: true` asks for words with sample positions.
72
+ # Audio goes to the engine at its own rate (models resample it with
73
+ # their own filter); positions are in samples of that rate, and the
74
+ # *_seconds readers account for it.
75
+ def transcribe(input, language: nil, timestamps: false, options: {})
76
+ options = options.merge("return_timestamps" => "true") if timestamps
77
+ run(audio: input, language: language, options: options)
78
+ end
79
+
80
+ # Who spoke when. The Result carries #speaker_turns. Diarization models
81
+ # take mono 16 kHz, so other input is converted first (Audio#to_asr_input,
82
+ # linear resampling); positions are then in 16 kHz samples.
83
+ def diarize(input, options: {})
84
+ run(audio: Audio.coerce(input).to_asr_input, options: options)
85
+ end
86
+
87
+ # Text to speech; returns the Audio. Raises NotAvailableError if the task
88
+ # produced none.
89
+ def synthesize(text, voice: nil, language: nil, options: {})
90
+ result = run(text: text, voice: voice, language: language, options: options)
91
+ result.audio or raise NotAvailableError, "#{family} returned no audio"
92
+ end
93
+
94
+ # Opens a stream (a session created with mode: "streaming"). Request
95
+ # options apply to the whole stream.
96
+ #
97
+ # With a block, yields the Stream and resets the session afterwards
98
+ # unless the block called Stream#finish; returns the block's value.
99
+ #
100
+ # session.stream do |s|
101
+ # audio.each_chunk(s.chunk_frames) { |chunk| s.push(chunk) }
102
+ # s.each_event { |e| print e.text }
103
+ # s.finish.text
104
+ # end
105
+ def stream(language: nil, timestamps: false, options: {})
106
+ options = options.merge("return_timestamps" => "true") if timestamps
107
+ stream = Stream.new(self, language: language, options: options)
108
+ return stream unless block_given?
109
+
110
+ begin
111
+ yield stream
112
+ ensure
113
+ stream.cancel unless stream.finished?
114
+ end
115
+ end
116
+
117
+ # Streams a whole recording through the session in the model's preferred
118
+ # chunks, yielding every Event, and returns the final Result. Without a
119
+ # block returns an Enumerator over the events (whose #each returns the
120
+ # final Result).
121
+ def stream_audio(input, chunk_frames: nil, language: nil, timestamps: false, options: {}, &block)
122
+ unless block
123
+ return enum_for(:stream_audio, input, chunk_frames: chunk_frames, language: language,
124
+ timestamps: timestamps, options: options)
125
+ end
126
+
127
+ audio = Audio.coerce(input)
128
+ stream(language: language, timestamps: timestamps, options: options) do |s|
129
+ audio.each_chunk(chunk_frames || s.chunk_frames(audio.sample_rate)) do |chunk|
130
+ s.push(chunk)
131
+ s.each_event(&block)
132
+ end
133
+ s.finish
134
+ end
135
+ end
136
+
137
+ # Frees the session. Safe to call twice.
138
+ def close
139
+ synchronize { @handle.close }
140
+ end
141
+
142
+ def closed?
143
+ @handle.closed?
144
+ end
145
+
146
+ def inspect
147
+ return "#<#{self.class.name} closed>" if closed?
148
+
149
+ "#<#{self.class.name} #{family} #{task}/#{mode} #{backend}>"
150
+ end
151
+
152
+ # @api private
153
+ def pointer
154
+ @handle.pointer
155
+ end
156
+
157
+ # @api private: serialises native calls (the Model's lock).
158
+ def synchronize(&block)
159
+ model.synchronize(&block)
160
+ end
161
+
162
+ private
163
+
164
+ def create(model, device, impl, options)
165
+ backend_name = FFI::MemoryPointer.from_string(backend)
166
+ config = Native::BackendConfig.new
167
+ config[:backend] = backend_name
168
+ config[:device] = device
169
+ config[:threads] = threads
170
+ out = FFI::MemoryPointer.new(:pointer)
171
+ Options.open(options) do |options_pointer|
172
+ status = if impl
173
+ Native.audiocpp_session_create_with_impl(model.pointer, task, mode, config, impl.to_s, options_pointer, out)
174
+ else
175
+ Native.audiocpp_session_create(model.pointer, task, mode, config, options_pointer, out)
176
+ end
177
+ Native.check!(status, "audiocpp_session_create #{task}/#{mode} on #{backend}")
178
+ end
179
+ out.read_pointer
180
+ end
181
+ end
182
+ end
@@ -0,0 +1,60 @@
1
+ # frozen_string_literal: true
2
+
3
+ module AudioCpp
4
+ # Joins a transcript with a diarization of the same audio: every word goes to
5
+ # the speaker whose turn overlaps it most (or the nearest turn within
6
+ # `max_gap` seconds), and consecutive words of one speaker form an Utterance.
7
+ #
8
+ # words = asr.transcribe(audio, timestamps: true).words
9
+ # turns = diar.diarize(audio).speaker_turns
10
+ # AudioCpp::Speakers.assign(words, turns).each { |u| puts "#{u.speaker}: #{u.text}" }
11
+ module Speakers
12
+ Utterance = Struct.new(:speaker, :words, keyword_init: true) do
13
+ def text
14
+ words.map(&:text).join(" ")
15
+ end
16
+
17
+ def start_seconds
18
+ words.first.start_seconds
19
+ end
20
+
21
+ def end_seconds
22
+ words.last.end_seconds
23
+ end
24
+ end
25
+
26
+ module_function
27
+
28
+ # Returns Utterances in word order; words no turn explains get speaker nil.
29
+ def assign(words, turns, max_gap: 1.0)
30
+ utterances = []
31
+ words.each do |word|
32
+ speaker = speaker_for(word, turns, max_gap)
33
+ if !utterances.empty? && utterances.last.speaker == speaker
34
+ utterances.last.words << word
35
+ else
36
+ utterances << Utterance.new(speaker: speaker, words: [word])
37
+ end
38
+ end
39
+ utterances
40
+ end
41
+
42
+ def speaker_for(word, turns, max_gap)
43
+ best = turns.max_by { |turn| overlap(word, turn) }
44
+ return best.speaker if best && overlap(word, best).positive?
45
+
46
+ nearest = turns.min_by { |turn| gap(word, turn) }
47
+ nearest.speaker if nearest && gap(word, nearest) <= max_gap
48
+ end
49
+
50
+ def overlap(word, turn)
51
+ [word.end_seconds, turn.end_seconds].min - [word.start_seconds, turn.start_seconds].max
52
+ end
53
+
54
+ def gap(word, turn)
55
+ [turn.start_seconds - word.end_seconds, word.start_seconds - turn.end_seconds, 0].max
56
+ end
57
+
58
+ private_class_method :speaker_for, :overlap, :gap
59
+ end
60
+ end
@@ -0,0 +1,154 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "ffi"
4
+
5
+ module AudioCpp
6
+ # A pull-based stream on a streaming Session: push audio, read the events it
7
+ # produced, finish for the complete Result. Get one from Session#stream.
8
+ #
9
+ # Events carry what is new since the previous one (for ASR, the newly
10
+ # decoded text). Text a model decodes only at the end of the stream comes in
11
+ # the Result of #finish, not as an event, so take the final transcript from
12
+ # there.
13
+ class Stream
14
+ def initialize(session, language: nil, options: {})
15
+ @session = session
16
+ @pending = []
17
+ @position = 0
18
+ @sample_rate = nil
19
+ @finished = false
20
+ session.synchronize do
21
+ Request.open(language: language, options: options) do |request|
22
+ Native.check!(Native.audiocpp_stream_start(session.pointer, request), "audiocpp_stream_start")
23
+ end
24
+ end
25
+ end
26
+
27
+ # :audio_chunks for streams fed with audio, :none for text-driven ones.
28
+ def input_kind
29
+ policy[:input]
30
+ end
31
+
32
+ # The chunk size the model prefers, in frames at `sample_rate`. Push this
33
+ # much per call where you can.
34
+ def chunk_frames(sample_rate = Audio::ASR_SAMPLE_RATE)
35
+ seconds = policy[:seconds]
36
+ return (seconds * sample_rate).round if seconds.positive?
37
+
38
+ policy[:samples].positive? ? policy[:samples] : (sample_rate * 0.16).round
39
+ end
40
+
41
+ # Feeds one chunk: an Audio, or an Array of mono samples at `sample_rate`.
42
+ # The events it produced are queued for #each_event. Returns self.
43
+ def push(chunk, sample_rate: Audio::ASR_SAMPLE_RATE)
44
+ raise Error, "stream already finished" if finished?
45
+
46
+ audio = chunk.is_a?(Audio) ? chunk : Audio.new(chunk, sample_rate: sample_rate)
47
+ @sample_rate ||= audio.sample_rate
48
+ buffer = Request.float_buffer(audio.samples)
49
+ out = FFI::MemoryPointer.new(:pointer)
50
+ @session.synchronize do
51
+ status = Native.audiocpp_stream_push(@session.pointer, buffer, audio.frames, audio.sample_rate,
52
+ audio.channels, @position, out)
53
+ Native.check!(status, "audiocpp_stream_push")
54
+ end
55
+ # Interleaved sample count, as audiocpp_cli counts start_sample.
56
+ @position += audio.samples.size
57
+ take_event(out.read_pointer)
58
+ self
59
+ end
60
+
61
+ # Yields every event produced so far (queued by #push, then the ones the
62
+ # model queued itself) and forgets them. Returns an Enumerator without a
63
+ # block.
64
+ def each_event
65
+ return enum_for(:each_event) unless block_given?
66
+
67
+ drain_queue
68
+ yield @pending.shift until @pending.empty?
69
+ self
70
+ end
71
+
72
+ # The events produced so far, as an Array.
73
+ def events
74
+ each_event.to_a
75
+ end
76
+
77
+ # Ends the stream and returns the complete Result. The session is ready for
78
+ # a new stream afterwards.
79
+ def finish
80
+ raise Error, "stream already finished" if finished?
81
+
82
+ @session.synchronize do
83
+ out = FFI::MemoryPointer.new(:pointer)
84
+ status = Native.audiocpp_stream_finish(@session.pointer, out)
85
+ result = out.read_pointer
86
+ begin
87
+ Native.check!(status, "audiocpp_stream_finish")
88
+ Result.read(result, sample_rate: @sample_rate)
89
+ ensure
90
+ Native.audiocpp_result_free(result)
91
+ @finished = true
92
+ Native.audiocpp_stream_reset(@session.pointer)
93
+ end
94
+ end
95
+ end
96
+
97
+ # Drops the stream without decoding its tail.
98
+ def cancel
99
+ return if finished?
100
+
101
+ @finished = true
102
+ @session.synchronize { Native.audiocpp_stream_reset(@session.pointer) } unless @session.closed?
103
+ nil
104
+ end
105
+
106
+ def finished?
107
+ @finished
108
+ end
109
+
110
+ private
111
+
112
+ def policy
113
+ @policy ||= @session.synchronize do
114
+ input = FFI::MemoryPointer.new(:int)
115
+ samples = FFI::MemoryPointer.new(:int64)
116
+ seconds = FFI::MemoryPointer.new(:double)
117
+ Native.check!(Native.audiocpp_stream_policy(@session.pointer, input, nil, samples, seconds),
118
+ "audiocpp_stream_policy")
119
+ {input: Native::StreamInputKind[input.read_int], samples: samples.read_int64, seconds: seconds.read_double}
120
+ end
121
+ end
122
+
123
+ def drain_queue
124
+ out = FFI::MemoryPointer.new(:pointer)
125
+ loop do
126
+ @session.synchronize do
127
+ Native.check!(Native.audiocpp_stream_next_event(@session.pointer, out), "audiocpp_stream_next_event")
128
+ end
129
+ event = out.read_pointer
130
+ break if event.null?
131
+
132
+ take_event(event)
133
+ end
134
+ end
135
+
136
+ def take_event(pointer)
137
+ return if pointer.null?
138
+
139
+ begin
140
+ event = Event.read(pointer, sample_rate: @sample_rate)
141
+ ensure
142
+ Native.audiocpp_event_free(pointer)
143
+ end
144
+ @pending << event unless empty_event?(event)
145
+ end
146
+
147
+ # A push that produced nothing still returns an event; keep only real ones.
148
+ def empty_event?(event)
149
+ (event.text.nil? || event.text.empty?) && !event.final? && event.voice_activity.empty? && event.words.empty? &&
150
+ event.segments.empty? && event.speaker_turns.empty? && event.audio.nil? && event.named_audio.empty? &&
151
+ event.artifacts.empty?
152
+ end
153
+ end
154
+ end
@@ -0,0 +1,10 @@
1
+ # frozen_string_literal: true
2
+
3
+ module AudioCpp
4
+ VERSION = "0.1.0"
5
+
6
+ # The C ABI these bindings were written against (include/audiocpp.h).
7
+ # A library with another major, or an older minor, is refused at load time.
8
+ ABI_MAJOR = 0
9
+ ABI_MINOR = 4
10
+ end
@@ -0,0 +1,110 @@
1
+ # frozen_string_literal: true
2
+
3
+ module AudioCpp
4
+ # Minimal RIFF/WAVE reader and writer: 16-bit PCM and 32-bit IEEE float,
5
+ # any channel count. Other encodings raise UnsupportedFormatError; convert
6
+ # them with ffmpeg outside the gem.
7
+ module WAV
8
+ PCM = 1
9
+ IEEE_FLOAT = 3
10
+ EXTENSIBLE = 0xFFFE
11
+ PCM16_SCALE = 32_768.0
12
+
13
+ module_function
14
+
15
+ def read(path)
16
+ parse(File.binread(path), source: path)
17
+ end
18
+
19
+ # Parses WAV bytes (a binary String).
20
+ def parse(bytes, source: "WAV data")
21
+ bytes = bytes.b
22
+ unless bytes.byteslice(0, 4) == "RIFF" && bytes.byteslice(8, 4) == "WAVE"
23
+ raise UnsupportedFormatError, "#{source} is not a RIFF/WAVE file"
24
+ end
25
+
26
+ format = nil
27
+ data = nil
28
+ offset = 12
29
+ while offset + 8 <= bytes.bytesize
30
+ id = bytes.byteslice(offset, 4)
31
+ size = bytes.byteslice(offset + 4, 4).unpack1("V")
32
+ body_start = offset + 8
33
+ # Streamed WAVs (ffmpeg to a pipe) leave the data size at 0 or 0xFFFFFFFF.
34
+ size = bytes.bytesize - body_start if id == "data" && (size.zero? || body_start + size > bytes.bytesize)
35
+ body = bytes.byteslice(body_start, size)
36
+ case id
37
+ when "fmt " then format = parse_format(body, source)
38
+ when "data" then data = body
39
+ end
40
+ offset = body_start + size + (size & 1)
41
+ end
42
+ raise UnsupportedFormatError, "#{source} has no fmt chunk" unless format
43
+ raise UnsupportedFormatError, "#{source} has no data chunk" unless data
44
+
45
+ Audio.new(decode(data, format), sample_rate: format[:sample_rate], channels: format[:channels])
46
+ end
47
+
48
+ # Writes `audio` as 16-bit PCM (`format: :pcm16`) or 32-bit float (`:float32`).
49
+ def write(path, audio, format: :pcm16)
50
+ File.binwrite(path, encode(audio, format: format))
51
+ path
52
+ end
53
+
54
+ # The WAV file as a binary String.
55
+ def encode(audio, format: :pcm16)
56
+ case format
57
+ when :pcm16
58
+ data = audio.samples.map { |s| (s * PCM16_SCALE).round.clamp(-32_768, 32_767) }.pack("s<*")
59
+ header(audio, PCM, 16, data.bytesize) + data
60
+ when :float32
61
+ data = audio.samples.pack("e*")
62
+ header(audio, IEEE_FLOAT, 32, data.bytesize) + data
63
+ else
64
+ raise ArgumentError, "format must be :pcm16 or :float32, got #{format.inspect}"
65
+ end
66
+ end
67
+
68
+ def parse_format(body, source)
69
+ raise UnsupportedFormatError, "#{source} has a truncated fmt chunk" if body.nil? || body.bytesize < 16
70
+
71
+ tag, channels, sample_rate, _byte_rate, _block_align, bits = body.unpack("vvVVvv")
72
+ tag = body.byteslice(24, 2).unpack1("v") if tag == EXTENSIBLE && body.bytesize >= 26
73
+ supported = (tag == PCM && bits == 16) || (tag == IEEE_FLOAT && bits == 32)
74
+ unless supported
75
+ raise UnsupportedFormatError,
76
+ "#{source}: only 16-bit PCM and 32-bit float WAV are read (format #{tag}, #{bits} bits); " \
77
+ "convert with `ffmpeg -i input -c:a pcm_s16le output.wav`"
78
+ end
79
+ raise UnsupportedFormatError, "#{source} declares no channels" if channels.zero?
80
+
81
+ {tag: tag, channels: channels, sample_rate: sample_rate}
82
+ end
83
+
84
+ def decode(data, format)
85
+ if format[:tag] == PCM
86
+ usable = data.bytesize - (data.bytesize % (2 * format[:channels]))
87
+ data.byteslice(0, usable).unpack("s<*").map { |v| v / PCM16_SCALE }
88
+ else
89
+ usable = data.bytesize - (data.bytesize % (4 * format[:channels]))
90
+ data.byteslice(0, usable).unpack("e*")
91
+ end
92
+ end
93
+
94
+ def header(audio, tag, bits, data_bytes)
95
+ block_align = audio.channels * bits / 8
96
+ fmt = [tag, audio.channels, audio.sample_rate, audio.sample_rate * block_align, block_align, bits].pack("vvVVvv")
97
+ chunks = +""
98
+ if tag == IEEE_FLOAT
99
+ # Non-PCM formats carry cbSize and a fact chunk with the frame count.
100
+ fmt << [0].pack("v")
101
+ chunks << "fact" << [4, audio.frames].pack("VV")
102
+ end
103
+ riff_size = 4 + (8 + fmt.bytesize) + chunks.bytesize + 8 + data_bytes
104
+ "RIFF".b + [riff_size].pack("V") + "WAVE" + "fmt " + [fmt.bytesize].pack("V") + fmt + chunks + "data" +
105
+ [data_bytes].pack("V")
106
+ end
107
+
108
+ private_class_method :parse_format, :decode, :header
109
+ end
110
+ end
data/lib/audio_cpp.rb ADDED
@@ -0,0 +1,113 @@
1
+ # frozen_string_literal: true
2
+
3
+ require_relative "audio_cpp/version"
4
+ require_relative "audio_cpp/errors"
5
+ require_relative "audio_cpp/library_path"
6
+ require_relative "audio_cpp/native"
7
+ require_relative "audio_cpp/handle"
8
+ require_relative "audio_cpp/audio"
9
+ require_relative "audio_cpp/resampler"
10
+ require_relative "audio_cpp/wav"
11
+ require_relative "audio_cpp/registry"
12
+ require_relative "audio_cpp/request"
13
+ require_relative "audio_cpp/result"
14
+ require_relative "audio_cpp/model"
15
+ require_relative "audio_cpp/session"
16
+ require_relative "audio_cpp/stream"
17
+ require_relative "audio_cpp/speakers"
18
+ require_relative "audio_cpp/models"
19
+
20
+ # Ruby bindings to audio.cpp's C API (include/audiocpp.h): speech recognition,
21
+ # diarization, text to speech and more, in-process.
22
+ module AudioCpp
23
+ LOG_LEVELS = %i[debug info warn error].freeze
24
+
25
+ class << self
26
+ # audio.cpp's own build version, e.g. "0.9.7".
27
+ def version
28
+ Native.utf8(Native.audiocpp_build_version)
29
+ end
30
+
31
+ # The library's C ABI version as "major.minor.patch".
32
+ def abi_version
33
+ packed = Native.audiocpp_abi_version
34
+ [packed >> 16, (packed >> 8) & 0xff, packed & 0xff].join(".")
35
+ end
36
+
37
+ # Model families compiled into the library ("gigaam_asr", "kokoro_tts", ...).
38
+ def families
39
+ @families ||= Registry.families.freeze
40
+ end
41
+
42
+ # Task tokens the library knows ("asr", "tts", "diar", ...).
43
+ def tasks
44
+ @tasks ||= Array.new(Native.audiocpp_task_count) { |index| Native.utf8(Native.audiocpp_task_name(index)) }.freeze
45
+ end
46
+
47
+ # The library's token for a model-spec task name ("music" -> "gen"), or nil.
48
+ def task_from_spec_name(name)
49
+ Native.utf8(Native.audiocpp_task_from_spec_name(name.to_s))
50
+ end
51
+
52
+ # @api private
53
+ def validate_task(task)
54
+ task = task.to_s
55
+ return task if tasks.include?(task)
56
+
57
+ raise ArgumentError, "unknown task #{task.inspect}; this library knows #{tasks.join(", ")}"
58
+ end
59
+
60
+ # Where the library was loaded from.
61
+ def library_path
62
+ Native::LIBRARY
63
+ end
64
+
65
+ # How the gem built the library ({"commit" => ..., "models" => ...}), read
66
+ # from BUILD_INFO next to it; nil for a library from elsewhere.
67
+ def build_info
68
+ path = File.join(File.dirname(library_path), "BUILD_INFO")
69
+ return nil unless File.file?(path)
70
+
71
+ File.readlines(path, chomp: true).to_h { |line| line.split("=", 2) }
72
+ end
73
+
74
+ # The Silero VAD weights installed next to the library by the gem build,
75
+ # or nil. Some families take it as an option, e.g.
76
+ # `"gigaam_asr.vad_model_path" => AudioCpp.silero_vad_path`.
77
+ def silero_vad_path
78
+ path = File.join(File.dirname(library_path), "assets", "framework", "models", "silero_vad",
79
+ "silero_vad_16k.safetensors")
80
+ File.file?(path) ? path : nil
81
+ end
82
+
83
+ # Routes the engine's log lines (normally printed to stderr) to the block,
84
+ # as `level, message` with level one of :debug, :info, :warn, :error.
85
+ # Lines below `level:` are dropped. `on_log` without a block restores stderr.
86
+ #
87
+ # The block may run on a thread the engine owns; keep it short and do not
88
+ # call back into AudioCpp from it.
89
+ def on_log(level: :warn, &block)
90
+ raise ArgumentError, "level must be one of #{LOG_LEVELS.join(", ")}" unless LOG_LEVELS.include?(level)
91
+
92
+ @log_callback = block && log_callback(LOG_LEVELS.index(level), block)
93
+ Native.audiocpp_log_set(@log_callback, nil)
94
+ nil
95
+ end
96
+
97
+ # Drops every engine log line.
98
+ def silence_logs
99
+ on_log(level: :error) {}
100
+ end
101
+
102
+ private
103
+
104
+ def log_callback(minimum, block)
105
+ passing = false
106
+ proc do |level, text|
107
+ # :cont continues the previous line and follows its fate.
108
+ passing = LOG_LEVELS.index(level).to_i >= minimum unless level == :cont
109
+ block.call(level, Native.utf8(text)) if passing && level != :none
110
+ end
111
+ end
112
+ end
113
+ end