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,263 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "ffi"
4
+
5
+ module AudioCpp
6
+ # Raw bindings to include/audiocpp.h, one attach_function per entry point,
7
+ # with the header's enums and structs. Nothing here frees anything for you;
8
+ # the classes in AudioCpp (Model, Session, ...) do that.
9
+ #
10
+ # Calls that can run for a long time (loading, running, streaming) are
11
+ # attached with `blocking: true`, so they release the GVL and other Ruby
12
+ # threads keep running meanwhile.
13
+ module Native
14
+ extend FFI::Library
15
+
16
+ LIBRARY = LibraryPath.resolve
17
+ begin
18
+ ffi_lib LIBRARY
19
+ rescue LoadError => e
20
+ raise LibraryError, <<~MSG.chomp
21
+ could not load libaudiocpp (tried #{LIBRARY}): #{e.message}
22
+ Reinstall the gem so it builds the library, or set AUDIOCPP_LIB to a libaudiocpp built with -DAUDIOCPP_BUILD_C_API=ON.
23
+ MSG
24
+ end
25
+
26
+ # ---- Versioning -------------------------------------------------------
27
+
28
+ attach_function :audiocpp_abi_version, [], :uint32
29
+
30
+ # Raises AbiMismatchError unless the loaded library has this gem's ABI
31
+ # major and at least its minor (docs/c_api.md, "Versioning").
32
+ def self.check_abi!(version = audiocpp_abi_version)
33
+ major = version >> 16
34
+ minor = (version >> 8) & 0xff
35
+ return version if major == ABI_MAJOR && minor >= ABI_MINOR
36
+
37
+ raise AbiMismatchError,
38
+ "#{LIBRARY} has C ABI #{major}.#{minor}.#{version & 0xff}; " \
39
+ "audio_cpp #{VERSION} needs #{ABI_MAJOR}.#{ABI_MINOR} or a later #{ABI_MAJOR}.x"
40
+ end
41
+ check_abi!
42
+
43
+ attach_function :audiocpp_build_version, [], :string
44
+
45
+ # ---- Status and errors ------------------------------------------------
46
+
47
+ Status = enum(:audiocpp_status, [
48
+ :ok, 0,
49
+ :invalid_argument, 1,
50
+ :unsupported_family, 2,
51
+ :load_failed, 3,
52
+ :runtime, 4,
53
+ :out_of_memory, 5,
54
+ :out_of_range, 6,
55
+ :not_available, 7
56
+ ])
57
+
58
+ attach_function :audiocpp_last_error, [], :string
59
+ attach_function :audiocpp_status_string, [:audiocpp_status], :string
60
+
61
+ # ---- Logging ----------------------------------------------------------
62
+
63
+ LogLevel = enum(:audiocpp_log_level, [
64
+ :none, 0,
65
+ :debug, 1,
66
+ :info, 2,
67
+ :warn, 3,
68
+ :error, 4,
69
+ :cont, 5
70
+ ])
71
+
72
+ callback :audiocpp_log_callback, [:audiocpp_log_level, :string, :pointer], :void
73
+ attach_function :audiocpp_log_set, [:audiocpp_log_callback, :pointer], :void
74
+
75
+ # ---- Options ----------------------------------------------------------
76
+
77
+ attach_function :audiocpp_options_create, [], :pointer
78
+ attach_function :audiocpp_options_set, [:pointer, :string, :string], :audiocpp_status
79
+ attach_function :audiocpp_options_free, [:pointer], :void
80
+
81
+ # ---- Registry ---------------------------------------------------------
82
+
83
+ attach_function :audiocpp_registry_create, [:string, :pointer], :audiocpp_status, blocking: true
84
+ attach_function :audiocpp_registry_free, [:pointer], :void
85
+ attach_function :audiocpp_registry_family_count, [:pointer], :size_t
86
+ attach_function :audiocpp_registry_family, [:pointer, :size_t, :pointer], :audiocpp_status
87
+
88
+ # ---- Task vocabulary --------------------------------------------------
89
+
90
+ attach_function :audiocpp_task_count, [], :size_t
91
+ attach_function :audiocpp_task_name, [:size_t], :string
92
+ attach_function :audiocpp_task_from_spec_name, [:string], :string
93
+
94
+ # ---- Model ------------------------------------------------------------
95
+
96
+ class ModelConfig < FFI::Struct
97
+ layout :family_hint, :pointer,
98
+ :config_id, :pointer,
99
+ :weight_id, :pointer,
100
+ :model_spec_override, :pointer
101
+ end
102
+
103
+ attach_function :audiocpp_model_load,
104
+ [:pointer, :string, ModelConfig.by_ref, :pointer, :pointer], :audiocpp_status, blocking: true
105
+ attach_function :audiocpp_model_free, [:pointer], :void
106
+ attach_function :audiocpp_model_family, [:pointer], :string
107
+ attach_function :audiocpp_model_description, [:pointer], :string
108
+ attach_function :audiocpp_model_supports, [:pointer, :string, :string], :int
109
+ attach_function :audiocpp_model_supports_timestamps, [:pointer], :int
110
+ attach_function :audiocpp_model_supports_speaker_reference, [:pointer], :int
111
+ attach_function :audiocpp_model_supports_style_condition, [:pointer], :int
112
+ attach_function :audiocpp_model_language_count, [:pointer], :size_t
113
+ attach_function :audiocpp_model_language, [:pointer, :size_t, :pointer], :audiocpp_status
114
+
115
+ OptionScope = enum(:audiocpp_option_scope, [
116
+ :request, 0,
117
+ :session, 1,
118
+ :load, 2
119
+ ])
120
+
121
+ attach_function :audiocpp_model_option_count, [:pointer, :audiocpp_option_scope], :size_t
122
+ attach_function :audiocpp_model_option,
123
+ [:pointer, :audiocpp_option_scope, :size_t, :pointer, :pointer, :pointer, :pointer, :pointer, :pointer, :pointer],
124
+ :audiocpp_status
125
+
126
+ # ---- Session ----------------------------------------------------------
127
+
128
+ class BackendConfig < FFI::Struct
129
+ layout :backend, :pointer,
130
+ :device, :int,
131
+ :threads, :int
132
+ end
133
+
134
+ attach_function :audiocpp_session_create,
135
+ [:pointer, :string, :string, BackendConfig.by_ref, :pointer, :pointer], :audiocpp_status, blocking: true
136
+ attach_function :audiocpp_session_create_with_impl,
137
+ [:pointer, :string, :string, BackendConfig.by_ref, :string, :pointer, :pointer], :audiocpp_status, blocking: true
138
+ attach_function :audiocpp_session_free, [:pointer], :void
139
+ attach_function :audiocpp_session_family, [:pointer], :string
140
+ attach_function :audiocpp_session_prepare, [:pointer, :pointer], :audiocpp_status, blocking: true
141
+ attach_function :audiocpp_session_run, [:pointer, :pointer, :pointer], :audiocpp_status, blocking: true
142
+
143
+ # ---- Request ----------------------------------------------------------
144
+
145
+ attach_function :audiocpp_request_create, [], :pointer
146
+ attach_function :audiocpp_request_free, [:pointer], :void
147
+ attach_function :audiocpp_request_set_text, [:pointer, :string, :string], :audiocpp_status
148
+ attach_function :audiocpp_request_set_text_language, [:pointer, :string], :audiocpp_status
149
+ attach_function :audiocpp_request_set_audio, [:pointer, :pointer, :size_t, :int, :int], :audiocpp_status
150
+ attach_function :audiocpp_request_set_voice_audio, [:pointer, :pointer, :size_t, :int, :int], :audiocpp_status
151
+ attach_function :audiocpp_request_set_voice_id, [:pointer, :string], :audiocpp_status
152
+ attach_function :audiocpp_request_set_style_language, [:pointer, :string], :audiocpp_status
153
+ attach_function :audiocpp_request_set_emotion, [:pointer, :string], :audiocpp_status
154
+ attach_function :audiocpp_request_set_speaking_rate, [:pointer, :float], :audiocpp_status
155
+ attach_function :audiocpp_request_set_pitch_shift, [:pointer, :float], :audiocpp_status
156
+ attach_function :audiocpp_request_set_energy_scale, [:pointer, :float], :audiocpp_status
157
+ attach_function :audiocpp_request_set_style_tag, [:pointer, :string, :string], :audiocpp_status
158
+
159
+ ArtifactKind = enum(:audiocpp_artifact_kind, [
160
+ :speaker_embedding, 0,
161
+ :style_embedding, 1,
162
+ :prompt_embedding, 2,
163
+ :acoustic_tokens, 3,
164
+ :midi, 4,
165
+ :transcript_alignment, 5,
166
+ :diarization_state, 6,
167
+ :vad_state, 7,
168
+ :custom, 8
169
+ ])
170
+
171
+ attach_function :audiocpp_request_add_artifact,
172
+ [:pointer, :audiocpp_artifact_kind, :string, :pointer, :size_t, :pointer], :audiocpp_status
173
+ attach_function :audiocpp_request_set_artifact_meta, [:pointer, :size_t, :string, :string], :audiocpp_status
174
+ attach_function :audiocpp_request_set_option, [:pointer, :string, :string], :audiocpp_status
175
+ attach_function :audiocpp_request_set_option_array, [:pointer, :string, :pointer, :size_t], :audiocpp_status
176
+
177
+ # ---- Result -----------------------------------------------------------
178
+
179
+ attach_function :audiocpp_result_free, [:pointer], :void
180
+ attach_function :audiocpp_result_audio, [:pointer, :pointer, :pointer, :pointer, :pointer], :audiocpp_status
181
+ attach_function :audiocpp_result_text, [:pointer, :pointer, :pointer], :audiocpp_status
182
+ attach_function :audiocpp_result_custom_schema, [:pointer, :pointer, :pointer], :audiocpp_status
183
+ attach_function :audiocpp_result_segment_count, [:pointer], :size_t
184
+ attach_function :audiocpp_result_segment,
185
+ [:pointer, :size_t, :pointer, :pointer, :pointer, :pointer], :audiocpp_status
186
+ attach_function :audiocpp_result_speaker_turn_count, [:pointer], :size_t
187
+ attach_function :audiocpp_result_speaker_turn,
188
+ [:pointer, :size_t, :pointer, :pointer, :pointer, :pointer, :pointer], :audiocpp_status
189
+ attach_function :audiocpp_result_word_count, [:pointer], :size_t
190
+ attach_function :audiocpp_result_word,
191
+ [:pointer, :size_t, :pointer, :pointer, :pointer, :pointer], :audiocpp_status
192
+ attach_function :audiocpp_result_named_audio_count, [:pointer], :size_t
193
+ attach_function :audiocpp_result_named_audio,
194
+ [:pointer, :size_t, :pointer, :pointer, :pointer, :pointer, :pointer], :audiocpp_status
195
+ attach_function :audiocpp_result_artifact_count, [:pointer], :size_t
196
+ attach_function :audiocpp_result_artifact,
197
+ [:pointer, :size_t, :pointer, :pointer, :pointer, :pointer], :audiocpp_status
198
+ attach_function :audiocpp_result_artifact_meta_count, [:pointer, :size_t], :size_t
199
+ attach_function :audiocpp_result_artifact_meta,
200
+ [:pointer, :size_t, :size_t, :pointer, :pointer], :audiocpp_status
201
+
202
+ # ---- Streaming --------------------------------------------------------
203
+
204
+ StreamInputKind = enum(:audiocpp_stream_input_kind, [
205
+ :none, 0,
206
+ :audio_chunks, 1
207
+ ])
208
+
209
+ StreamOutputKind = enum(:audiocpp_stream_output_kind, [
210
+ :final_result, 0,
211
+ :pull_events, 1
212
+ ])
213
+
214
+ attach_function :audiocpp_stream_policy, [:pointer, :pointer, :pointer, :pointer, :pointer], :audiocpp_status
215
+ attach_function :audiocpp_stream_start, [:pointer, :pointer], :audiocpp_status, blocking: true
216
+ attach_function :audiocpp_stream_push,
217
+ [:pointer, :pointer, :size_t, :int, :int, :int64, :pointer], :audiocpp_status, blocking: true
218
+ attach_function :audiocpp_stream_next_event, [:pointer, :pointer], :audiocpp_status, blocking: true
219
+ attach_function :audiocpp_stream_finish, [:pointer, :pointer], :audiocpp_status, blocking: true
220
+ attach_function :audiocpp_stream_reset, [:pointer], :audiocpp_status, blocking: true
221
+
222
+ attach_function :audiocpp_event_free, [:pointer], :void
223
+ attach_function :audiocpp_event_is_final, [:pointer], :int
224
+ attach_function :audiocpp_event_as_result, [:pointer], :pointer
225
+
226
+ VoiceActivityKind = enum(:audiocpp_voice_activity_kind, [
227
+ :speech_start, 0,
228
+ :speech_end, 1,
229
+ :speech_segment, 2
230
+ ])
231
+
232
+ attach_function :audiocpp_event_voice_activity_count, [:pointer], :size_t
233
+ attach_function :audiocpp_event_voice_activity,
234
+ [:pointer, :size_t, :pointer, :pointer, :pointer], :audiocpp_status
235
+
236
+ # ---- Helpers ----------------------------------------------------------
237
+
238
+ # Raises the Error subclass for a non-OK status, with the thread-local
239
+ # detail read immediately after the failing call.
240
+ def self.check!(status, operation)
241
+ return if status == :ok
242
+
243
+ detail = utf8(audiocpp_last_error)
244
+ raise AudioCpp.error_class_for(status).new(
245
+ operation: operation,
246
+ status: status,
247
+ status_name: utf8(audiocpp_status_string(status)),
248
+ detail: detail
249
+ )
250
+ end
251
+
252
+ # Borrowed C strings come back as binary; the C API speaks UTF-8.
253
+ def self.utf8(string)
254
+ string&.dup&.force_encoding(Encoding::UTF_8)
255
+ end
256
+
257
+ # Reads a `const char *` written into an out parameter.
258
+ def self.read_string(out)
259
+ pointer = out.read_pointer
260
+ pointer.null? ? nil : utf8(pointer.read_string)
261
+ end
262
+ end
263
+ end
@@ -0,0 +1,55 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "ffi"
4
+
5
+ module AudioCpp
6
+ # Short-lived `audiocpp_registry`. A loaded model keeps its registry alive
7
+ # internally, so the Ruby side frees it right after loading. Internal.
8
+ module Registry
9
+ module_function
10
+
11
+ def open
12
+ out = FFI::MemoryPointer.new(:pointer)
13
+ Native.check!(Native.audiocpp_registry_create(nil, out), "audiocpp_registry_create")
14
+ registry = out.read_pointer
15
+ begin
16
+ yield registry
17
+ ensure
18
+ Native.audiocpp_registry_free(registry)
19
+ end
20
+ end
21
+
22
+ def families
23
+ open do |registry|
24
+ out = FFI::MemoryPointer.new(:pointer)
25
+ Array.new(Native.audiocpp_registry_family_count(registry)) do |index|
26
+ Native.check!(Native.audiocpp_registry_family(registry, index, out), "audiocpp_registry_family")
27
+ Native.read_string(out)
28
+ end
29
+ end
30
+ end
31
+ end
32
+
33
+ # Short-lived `audiocpp_options` built from a Hash; yields NULL for an empty
34
+ # Hash. Internal.
35
+ module Options
36
+ module_function
37
+
38
+ def open(options)
39
+ return yield FFI::Pointer::NULL if options.nil? || options.empty?
40
+
41
+ pointer = Native.audiocpp_options_create
42
+ raise OutOfMemoryError, "audiocpp_options_create returned NULL" if pointer.null?
43
+
44
+ begin
45
+ options.each do |key, value|
46
+ Native.check!(Native.audiocpp_options_set(pointer, key.to_s, value.to_s), "audiocpp_options_set #{key}")
47
+ end
48
+ yield pointer
49
+ ensure
50
+ Native.audiocpp_options_free(pointer)
51
+ end
52
+ end
53
+ end
54
+ private_constant :Registry, :Options
55
+ end
@@ -0,0 +1,68 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "ffi"
4
+
5
+ module AudioCpp
6
+ # Builds an `audiocpp_request`, yields it and frees it. Internal.
7
+ #
8
+ # Option values are strings on the C side; Ruby values are converted with
9
+ # #to_s (true becomes "true"). An Array value is sent as a list option.
10
+ module Request
11
+ module_function
12
+
13
+ def open(audio: nil, text: nil, language: nil, voice: nil, options: {})
14
+ pointer = Native.audiocpp_request_create
15
+ raise OutOfMemoryError, "audiocpp_request_create returned NULL" if pointer.null?
16
+
17
+ begin
18
+ set_text(pointer, text, language)
19
+ set_audio(pointer, audio) if audio
20
+ set_voice(pointer, voice) if voice
21
+ options.each { |key, value| set_option(pointer, key.to_s, value) }
22
+ yield pointer
23
+ ensure
24
+ Native.audiocpp_request_free(pointer)
25
+ end
26
+ end
27
+
28
+ def set_text(pointer, text, language)
29
+ if text
30
+ Native.check!(Native.audiocpp_request_set_text(pointer, text.to_s, language&.to_s), "audiocpp_request_set_text")
31
+ elsif language
32
+ # What audiocpp_cli's --language does for audio input: the option, read by the family.
33
+ Native.check!(Native.audiocpp_request_set_option(pointer, "language", language.to_s), "audiocpp_request_set_option")
34
+ end
35
+ end
36
+
37
+ def set_audio(pointer, audio)
38
+ buffer = float_buffer(audio.samples)
39
+ Native.check!(Native.audiocpp_request_set_audio(pointer, buffer, audio.frames, audio.sample_rate, audio.channels), "audiocpp_request_set_audio")
40
+ end
41
+
42
+ # audiocpp_cli's --voice-id: a built-in voice or a cached voice state.
43
+ def set_voice(pointer, voice)
44
+ Native.check!(Native.audiocpp_request_set_voice_id(pointer, voice.to_s), "audiocpp_request_set_voice_id")
45
+ end
46
+
47
+ def set_option(pointer, key, value)
48
+ return set_list_option(pointer, key, value) if value.is_a?(Array)
49
+
50
+ Native.check!(Native.audiocpp_request_set_option(pointer, key, value.to_s), "audiocpp_request_set_option")
51
+ end
52
+
53
+ def set_list_option(pointer, key, values)
54
+ strings = values.map { |value| FFI::MemoryPointer.from_string(value.to_s) }
55
+ array = FFI::MemoryPointer.new(:pointer, [strings.size, 1].max)
56
+ array.write_array_of_pointer(strings) unless strings.empty?
57
+ Native.check!(Native.audiocpp_request_set_option_array(pointer, key, array, strings.size), "audiocpp_request_set_option_array")
58
+ end
59
+
60
+ # Interleaved float32 samples in native memory (copied by the C side).
61
+ def float_buffer(samples)
62
+ buffer = FFI::MemoryPointer.new(:float, [samples.size, 1].max)
63
+ buffer.write_array_of_float(samples) unless samples.empty?
64
+ buffer
65
+ end
66
+ end
67
+ private_constant :Request
68
+ end
@@ -0,0 +1,38 @@
1
+ # frozen_string_literal: true
2
+
3
+ module AudioCpp
4
+ # Sample-rate conversion by linear interpolation.
5
+ #
6
+ # Good enough to bring speech to the 16 kHz most ASR models want. It has no
7
+ # anti-aliasing filter, so downsampling music or anything with energy above
8
+ # the new Nyquist frequency aliases; use ffmpeg or sox for that.
9
+ module Resampler
10
+ module_function
11
+
12
+ # `samples` is interleaved; returns a new interleaved Array.
13
+ def linear(samples, from:, to:, channels: 1)
14
+ raise ArgumentError, "rates must be positive" unless from.positive? && to.positive?
15
+ return samples.dup if from == to
16
+
17
+ frames_in = samples.size / channels
18
+ return [] if frames_in.zero?
19
+
20
+ frames_out = (frames_in * to).fdiv(from).round
21
+ output = Array.new(frames_out * channels)
22
+ last = frames_in - 1
23
+ frames_out.times do |frame|
24
+ position = (frame * from).fdiv(to)
25
+ index = position.floor
26
+ index = last if index > last
27
+ fraction = position - index
28
+ following = (index < last) ? index + 1 : last
29
+ channels.times do |channel|
30
+ a = samples[(index * channels) + channel]
31
+ b = samples[(following * channels) + channel]
32
+ output[(frame * channels) + channel] = a + ((b - a) * fraction)
33
+ end
34
+ end
35
+ output
36
+ end
37
+ end
38
+ end
@@ -0,0 +1,272 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "ffi"
4
+
5
+ module AudioCpp
6
+ # Positions are in samples of the audio the request carried; `sample_rate`
7
+ # is that audio's rate, so the *_seconds readers need nothing else.
8
+ module Timed
9
+ def start_seconds
10
+ start_sample.fdiv(sample_rate)
11
+ end
12
+
13
+ def end_seconds
14
+ end_sample.fdiv(sample_rate)
15
+ end
16
+
17
+ def duration
18
+ (end_sample - start_sample).fdiv(sample_rate)
19
+ end
20
+ end
21
+
22
+ Word = Struct.new(:text, :start_sample, :end_sample, :confidence, :sample_rate, keyword_init: true) do
23
+ include Timed
24
+ end
25
+
26
+ Segment = Struct.new(:text, :start_sample, :end_sample, :confidence, :sample_rate, keyword_init: true) do
27
+ include Timed
28
+ end
29
+
30
+ # One stretch of one voice. Turns of different speakers may overlap.
31
+ SpeakerTurn = Struct.new(:speaker, :start_sample, :end_sample, :confidence, :text, :sample_rate,
32
+ keyword_init: true) do
33
+ include Timed
34
+ end
35
+
36
+ # An opaque payload a family produced (speaker embedding, diarization state, ...).
37
+ # `kind` is a Symbol, `payload` a binary String, `meta` a Hash of Strings.
38
+ Artifact = Struct.new(:kind, :id, :payload, :meta, keyword_init: true)
39
+
40
+ # Everything a task returned, copied out of the C result, so it outlives the
41
+ # handle and needs no freeing. Fields a task did not produce are nil or empty.
42
+ class Result
43
+ attr_reader :text, :language, :words, :segments, :speaker_turns, :audio, :named_audio, :artifacts,
44
+ :custom_schema, :custom_data
45
+
46
+ def initialize(text: nil, language: nil, words: [], segments: [], speaker_turns: [], audio: nil,
47
+ named_audio: {}, artifacts: [], custom_schema: nil, custom_data: nil)
48
+ @text = text
49
+ @language = language
50
+ @words = words
51
+ @segments = segments
52
+ @speaker_turns = speaker_turns
53
+ @audio = audio
54
+ @named_audio = named_audio
55
+ @artifacts = artifacts
56
+ @custom_schema = custom_schema
57
+ @custom_data = custom_data
58
+ end
59
+
60
+ # Distinct speaker ids in order of first appearance.
61
+ def speakers
62
+ speaker_turns.map(&:speaker).uniq
63
+ end
64
+
65
+ def to_s
66
+ text.to_s
67
+ end
68
+
69
+ def inspect
70
+ parts = []
71
+ parts << "text=#{text.inspect}" if text
72
+ parts << "words=#{words.size}" unless words.empty?
73
+ parts << "segments=#{segments.size}" unless segments.empty?
74
+ parts << "speaker_turns=#{speaker_turns.size}" unless speaker_turns.empty?
75
+ parts << "audio=#{audio.inspect}" if audio
76
+ "#<#{self.class.name} #{parts.join(" ")}>"
77
+ end
78
+
79
+ # Copies a borrowed `audiocpp_result *` into Ruby values.
80
+ def self.read(pointer, sample_rate:)
81
+ new(**ResultReader.new(pointer, sample_rate).fields)
82
+ end
83
+ end
84
+
85
+ # One streaming event: the same shapes as a Result (the text is the newly
86
+ # decoded part, not the running transcript), plus voice activity.
87
+ class Event < Result
88
+ VoiceActivity = Struct.new(:kind, :sample, :probability, keyword_init: true)
89
+
90
+ attr_reader :voice_activity
91
+
92
+ def initialize(final: false, voice_activity: [], **fields)
93
+ super(**fields)
94
+ @final = final
95
+ @voice_activity = voice_activity
96
+ end
97
+
98
+ def final?
99
+ @final
100
+ end
101
+
102
+ # Copies a borrowed `audiocpp_event *` into Ruby values.
103
+ def self.read(pointer, sample_rate:)
104
+ fields = ResultReader.new(Native.audiocpp_event_as_result(pointer), sample_rate).fields
105
+ new(final: Native.audiocpp_event_is_final(pointer) == 1, voice_activity: read_voice_activity(pointer), **fields)
106
+ end
107
+
108
+ def self.read_voice_activity(pointer)
109
+ kind = FFI::MemoryPointer.new(:int)
110
+ sample = FFI::MemoryPointer.new(:int64)
111
+ probability = FFI::MemoryPointer.new(:float)
112
+ Array.new(Native.audiocpp_event_voice_activity_count(pointer)) do |index|
113
+ Native.check!(Native.audiocpp_event_voice_activity(pointer, index, kind, sample, probability),
114
+ "audiocpp_event_voice_activity")
115
+ VoiceActivity.new(kind: Native::VoiceActivityKind[kind.read_int], sample: sample.read_int64,
116
+ probability: probability.read_float)
117
+ end
118
+ end
119
+ private_class_method :read_voice_activity
120
+
121
+ def inspect
122
+ flags = final? ? " final" : ""
123
+ flags += " voice_activity=#{voice_activity.map(&:kind)}" unless voice_activity.empty?
124
+ super.sub(/>\z/, "#{flags}>")
125
+ end
126
+ end
127
+
128
+ # Reads every accessor of a result handle. Internal.
129
+ class ResultReader
130
+ def initialize(pointer, sample_rate)
131
+ @pointer = pointer
132
+ @sample_rate = sample_rate
133
+ end
134
+
135
+ def fields
136
+ text, language = text_and_language
137
+ schema, data = custom_schema
138
+ {
139
+ text: text, language: language, words: words, segments: segments, speaker_turns: speaker_turns,
140
+ audio: audio, named_audio: named_audio, artifacts: artifacts, custom_schema: schema, custom_data: data
141
+ }
142
+ end
143
+
144
+ private
145
+
146
+ attr_reader :pointer, :sample_rate
147
+
148
+ def text_and_language
149
+ text = string_out
150
+ language = string_out
151
+ status = Native.audiocpp_result_text(pointer, text, language)
152
+ return [nil, nil] if status == :not_available
153
+
154
+ Native.check!(status, "audiocpp_result_text")
155
+ [Native.read_string(text), presence(Native.read_string(language))]
156
+ end
157
+
158
+ def custom_schema
159
+ schema = string_out
160
+ data = string_out
161
+ status = Native.audiocpp_result_custom_schema(pointer, schema, data)
162
+ return [nil, nil] if status == :not_available
163
+
164
+ Native.check!(status, "audiocpp_result_custom_schema")
165
+ [Native.read_string(schema), Native.read_string(data)]
166
+ end
167
+
168
+ def audio
169
+ samples, frames, rate, channels = audio_outs
170
+ status = Native.audiocpp_result_audio(pointer, samples, frames, rate, channels)
171
+ return nil if status == :not_available
172
+
173
+ Native.check!(status, "audiocpp_result_audio")
174
+ read_audio(samples, frames, rate, channels)
175
+ end
176
+
177
+ def named_audio
178
+ id = string_out
179
+ samples, frames, rate, channels = audio_outs
180
+ Native.audiocpp_result_named_audio_count(pointer).times.to_h do |index|
181
+ Native.check!(Native.audiocpp_result_named_audio(pointer, index, id, samples, frames, rate, channels),
182
+ "audiocpp_result_named_audio")
183
+ [Native.read_string(id), read_audio(samples, frames, rate, channels)]
184
+ end
185
+ end
186
+
187
+ def words
188
+ word = string_out
189
+ start, stop, confidence = timing_outs
190
+ Array.new(Native.audiocpp_result_word_count(pointer)) do |index|
191
+ Native.check!(Native.audiocpp_result_word(pointer, index, word, start, stop, confidence),
192
+ "audiocpp_result_word")
193
+ Word.new(text: Native.read_string(word), start_sample: start.read_int64, end_sample: stop.read_int64,
194
+ confidence: confidence.read_float, sample_rate: sample_rate)
195
+ end
196
+ end
197
+
198
+ def segments
199
+ text = string_out
200
+ start, stop, confidence = timing_outs
201
+ Array.new(Native.audiocpp_result_segment_count(pointer)) do |index|
202
+ Native.check!(Native.audiocpp_result_segment(pointer, index, start, stop, confidence, text),
203
+ "audiocpp_result_segment")
204
+ Segment.new(text: Native.read_string(text), start_sample: start.read_int64, end_sample: stop.read_int64,
205
+ confidence: confidence.read_float, sample_rate: sample_rate)
206
+ end
207
+ end
208
+
209
+ def speaker_turns
210
+ speaker = string_out
211
+ text = string_out
212
+ start, stop, confidence = timing_outs
213
+ Array.new(Native.audiocpp_result_speaker_turn_count(pointer)) do |index|
214
+ Native.check!(Native.audiocpp_result_speaker_turn(pointer, index, start, stop, speaker, confidence, text),
215
+ "audiocpp_result_speaker_turn")
216
+ SpeakerTurn.new(speaker: Native.read_string(speaker), start_sample: start.read_int64,
217
+ end_sample: stop.read_int64, confidence: confidence.read_float, text: presence(Native.read_string(text)),
218
+ sample_rate: sample_rate)
219
+ end
220
+ end
221
+
222
+ def artifacts
223
+ kind = FFI::MemoryPointer.new(:int)
224
+ id = string_out
225
+ payload = FFI::MemoryPointer.new(:pointer)
226
+ bytes = FFI::MemoryPointer.new(:size_t)
227
+ Array.new(Native.audiocpp_result_artifact_count(pointer)) do |index|
228
+ Native.check!(Native.audiocpp_result_artifact(pointer, index, kind, id, payload, bytes),
229
+ "audiocpp_result_artifact")
230
+ data = payload.read_pointer
231
+ size = bytes.read(:size_t)
232
+ Artifact.new(kind: Native::ArtifactKind[kind.read_int], id: Native.read_string(id),
233
+ payload: (data.null? || size.zero?) ? "".b : data.read_bytes(size), meta: artifact_meta(index))
234
+ end
235
+ end
236
+
237
+ def artifact_meta(index)
238
+ key = string_out
239
+ value = string_out
240
+ Native.audiocpp_result_artifact_meta_count(pointer, index).times.to_h do |meta_index|
241
+ Native.check!(Native.audiocpp_result_artifact_meta(pointer, index, meta_index, key, value),
242
+ "audiocpp_result_artifact_meta")
243
+ [Native.read_string(key), Native.read_string(value)]
244
+ end
245
+ end
246
+
247
+ def read_audio(samples, frames, rate, channels)
248
+ count = frames.read(:size_t) * channels.read_int
249
+ data = samples.read_pointer
250
+ values = (data.null? || count.zero?) ? [] : data.read_array_of_float(count)
251
+ Audio.new(values, sample_rate: rate.read_int, channels: channels.read_int)
252
+ end
253
+
254
+ def string_out
255
+ FFI::MemoryPointer.new(:pointer)
256
+ end
257
+
258
+ def timing_outs
259
+ [FFI::MemoryPointer.new(:int64), FFI::MemoryPointer.new(:int64), FFI::MemoryPointer.new(:float)]
260
+ end
261
+
262
+ def audio_outs
263
+ [FFI::MemoryPointer.new(:pointer), FFI::MemoryPointer.new(:size_t), FFI::MemoryPointer.new(:int),
264
+ FFI::MemoryPointer.new(:int)]
265
+ end
266
+
267
+ def presence(string)
268
+ (string.nil? || string.empty?) ? nil : string
269
+ end
270
+ end
271
+ private_constant :ResultReader
272
+ end