-
Notifications
You must be signed in to change notification settings - Fork 10
Expand file tree
/
Copy pathOrca.swift
More file actions
662 lines (567 loc) · 26.6 KB
/
Copy pathOrca.swift
File metadata and controls
662 lines (567 loc) · 26.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
//
// Copyright 2024-2025 Picovoice Inc.
// You may not use this file except in compliance with the license. A copy of the license is located in the "LICENSE"
// file accompanying this source.
// Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
// an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
// specific language governing permissions and limitations under the License.
//
import Foundation
import PvOrca
public struct OrcaPhoneme {
/// Synthesized phoneme.
public let phoneme: String
/// Start of phoneme in seconds.
public let startSec: Float
/// End of phoneme in seconds.
public let endSec: Float
/// Constructor.
///
/// - Parameters:
/// - phoneme: Synthesized phoneme.
/// - startSec: Start of phoneme in seconds.
/// - endSec: End of phoneme in seconds.
public init(
phoneme: String,
startSec: Float,
endSec: Float) {
self.phoneme = phoneme
self.startSec = startSec
self.endSec = endSec
}
}
public struct OrcaWord {
/// Synthesized word.
public let word: String
/// Start of word in seconds.
public let startSec: Float
/// End of word in seconds.
public let endSec: Float
/// Array of phonemes.
public let phonemeArray: [OrcaPhoneme]
/// Constructor.
///
/// - Parameters:
/// - word: Synthesized word.
/// - startSec: Start of word in seconds.
/// - endSec: End of word in seconds.
/// - phonemeArray: Array of phonemes.
public init(
word: String,
startSec: Float,
endSec: Float,
phonemeArray: [OrcaPhoneme]) {
self.word = word
self.startSec = startSec
self.endSec = endSec
self.phonemeArray = phonemeArray
}
}
private func swapQuotes(_ text: String) -> String {
var output = text
output = output.replacingOccurrences(of: "’", with: "'")
output = output.replacingOccurrences(of: "‘", with: "'")
output = output.replacingOccurrences(of: "“", with: "\"")
output = output.replacingOccurrences(of: "”", with: "\"")
return output
}
/// iOS (Swift) binding for Orca Text-to-Speech engine. Provides a Swift interface to the Orca library.
public class Orca {
private var handle: OpaquePointer?
private var stream: OpaquePointer?
/// Orca valid symbols
private var _validCharacters: Set<String>?
/// Orca sample rate
private var _sampleRate: Int32?
/// Maximum number of characters allowed in a single synthesis request.
private var _maxCharacterLimit: Int32?
/// Orca version string
public static let version = String(cString: pv_orca_version())
private static var sdk = "ios"
/// OrcaStream object that converts a stream of text to a stream of audio.
public class OrcaStream {
private var orca: Orca
private var stream: OpaquePointer?
/// Adds a chunk of text to the OrcaStream object and generates audio if enough text has been added.
/// This function is expected to be called multiple times with consecutive chunks of text from a text stream.
/// The incoming text is buffered as it arrives until the length is long enough to convert a chunk of the
/// buffered text into audio. The caller needs to use `OrcaStream.flush()` to generate the audio chunk
/// for the remaining text that has not yet been synthesized.
///
/// - Parameters:
/// - text: A chunk of text from a text input stream, comprised of valid characters.
/// Valid characters can be retrieved by calling `.validCharacters`.
/// Custom pronunciations can be embedded in the text via the syntax `{word|pronunciation}`.
/// They need to be added in a single call to this function.
/// The pronunciation is expressed in ARPAbet format, e.g.: "I {live|L IH V} in {Sevilla|S EH V IY Y AH}".
/// - Returns: The generated audio as a sequence of 16-bit linearly-encoded integers, `nil` if no
/// audio chunk has been produced.
/// - Throws: OrcaError
public func synthesize(text: String) throws -> [Int16]? {
if stream == nil {
throw OrcaInvalidStateError("Unable to synthesize - stream not open")
}
var cNumSamples: Int32 = 0
var cPcm: UnsafeMutablePointer<Int16>?
let formattedText = swapQuotes(text)
let status = pv_orca_stream_synthesize(
stream,
formattedText,
&cNumSamples,
&cPcm)
if status != PV_STATUS_SUCCESS {
let messageStack = try Orca.getMessageStack()
throw Orca.pvStatusToOrcaError(status, "Unable to synthesize streaming speech", messageStack)
}
let buffer = UnsafeBufferPointer(start: cPcm, count: Int(cNumSamples))
let pcm = Array(buffer)
pv_orca_pcm_delete(cPcm)
return pcm.isEmpty ? nil : pcm
}
/// Generates audio for all the buffered text that was added to the OrcaStream object
/// via `OrcaStream.synthesize()`.
///
/// - Returns: The generated audio as a sequence of 16-bit linearly-encoded integers, `nil` if no
/// audio chunk has been produced.
/// - Throws: OrcaError
public func flush() throws -> [Int16]? {
if stream == nil {
throw OrcaInvalidStateError("Unable to flush - stream not open")
}
var cNumSamples: Int32 = 0
var cPcm: UnsafeMutablePointer<Int16>?
let status = pv_orca_stream_flush(
stream,
&cNumSamples,
&cPcm)
if status != PV_STATUS_SUCCESS {
let messageStack = try Orca.getMessageStack()
throw Orca.pvStatusToOrcaError(status, "Unable to flush streaming speech", messageStack)
}
let buffer = UnsafeBufferPointer(start: cPcm, count: Int(cNumSamples))
let pcm = Array(buffer)
pv_orca_pcm_delete(cPcm)
return pcm.isEmpty ? nil : pcm
}
/// Releases the resources acquired by the OrcaStream object.
public func close() {
if stream != nil {
pv_orca_stream_close(stream)
stream = nil
}
}
public init(orca: Orca, stream: OpaquePointer) {
self.orca = orca
self.stream = stream
}
}
public static func setSdk(sdk: String) {
self.sdk = sdk
}
/// Lists all available devices that Orca can use for inference.
/// Entries in the list can be used as the `device` argument when initializing Orca.
///
/// - Throws: OrcaError
/// - Returns: Array of available devices that Orca can be used for inference.
public static func getAvailableDevices() throws -> [String] {
var cHardwareDevices: UnsafeMutablePointer<UnsafeMutablePointer<Int8>?>?
var numHardwareDevices: Int32 = 0
let status = pv_orca_list_hardware_devices(&cHardwareDevices, &numHardwareDevices)
if status != PV_STATUS_SUCCESS {
let messageStack = try Orca.getMessageStack()
throw Orca.pvStatusToOrcaError(status, "Orca getAvailableDevices failed", messageStack)
}
var hardwareDevices: [String] = []
for i in 0..<numHardwareDevices {
hardwareDevices.append(String(cString: cHardwareDevices!.advanced(by: Int(i)).pointee!))
}
pv_orca_free_hardware_devices(cHardwareDevices, numHardwareDevices)
return hardwareDevices
}
/// Set of characters supported by Orca.
public var validCharacters: Set<String>? {
return self._validCharacters
}
/// Audio sample rate of generated audio.
public var sampleRate: Int32? {
return self._sampleRate
}
/// Maximum number of characters allowed per call to `synthesize()`.
public var maxCharacterLimit: Int32? {
return self._maxCharacterLimit
}
/// Constructor.
///
/// - Parameters:
/// - accessKey: AccessKey obtained from the Picovoice Console (https://console.picovoice.ai/)
/// - modelPath: Absolute path to file containing model parameters.
/// - device: String representation of the device (e.g., CPU or GPU) to use. If set to `best`, the most
/// suitable device is selected automatically. If set to `gpu`, the engine uses the first available GPU
/// device. To select a specific GPU device, set this argument to `gpu:${GPU_INDEX}`, where `${GPU_INDEX}`
/// is the index of the target GPU. If set to `cpu`, the engine will run on the CPU with the default
/// number of threads. To specify the number of threads, set this argument to `cpu:${NUM_THREADS}`,
/// where `${NUM_THREADS}` is the desired number of threads.
/// - Throws: OrcaError
public init(
accessKey: String,
modelPath: String,
device: String? = nil) throws {
var modelPathArg = modelPath
if !FileManager().fileExists(atPath: modelPathArg) {
modelPathArg = try getResourcePath(modelPathArg)
}
var deviceArg = device
if device == nil {
deviceArg = "best"
}
pv_set_sdk(Orca.sdk)
let initStatus = pv_orca_init(
accessKey,
modelPathArg,
deviceArg,
&handle)
if initStatus != PV_STATUS_SUCCESS {
let messageStack = try Orca.getMessageStack()
throw Orca.pvStatusToOrcaError(initStatus, "Orca init failed", messageStack)
}
var cNumCharacters: Int32 = 0
var cCharacters: UnsafePointer<UnsafePointer<Int8>?>?
let validCharactersStatus = pv_orca_valid_characters(handle, &cNumCharacters, &cCharacters)
if validCharactersStatus != PV_STATUS_SUCCESS {
let messageStack = try Orca.getMessageStack()
throw Orca.pvStatusToOrcaError(validCharactersStatus, "Unable to get Orca valid characters", messageStack)
}
var validCharacters: Set<String> = ["‘", "’", "“", "”"]
for i in 0..<cNumCharacters {
if let cString = cCharacters?.advanced(by: Int(i)).pointee {
let swiftString = String(cString: cString)
validCharacters.insert(swiftString)
}
}
pv_orca_valid_characters_delete(cCharacters)
self._validCharacters = validCharacters
var cSampleRate: Int32 = 0
let sampleRateStatus = pv_orca_sample_rate(handle, &cSampleRate)
if sampleRateStatus != PV_STATUS_SUCCESS {
let messageStack = try Orca.getMessageStack()
throw Orca.pvStatusToOrcaError(sampleRateStatus, "Orca failed to get sample rate", messageStack)
}
self._sampleRate = cSampleRate
var cMaxCharacterLimit: Int32 = 0
let maxCharacterLimitStatus = pv_orca_max_character_limit(handle, &cMaxCharacterLimit)
if maxCharacterLimitStatus != PV_STATUS_SUCCESS {
let messageStack = try Orca.getMessageStack()
throw Orca.pvStatusToOrcaError(
maxCharacterLimitStatus,
"Orca failed to get max character limit",
messageStack)
}
self._maxCharacterLimit = cMaxCharacterLimit
}
/// Constructor.
///
/// - Parameters:
/// - accessKey: The AccessKey obtained from Picovoice Console (https://console.picovoice.ai).
/// - modelURL: URL to file containing model parameters.
/// - device: String representation of the device (e.g., CPU or GPU) to use. If set to `best`, the most
/// suitable device is selected automatically. If set to `gpu`, the engine uses the first available GPU
/// device. To select a specific GPU device, set this argument to `gpu:${GPU_INDEX}`, where `${GPU_INDEX}`
/// is the index of the target GPU. If set to `cpu`, the engine will run on the CPU with the default
/// number of threads. To specify the number of threads, set this argument to `cpu:${NUM_THREADS}`,
/// where `${NUM_THREADS}` is the desired number of threads.
/// - Throws: OrcaError
public convenience init(
accessKey: String,
modelURL: URL,
device: String? = nil) throws {
try self.init(
accessKey: accessKey,
modelPath: modelURL.path,
device: device)
}
deinit {
self.delete()
}
/// Releases native resources that were allocated to Orca
public func delete() {
if handle != nil {
pv_orca_delete(handle)
handle = nil
}
}
/// Generates audio from text. The returned audio contains the speech representation of the text.
///
/// - Parameters:
/// - text: Text to be converted to audio. The maximum number of characters per call to `.synthesize()` is
/// `self.maxCharacterLimit`. Allowed characters can be retrieved by calling `self.validCharacters`.
/// Custom pronunciations can be embedded in the text via the syntax `{word|pronunciation}`.
/// The pronunciation is expressed in ARPAbet format, e.g.: "I {live|L IH V} in {Sevilla|S EH V IY Y AH}".
/// - speechRate: Rate of speech of the generated audio. Valid values are within [0.7, 1.3].
/// - randomState: Random seed for the synthesis process.
/// - Returns: A tuple containing the generated audio as a sequence of 16-bit linearly-encoded integers
/// and an array of OrcaWord objects representing the word alignments.
/// - Throws: OrcaError
public func synthesize(
text: String,
speechRate: Double? = nil,
randomState: Int64? = nil
) throws -> (pcm: [Int16], wordArray: [OrcaWord]) {
if handle == nil {
throw OrcaInvalidStateError("Unable to synthesize - resources have been released")
}
if text.count > self._maxCharacterLimit! {
throw OrcaInvalidArgumentError(
"Text length (\(text.count)) must be smaller than \(self._maxCharacterLimit!)")
}
let cSynthesizeParams = try getCSynthesizeParams(speechRate: speechRate, randomState: randomState)
var cNumSamples: Int32 = 0
var cPcm: UnsafeMutablePointer<Int16>?
var cNumAlignments: Int32 = 0
var cAlignments: UnsafeMutablePointer<UnsafeMutablePointer<pv_orca_word_alignment_t>?>?
let formattedText = swapQuotes(text)
let status = pv_orca_synthesize(
handle,
formattedText,
cSynthesizeParams,
&cNumSamples,
&cPcm,
&cNumAlignments,
&cAlignments)
if status != PV_STATUS_SUCCESS {
let messageStack = try Orca.getMessageStack()
throw Orca.pvStatusToOrcaError(status, "Unable to synthesize speech", messageStack)
}
let buffer = UnsafeBufferPointer(start: cPcm, count: Int(cNumSamples))
let pcm = Array(buffer)
var wordArray = [OrcaWord]()
if let cAlignments = cAlignments {
for alignmentIndex in 0..<Int(cNumAlignments) {
if let cAlignment = cAlignments[alignmentIndex]?.pointee {
var phonemeArray = [OrcaPhoneme]()
if let phonemesPointer = cAlignment.phonemes {
for phonemeIndex in 0..<Int(cAlignment.num_phonemes) {
if let cPhoneme = phonemesPointer.advanced(by: phonemeIndex).pointee {
let phoneme = OrcaPhoneme(
phoneme: String(cString: cPhoneme.pointee.phoneme),
startSec: Float(cPhoneme.pointee.start_sec),
endSec: Float(cPhoneme.pointee.end_sec)
)
phonemeArray.append(phoneme)
}
}
}
let word = OrcaWord(
word: String(cString: cAlignment.word),
startSec: Float(cAlignment.start_sec),
endSec: Float(cAlignment.end_sec),
phonemeArray: phonemeArray
)
wordArray.append(word)
}
}
}
pv_orca_pcm_delete(cPcm)
pv_orca_synthesize_params_delete(cSynthesizeParams)
pv_orca_word_alignments_delete(cNumAlignments, cAlignments)
return (pcm, wordArray)
}
/// Generates audio from text and saves it to a WAV file. The file contains the speech representation of the text.
///
/// - Parameters:
/// - text: Text to be converted to audio. The maximum number of characters per call to `.synthesize()` is
/// `self.maxCharacterLimit`. Allowed characters can be retrieved by calling `self.validCharacters`.
/// Custom pronunciations can be embedded in the text via the syntax `{word|pronunciation}`.
/// The pronunciation is expressed in ARPAbet format, e.g.: "I {live|L IH V} in {Sevilla|S EH V IY Y AH}".
/// - outputPath: Absolute path to the output audio file. The output file is saved as `WAV (.wav)`
/// and consists of a single mono channel.
/// - speechRate: Rate of speech of the generated audio. Valid values are within [0.7, 1.3].
/// - randomState: Random seed for the synthesis process.
/// - Returns: An array of OrcaWord objects representing the word alignments.
/// - Throws: OrcaError
public func synthesizeToFile(
text: String,
outputPath: String,
speechRate: Double? = nil,
randomState: Int64? = nil
) throws -> [OrcaWord] {
if handle == nil {
throw OrcaInvalidStateError("Unable to synthesize - resources have been released")
}
if text.count > self._maxCharacterLimit! {
throw OrcaInvalidArgumentError(
"Text length (\(text.count)) must be smaller than \(self._maxCharacterLimit!)")
}
let cSynthesizeParams = try getCSynthesizeParams(speechRate: speechRate, randomState: randomState)
var cNumAlignments: Int32 = 0
var cAlignments: UnsafeMutablePointer<UnsafeMutablePointer<pv_orca_word_alignment_t>?>?
let formattedText = swapQuotes(text)
let status = pv_orca_synthesize_to_file(
handle,
formattedText,
cSynthesizeParams,
outputPath,
&cNumAlignments,
&cAlignments)
if status != PV_STATUS_SUCCESS {
let messageStack = try Orca.getMessageStack()
throw Orca.pvStatusToOrcaError(status, "Unable to synthesize speech to file", messageStack)
}
var wordArray = [OrcaWord]()
if let cAlignments = cAlignments {
for alignmentIndex in 0..<Int(cNumAlignments) {
if let cAlignment = cAlignments[alignmentIndex]?.pointee {
var phonemeArray = [OrcaPhoneme]()
if let phonemesPointer = cAlignment.phonemes {
for phonemeIndex in 0..<Int(cAlignment.num_phonemes) {
if let cPhoneme = phonemesPointer.advanced(by: phonemeIndex).pointee {
let phoneme = OrcaPhoneme(
phoneme: String(cString: cPhoneme.pointee.phoneme),
startSec: Float(cPhoneme.pointee.start_sec),
endSec: Float(cPhoneme.pointee.end_sec)
)
phonemeArray.append(phoneme)
}
}
}
let word = OrcaWord(
word: String(cString: cAlignment.word),
startSec: Float(cAlignment.start_sec),
endSec: Float(cAlignment.end_sec),
phonemeArray: phonemeArray
)
wordArray.append(word)
}
}
}
pv_orca_synthesize_params_delete(cSynthesizeParams)
pv_orca_word_alignments_delete(cNumAlignments, cAlignments)
return wordArray
}
/// Generates audio from text and saves it to a WAV file. The file contains the speech representation of the text.
///
/// - Parameters:
/// - text: Text to be converted to audio. The maximum number of characters per call to `.synthesize()` is
/// `self.maxCharacterLimit`. Allowed characters can be retrieved by calling `self.validCharacters`.
/// Custom pronunciations can be embedded in the text via the syntax `{word|pronunciation}`.
/// The pronunciation is expressed in ARPAbet format, e.g.: "I {live|L IH V} in {Sevilla|S EH V IY Y AH}".
/// - outputURL: URL to the output audio file. The output file is saved as `WAV (.wav)`
/// and consists of a single mono channel.
/// - speechRate: Rate of speech of the generated audio. Valid values are within [0.7, 1.3].
/// - randomState: Random seed for the synthesis process.
/// - Returns: An array of OrcaWord objects representing the word alignments.
/// - Throws: OrcaError
public func synthesizeToFile(
text: String,
outputURL: URL,
speechRate: Double? = nil,
randomState: Int64? = nil
) throws -> [OrcaWord] {
try synthesizeToFile(text: text, outputPath: outputURL.path, speechRate: speechRate, randomState: randomState)
}
private func getCSynthesizeParams(speechRate: Double? = nil, randomState: Int64? = nil) throws -> OpaquePointer? {
var cParams: OpaquePointer?
var status = pv_orca_synthesize_params_init(&cParams)
if status != PV_STATUS_SUCCESS {
let messageStack = try Orca.getMessageStack()
throw Orca.pvStatusToOrcaError(status, "Unable to create Orca synthesize params object", messageStack)
}
if speechRate != nil {
status = pv_orca_synthesize_params_set_speech_rate(cParams, Float(speechRate!))
if status != PV_STATUS_SUCCESS {
let messageStack = try Orca.getMessageStack()
throw Orca.pvStatusToOrcaError(status, "Unable to set Orca speech rate", messageStack)
}
}
if randomState != nil {
status = pv_orca_synthesize_params_set_random_state(cParams, randomState!)
if status != PV_STATUS_SUCCESS {
let messageStack = try Orca.getMessageStack()
throw Orca.pvStatusToOrcaError(status, "Unable to set Orca random state", messageStack)
}
}
return cParams
}
/// Opens a stream for streaming text synthesis.
///
/// - Parameters:
/// - speechRate: Rate of speech of the generated audio. Valid values are within [0.7, 1.3].
/// - randomState: Random seed for the synthesis process.
/// - Returns: An instance of the OrcaStream class.
/// - Throws: OrcaError
public func streamOpen(speechRate: Double? = nil, randomState: Int64? = nil) throws -> OrcaStream {
if handle == nil {
throw OrcaInvalidStateError("Unable to synthesize - resources have been released")
}
let cSynthesizeParams = try getCSynthesizeParams(speechRate: speechRate, randomState: randomState)
let status = pv_orca_stream_open(
handle,
cSynthesizeParams,
&stream)
if status != PV_STATUS_SUCCESS {
let messageStack = try Orca.getMessageStack()
throw Orca.pvStatusToOrcaError(status, "Unable to open stream", messageStack)
}
return OrcaStream(orca: self, stream: stream!)
}
/// Given a path, return the full path to the resource.
///
/// - Parameters:
/// - filePath: relative path of a file in the bundle.
/// - Throws: OrcaIOError
/// - Returns: The full path of the resource.
private func getResourcePath(_ filePath: String) throws -> String {
if let resourcePath = Bundle(for: type(of: self)).resourceURL?.appendingPathComponent(filePath).path {
if FileManager.default.fileExists(atPath: resourcePath) {
return resourcePath
}
}
throw OrcaIOError("Could not find file at path '\(filePath)'. " +
"If this is a packaged asset, ensure you have added it to your xcode project.")
}
private static func pvStatusToOrcaError(
_ status: pv_status_t,
_ message: String,
_ messageStack: [String] = []) -> OrcaError {
switch status {
case PV_STATUS_OUT_OF_MEMORY:
return OrcaMemoryError(message, messageStack)
case PV_STATUS_IO_ERROR:
return OrcaIOError(message, messageStack)
case PV_STATUS_INVALID_ARGUMENT:
return OrcaInvalidArgumentError(message, messageStack)
case PV_STATUS_STOP_ITERATION:
return OrcaStopIterationError(message, messageStack)
case PV_STATUS_KEY_ERROR:
return OrcaKeyError(message, messageStack)
case PV_STATUS_INVALID_STATE:
return OrcaInvalidStateError(message, messageStack)
case PV_STATUS_RUNTIME_ERROR:
return OrcaRuntimeError(message, messageStack)
case PV_STATUS_ACTIVATION_ERROR:
return OrcaActivationError(message, messageStack)
case PV_STATUS_ACTIVATION_LIMIT_REACHED:
return OrcaActivationLimitError(message, messageStack)
case PV_STATUS_ACTIVATION_THROTTLED:
return OrcaActivationThrottledError(message, messageStack)
case PV_STATUS_ACTIVATION_REFUSED:
return OrcaActivationRefusedError(message, messageStack)
default:
let pvStatusString = String(cString: pv_status_to_string(status))
return OrcaError("\(pvStatusString): \(message)", messageStack)
}
}
private static func getMessageStack() throws -> [String] {
var messageStackRef: UnsafeMutablePointer<UnsafeMutablePointer<Int8>?>?
var messageStackDepth: Int32 = 0
let status = pv_get_error_stack(&messageStackRef, &messageStackDepth)
if status != PV_STATUS_SUCCESS {
throw Orca.pvStatusToOrcaError(status, "Unable to get Orca error state")
}
var messageStack: [String] = []
for i in 0..<messageStackDepth {
messageStack.append(String(cString: messageStackRef!.advanced(by: Int(i)).pointee!))
}
pv_free_error_stack(messageStackRef)
return messageStack
}
}