main
swift 2,007 lines 63.2 KB
Raw
1 // This file was autogenerated by some hot garbage in the `uniffi` crate.
2 // Trust me, you don't want to mess with it!
3
4 // swiftlint:disable all
5 import Foundation
6
7 // Depending on the consumer's build setup, the low-level FFI code
8 // might be in a separate module, or it might be compiled inline into
9 // this module. This is a bit of light hackery to work with both.
10 #if canImport(demucs_ffiFFI)
11 import demucs_ffiFFI
12 #endif
13
14 fileprivate extension RustBuffer {
15 // Allocate a new buffer, copying the contents of a `UInt8` array.
16 init(bytes: [UInt8]) {
17 let rbuf = bytes.withUnsafeBufferPointer { ptr in
18 RustBuffer.from(ptr)
19 }
20 self.init(capacity: rbuf.capacity, len: rbuf.len, data: rbuf.data)
21 }
22
23 static func empty() -> RustBuffer {
24 RustBuffer(capacity: 0, len:0, data: nil)
25 }
26
27 static func from(_ ptr: UnsafeBufferPointer<UInt8>) -> RustBuffer {
28 try! rustCall { ffi_demucs_ffi_rustbuffer_from_bytes(ForeignBytes(bufferPointer: ptr), $0) }
29 }
30
31 // Frees the buffer in place.
32 // The buffer must not be used after this is called.
33 func deallocate() {
34 try! rustCall { ffi_demucs_ffi_rustbuffer_free(self, $0) }
35 }
36 }
37
38 fileprivate extension ForeignBytes {
39 init(bufferPointer: UnsafeBufferPointer<UInt8>) {
40 self.init(len: Int32(bufferPointer.count), data: bufferPointer.baseAddress)
41 }
42 }
43
44 // For every type used in the interface, we provide helper methods for conveniently
45 // lifting and lowering that type from C-compatible data, and for reading and writing
46 // values of that type in a buffer.
47
48 // Helper classes/extensions that don't change.
49 // Someday, this will be in a library of its own.
50
51 fileprivate extension Data {
52 init(rustBuffer: RustBuffer) {
53 self.init(
54 bytesNoCopy: rustBuffer.data!,
55 count: Int(rustBuffer.len),
56 deallocator: .none
57 )
58 }
59 }
60
61 // Define reader functionality. Normally this would be defined in a class or
62 // struct, but we use standalone functions instead in order to make external
63 // types work.
64 //
65 // With external types, one swift source file needs to be able to call the read
66 // method on another source file's FfiConverter, but then what visibility
67 // should Reader have?
68 // - If Reader is fileprivate, then this means the read() must also
69 // be fileprivate, which doesn't work with external types.
70 // - If Reader is internal/public, we'll get compile errors since both source
71 // files will try define the same type.
72 //
73 // Instead, the read() method and these helper functions input a tuple of data
74
75 fileprivate func createReader(data: Data) -> (data: Data, offset: Data.Index) {
76 (data: data, offset: 0)
77 }
78
79 // Reads an integer at the current offset, in big-endian order, and advances
80 // the offset on success. Throws if reading the integer would move the
81 // offset past the end of the buffer.
82 fileprivate func readInt<T: FixedWidthInteger>(_ reader: inout (data: Data, offset: Data.Index)) throws -> T {
83 let range = reader.offset..<reader.offset + MemoryLayout<T>.size
84 guard reader.data.count >= range.upperBound else {
85 throw UniffiInternalError.bufferOverflow
86 }
87 if T.self == UInt8.self {
88 let value = reader.data[reader.offset]
89 reader.offset += 1
90 return value as! T
91 }
92 var value: T = 0
93 let _ = withUnsafeMutableBytes(of: &value, { reader.data.copyBytes(to: $0, from: range)})
94 reader.offset = range.upperBound
95 return value.bigEndian
96 }
97
98 // Reads an arbitrary number of bytes, to be used to read
99 // raw bytes, this is useful when lifting strings
100 fileprivate func readBytes(_ reader: inout (data: Data, offset: Data.Index), count: Int) throws -> Array<UInt8> {
101 let range = reader.offset..<(reader.offset+count)
102 guard reader.data.count >= range.upperBound else {
103 throw UniffiInternalError.bufferOverflow
104 }
105 var value = [UInt8](repeating: 0, count: count)
106 value.withUnsafeMutableBufferPointer({ buffer in
107 reader.data.copyBytes(to: buffer, from: range)
108 })
109 reader.offset = range.upperBound
110 return value
111 }
112
113 // Reads a float at the current offset.
114 fileprivate func readFloat(_ reader: inout (data: Data, offset: Data.Index)) throws -> Float {
115 return Float(bitPattern: try readInt(&reader))
116 }
117
118 // Reads a float at the current offset.
119 fileprivate func readDouble(_ reader: inout (data: Data, offset: Data.Index)) throws -> Double {
120 return Double(bitPattern: try readInt(&reader))
121 }
122
123 // Indicates if the offset has reached the end of the buffer.
124 fileprivate func hasRemaining(_ reader: (data: Data, offset: Data.Index)) -> Bool {
125 return reader.offset < reader.data.count
126 }
127
128 // Define writer functionality. Normally this would be defined in a class or
129 // struct, but we use standalone functions instead in order to make external
130 // types work. See the above discussion on Readers for details.
131
132 fileprivate func createWriter() -> [UInt8] {
133 return []
134 }
135
136 fileprivate func writeBytes<S>(_ writer: inout [UInt8], _ byteArr: S) where S: Sequence, S.Element == UInt8 {
137 writer.append(contentsOf: byteArr)
138 }
139
140 // Writes an integer in big-endian order.
141 //
142 // Warning: make sure what you are trying to write
143 // is in the correct type!
144 fileprivate func writeInt<T: FixedWidthInteger>(_ writer: inout [UInt8], _ value: T) {
145 var value = value.bigEndian
146 withUnsafeBytes(of: &value) { writer.append(contentsOf: $0) }
147 }
148
149 fileprivate func writeFloat(_ writer: inout [UInt8], _ value: Float) {
150 writeInt(&writer, value.bitPattern)
151 }
152
153 fileprivate func writeDouble(_ writer: inout [UInt8], _ value: Double) {
154 writeInt(&writer, value.bitPattern)
155 }
156
157 // Protocol for types that transfer other types across the FFI. This is
158 // analogous to the Rust trait of the same name.
159 fileprivate protocol FfiConverter {
160 associatedtype FfiType
161 associatedtype SwiftType
162
163 static func lift(_ value: FfiType) throws -> SwiftType
164 static func lower(_ value: SwiftType) -> FfiType
165 static func read(from buf: inout (data: Data, offset: Data.Index)) throws -> SwiftType
166 static func write(_ value: SwiftType, into buf: inout [UInt8])
167 }
168
169 // Types conforming to `Primitive` pass themselves directly over the FFI.
170 fileprivate protocol FfiConverterPrimitive: FfiConverter where FfiType == SwiftType { }
171
172 extension FfiConverterPrimitive {
173 #if swift(>=5.8)
174 @_documentation(visibility: private)
175 #endif
176 public static func lift(_ value: FfiType) throws -> SwiftType {
177 return value
178 }
179
180 #if swift(>=5.8)
181 @_documentation(visibility: private)
182 #endif
183 public static func lower(_ value: SwiftType) -> FfiType {
184 return value
185 }
186 }
187
188 // Types conforming to `FfiConverterRustBuffer` lift and lower into a `RustBuffer`.
189 // Used for complex types where it's hard to write a custom lift/lower.
190 fileprivate protocol FfiConverterRustBuffer: FfiConverter where FfiType == RustBuffer {}
191
192 extension FfiConverterRustBuffer {
193 #if swift(>=5.8)
194 @_documentation(visibility: private)
195 #endif
196 public static func lift(_ buf: RustBuffer) throws -> SwiftType {
197 var reader = createReader(data: Data(rustBuffer: buf))
198 let value = try read(from: &reader)
199 if hasRemaining(reader) {
200 throw UniffiInternalError.incompleteData
201 }
202 buf.deallocate()
203 return value
204 }
205
206 #if swift(>=5.8)
207 @_documentation(visibility: private)
208 #endif
209 public static func lower(_ value: SwiftType) -> RustBuffer {
210 var writer = createWriter()
211 write(value, into: &writer)
212 return RustBuffer(bytes: writer)
213 }
214 }
215 // An error type for FFI errors. These errors occur at the UniFFI level, not
216 // the library level.
217 fileprivate enum UniffiInternalError: LocalizedError {
218 case bufferOverflow
219 case incompleteData
220 case unexpectedOptionalTag
221 case unexpectedEnumCase
222 case unexpectedNullPointer
223 case unexpectedRustCallStatusCode
224 case unexpectedRustCallError
225 case unexpectedStaleHandle
226 case rustPanic(_ message: String)
227
228 public var errorDescription: String? {
229 switch self {
230 case .bufferOverflow: return "Reading the requested value would read past the end of the buffer"
231 case .incompleteData: return "The buffer still has data after lifting its containing value"
232 case .unexpectedOptionalTag: return "Unexpected optional tag; should be 0 or 1"
233 case .unexpectedEnumCase: return "Raw enum value doesn't match any cases"
234 case .unexpectedNullPointer: return "Raw pointer value was null"
235 case .unexpectedRustCallStatusCode: return "Unexpected RustCallStatus code"
236 case .unexpectedRustCallError: return "CALL_ERROR but no errorClass specified"
237 case .unexpectedStaleHandle: return "The object in the handle map has been dropped already"
238 case let .rustPanic(message): return message
239 }
240 }
241 }
242
243 fileprivate extension NSLock {
244 func withLock<T>(f: () throws -> T) rethrows -> T {
245 self.lock()
246 defer { self.unlock() }
247 return try f()
248 }
249 }
250
251 fileprivate let CALL_SUCCESS: Int8 = 0
252 fileprivate let CALL_ERROR: Int8 = 1
253 fileprivate let CALL_UNEXPECTED_ERROR: Int8 = 2
254 fileprivate let CALL_CANCELLED: Int8 = 3
255
256 fileprivate extension RustCallStatus {
257 init() {
258 self.init(
259 code: CALL_SUCCESS,
260 errorBuf: RustBuffer.init(
261 capacity: 0,
262 len: 0,
263 data: nil
264 )
265 )
266 }
267 }
268
269 private func rustCall<T>(_ callback: (UnsafeMutablePointer<RustCallStatus>) -> T) throws -> T {
270 let neverThrow: ((RustBuffer) throws -> Never)? = nil
271 return try makeRustCall(callback, errorHandler: neverThrow)
272 }
273
274 private func rustCallWithError<T, E: Swift.Error>(
275 _ errorHandler: @escaping (RustBuffer) throws -> E,
276 _ callback: (UnsafeMutablePointer<RustCallStatus>) -> T) throws -> T {
277 try makeRustCall(callback, errorHandler: errorHandler)
278 }
279
280 private func makeRustCall<T, E: Swift.Error>(
281 _ callback: (UnsafeMutablePointer<RustCallStatus>) -> T,
282 errorHandler: ((RustBuffer) throws -> E)?
283 ) throws -> T {
284 uniffiEnsureDemucsFfiInitialized()
285 var callStatus = RustCallStatus.init()
286 let returnedVal = callback(&callStatus)
287 try uniffiCheckCallStatus(callStatus: callStatus, errorHandler: errorHandler)
288 return returnedVal
289 }
290
291 private func uniffiCheckCallStatus<E: Swift.Error>(
292 callStatus: RustCallStatus,
293 errorHandler: ((RustBuffer) throws -> E)?
294 ) throws {
295 switch callStatus.code {
296 case CALL_SUCCESS:
297 return
298
299 case CALL_ERROR:
300 if let errorHandler = errorHandler {
301 throw try errorHandler(callStatus.errorBuf)
302 } else {
303 callStatus.errorBuf.deallocate()
304 throw UniffiInternalError.unexpectedRustCallError
305 }
306
307 case CALL_UNEXPECTED_ERROR:
308 // When the rust code sees a panic, it tries to construct a RustBuffer
309 // with the message. But if that code panics, then it just sends back
310 // an empty buffer.
311 if callStatus.errorBuf.len > 0 {
312 throw UniffiInternalError.rustPanic(try FfiConverterString.lift(callStatus.errorBuf))
313 } else {
314 callStatus.errorBuf.deallocate()
315 throw UniffiInternalError.rustPanic("Rust panic")
316 }
317
318 case CALL_CANCELLED:
319 fatalError("Cancellation not supported yet")
320
321 default:
322 throw UniffiInternalError.unexpectedRustCallStatusCode
323 }
324 }
325
326 private func uniffiTraitInterfaceCall<T>(
327 callStatus: UnsafeMutablePointer<RustCallStatus>,
328 makeCall: () throws -> T,
329 writeReturn: (T) -> ()
330 ) {
331 do {
332 try writeReturn(makeCall())
333 } catch let error {
334 callStatus.pointee.code = CALL_UNEXPECTED_ERROR
335 callStatus.pointee.errorBuf = FfiConverterString.lower(String(describing: error))
336 }
337 }
338
339 private func uniffiTraitInterfaceCallWithError<T, E>(
340 callStatus: UnsafeMutablePointer<RustCallStatus>,
341 makeCall: () throws -> T,
342 writeReturn: (T) -> (),
343 lowerError: (E) -> RustBuffer
344 ) {
345 do {
346 try writeReturn(makeCall())
347 } catch let error as E {
348 callStatus.pointee.code = CALL_ERROR
349 callStatus.pointee.errorBuf = lowerError(error)
350 } catch {
351 callStatus.pointee.code = CALL_UNEXPECTED_ERROR
352 callStatus.pointee.errorBuf = FfiConverterString.lower(String(describing: error))
353 }
354 }
355 // Initial value and increment amount for handles.
356 // These ensure that SWIFT handles always have the lowest bit set
357 fileprivate let UNIFFI_HANDLEMAP_INITIAL: UInt64 = 1
358 fileprivate let UNIFFI_HANDLEMAP_DELTA: UInt64 = 2
359
360 fileprivate final class UniffiHandleMap<T>: @unchecked Sendable {
361 // All mutation happens with this lock held, which is why we implement @unchecked Sendable.
362 private let lock = NSLock()
363 private var map: [UInt64: T] = [:]
364 private var currentHandle: UInt64 = UNIFFI_HANDLEMAP_INITIAL
365
366 func insert(obj: T) -> UInt64 {
367 lock.withLock {
368 return doInsert(obj)
369 }
370 }
371
372 // Low-level insert function, this assumes `lock` is held.
373 private func doInsert(_ obj: T) -> UInt64 {
374 let handle = currentHandle
375 currentHandle += UNIFFI_HANDLEMAP_DELTA
376 map[handle] = obj
377 return handle
378 }
379
380 func get(handle: UInt64) throws -> T {
381 try lock.withLock {
382 guard let obj = map[handle] else {
383 throw UniffiInternalError.unexpectedStaleHandle
384 }
385 return obj
386 }
387 }
388
389 func clone(handle: UInt64) throws -> UInt64 {
390 try lock.withLock {
391 guard let obj = map[handle] else {
392 throw UniffiInternalError.unexpectedStaleHandle
393 }
394 return doInsert(obj)
395 }
396 }
397
398 @discardableResult
399 func remove(handle: UInt64) throws -> T {
400 try lock.withLock {
401 guard let obj = map.removeValue(forKey: handle) else {
402 throw UniffiInternalError.unexpectedStaleHandle
403 }
404 return obj
405 }
406 }
407
408 var count: Int {
409 get {
410 map.count
411 }
412 }
413 }
414
415
416 // Public interface members begin here.
417 // Magic number for the Rust proxy to call using the same mechanism as every other method,
418 // to free the callback once it's dropped by Rust.
419 private let IDX_CALLBACK_FREE: Int32 = 0
420 // Callback return codes
421 private let UNIFFI_CALLBACK_SUCCESS: Int32 = 0
422 private let UNIFFI_CALLBACK_ERROR: Int32 = 1
423 private let UNIFFI_CALLBACK_UNEXPECTED_ERROR: Int32 = 2
424
425 #if swift(>=5.8)
426 @_documentation(visibility: private)
427 #endif
428 fileprivate struct FfiConverterUInt32: FfiConverterPrimitive {
429 typealias FfiType = UInt32
430 typealias SwiftType = UInt32
431
432 public static func read(from buf: inout (data: Data, offset: Data.Index)) throws -> UInt32 {
433 return try lift(readInt(&buf))
434 }
435
436 public static func write(_ value: SwiftType, into buf: inout [UInt8]) {
437 writeInt(&buf, lower(value))
438 }
439 }
440
441 #if swift(>=5.8)
442 @_documentation(visibility: private)
443 #endif
444 fileprivate struct FfiConverterUInt64: FfiConverterPrimitive {
445 typealias FfiType = UInt64
446 typealias SwiftType = UInt64
447
448 public static func read(from buf: inout (data: Data, offset: Data.Index)) throws -> UInt64 {
449 return try lift(readInt(&buf))
450 }
451
452 public static func write(_ value: SwiftType, into buf: inout [UInt8]) {
453 writeInt(&buf, lower(value))
454 }
455 }
456
457 #if swift(>=5.8)
458 @_documentation(visibility: private)
459 #endif
460 fileprivate struct FfiConverterFloat: FfiConverterPrimitive {
461 typealias FfiType = Float
462 typealias SwiftType = Float
463
464 public static func read(from buf: inout (data: Data, offset: Data.Index)) throws -> Float {
465 return try lift(readFloat(&buf))
466 }
467
468 public static func write(_ value: Float, into buf: inout [UInt8]) {
469 writeFloat(&buf, lower(value))
470 }
471 }
472
473 #if swift(>=5.8)
474 @_documentation(visibility: private)
475 #endif
476 fileprivate struct FfiConverterDouble: FfiConverterPrimitive {
477 typealias FfiType = Double
478 typealias SwiftType = Double
479
480 public static func read(from buf: inout (data: Data, offset: Data.Index)) throws -> Double {
481 return try lift(readDouble(&buf))
482 }
483
484 public static func write(_ value: Double, into buf: inout [UInt8]) {
485 writeDouble(&buf, lower(value))
486 }
487 }
488
489 #if swift(>=5.8)
490 @_documentation(visibility: private)
491 #endif
492 fileprivate struct FfiConverterBool : FfiConverter {
493 typealias FfiType = Int8
494 typealias SwiftType = Bool
495
496 public static func lift(_ value: Int8) throws -> Bool {
497 return value != 0
498 }
499
500 public static func lower(_ value: Bool) -> Int8 {
501 return value ? 1 : 0
502 }
503
504 public static func read(from buf: inout (data: Data, offset: Data.Index)) throws -> Bool {
505 return try lift(readInt(&buf))
506 }
507
508 public static func write(_ value: Bool, into buf: inout [UInt8]) {
509 writeInt(&buf, lower(value))
510 }
511 }
512
513 #if swift(>=5.8)
514 @_documentation(visibility: private)
515 #endif
516 fileprivate struct FfiConverterString: FfiConverter {
517 typealias SwiftType = String
518 typealias FfiType = RustBuffer
519
520 public static func lift(_ value: RustBuffer) throws -> String {
521 defer {
522 value.deallocate()
523 }
524 if value.data == nil {
525 return String()
526 }
527 let bytes = UnsafeBufferPointer<UInt8>(start: value.data!, count: Int(value.len))
528 return String(bytes: bytes, encoding: String.Encoding.utf8)!
529 }
530
531 public static func lower(_ value: String) -> RustBuffer {
532 return value.utf8CString.withUnsafeBufferPointer { ptr in
533 // The swift string gives us int8_t, we want uint8_t.
534 ptr.withMemoryRebound(to: UInt8.self) { ptr in
535 // The swift string gives us a trailing null byte, we don't want it.
536 let buf = UnsafeBufferPointer(rebasing: ptr.prefix(upTo: ptr.count - 1))
537 return RustBuffer.from(buf)
538 }
539 }
540 }
541
542 public static func read(from buf: inout (data: Data, offset: Data.Index)) throws -> String {
543 let len: Int32 = try readInt(&buf)
544 return String(bytes: try readBytes(&buf, count: Int(len)), encoding: String.Encoding.utf8)!
545 }
546
547 public static func write(_ value: String, into buf: inout [UInt8]) {
548 let len = Int32(value.utf8.count)
549 writeInt(&buf, len)
550 writeBytes(&buf, value.utf8)
551 }
552 }
553
554
555
556
557 /**
558 * Holds at most one loaded model.
559 *
560 * burn modules are `Send` but not `Sync` (parameters sit in a `OnceCell`), so
561 * the model lives behind a `Mutex` and each operation holds it for its whole
562 * run: loads, warmups and separations on one engine happen one at a time.
563 * The loaded model's identity is kept apart so status queries never wait on
564 * a separation.
565 */
566 public protocol FfiDemucsEngineProtocol: AnyObject, Sendable {
567
568 func isLoaded() -> Bool
569
570 /**
571 * Loads a downloaded model, replacing any model already loaded. Returns
572 * the load time in seconds. Fails with `NotCached` if the weights have
573 * not been downloaded yet.
574 */
575 func loadModel(model: FfiDemucsModel) async throws -> Double
576
577 func loadedModel() -> FfiDemucsModel?
578
579 /**
580 * Separates stereo PCM at any sample rate. Both channels must have the
581 * same, non-zero length; pass the same buffer twice for mono.
582 */
583 func separate(left: [Float], right: [Float], sampleRate: UInt32, listener: FfiSeparationListener) async throws -> [FfiStem]
584
585 /**
586 * Frees the loaded model. Returns `false` if nothing was loaded.
587 */
588 func unloadModel() async -> Bool
589
590 /**
591 * Runs a dummy separation so the first real one does not pay for shader
592 * compilation.
593 */
594 func warmup() async throws
595
596 }
597 /**
598 * Holds at most one loaded model.
599 *
600 * burn modules are `Send` but not `Sync` (parameters sit in a `OnceCell`), so
601 * the model lives behind a `Mutex` and each operation holds it for its whole
602 * run: loads, warmups and separations on one engine happen one at a time.
603 * The loaded model's identity is kept apart so status queries never wait on
604 * a separation.
605 */
606 open class FfiDemucsEngine: FfiDemucsEngineProtocol, @unchecked Sendable {
607 fileprivate let handle: UInt64
608
609 /// Used to instantiate a [FFIObject] without an actual handle, for fakes in tests, mostly.
610 #if swift(>=5.8)
611 @_documentation(visibility: private)
612 #endif
613 public struct NoHandle {
614 public init() {}
615 }
616
617 // TODO: We'd like this to be `private` but for Swifty reasons,
618 // we can't implement `FfiConverter` without making this `required` and we can't
619 // make it `required` without making it `public`.
620 #if swift(>=5.8)
621 @_documentation(visibility: private)
622 #endif
623 required public init(unsafeFromHandle handle: UInt64) {
624 self.handle = handle
625 }
626
627 // This constructor can be used to instantiate a fake object.
628 // - Parameter noHandle: Placeholder value so we can have a constructor separate from the default empty one that may be implemented for classes extending [FFIObject].
629 //
630 // - Warning:
631 // Any object instantiated with this constructor cannot be passed to an actual Rust-backed object. Since there isn't a backing handle the FFI lower functions will crash.
632 #if swift(>=5.8)
633 @_documentation(visibility: private)
634 #endif
635 public init(noHandle: NoHandle) {
636 self.handle = 0
637 }
638
639 #if swift(>=5.8)
640 @_documentation(visibility: private)
641 #endif
642 public func uniffiCloneHandle() -> UInt64 {
643 return try! rustCall { uniffi_demucs_ffi_fn_clone_ffidemucsengine(self.handle, $0) }
644 }
645 public convenience init() {
646 let handle =
647 try! rustCall() {
648 uniffi_demucs_ffi_fn_constructor_ffidemucsengine_new($0
649 )
650 }
651 self.init(unsafeFromHandle: handle)
652 }
653
654 deinit {
655 if handle == 0 {
656 // Mock objects have handle=0 don't try to free them
657 return
658 }
659
660 try! rustCall { uniffi_demucs_ffi_fn_free_ffidemucsengine(handle, $0) }
661 }
662
663
664
665
666 open func isLoaded() -> Bool {
667 return try! FfiConverterBool.lift(try! rustCall() {
668 uniffi_demucs_ffi_fn_method_ffidemucsengine_is_loaded(
669 self.uniffiCloneHandle(),$0
670 )
671 })
672 }
673
674 /**
675 * Loads a downloaded model, replacing any model already loaded. Returns
676 * the load time in seconds. Fails with `NotCached` if the weights have
677 * not been downloaded yet.
678 */
679 open func loadModel(model: FfiDemucsModel)async throws -> Double {
680 return
681 try await uniffiRustCallAsync(
682 rustFutureFunc: {
683 uniffi_demucs_ffi_fn_method_ffidemucsengine_load_model(
684 self.uniffiCloneHandle(),
685 FfiConverterTypeFfiDemucsModel_lower(model)
686 )
687 },
688 pollFunc: ffi_demucs_ffi_rust_future_poll_f64,
689 completeFunc: ffi_demucs_ffi_rust_future_complete_f64,
690 freeFunc: ffi_demucs_ffi_rust_future_free_f64,
691 liftFunc: FfiConverterDouble.lift,
692 errorHandler: FfiConverterTypeFfiDemucsError_lift
693 )
694 }
695
696 open func loadedModel() -> FfiDemucsModel? {
697 return try! FfiConverterOptionTypeFfiDemucsModel.lift(try! rustCall() {
698 uniffi_demucs_ffi_fn_method_ffidemucsengine_loaded_model(
699 self.uniffiCloneHandle(),$0
700 )
701 })
702 }
703
704 /**
705 * Separates stereo PCM at any sample rate. Both channels must have the
706 * same, non-zero length; pass the same buffer twice for mono.
707 */
708 open func separate(left: [Float], right: [Float], sampleRate: UInt32, listener: FfiSeparationListener)async throws -> [FfiStem] {
709 return
710 try await uniffiRustCallAsync(
711 rustFutureFunc: {
712 uniffi_demucs_ffi_fn_method_ffidemucsengine_separate(
713 self.uniffiCloneHandle(),
714 FfiConverterSequenceFloat.lower(left),FfiConverterSequenceFloat.lower(right),FfiConverterUInt32.lower(sampleRate),FfiConverterCallbackInterfaceFfiSeparationListener_lower(listener)
715 )
716 },
717 pollFunc: ffi_demucs_ffi_rust_future_poll_rust_buffer,
718 completeFunc: ffi_demucs_ffi_rust_future_complete_rust_buffer,
719 freeFunc: ffi_demucs_ffi_rust_future_free_rust_buffer,
720 liftFunc: FfiConverterSequenceTypeFfiStem.lift,
721 errorHandler: FfiConverterTypeFfiDemucsError_lift
722 )
723 }
724
725 /**
726 * Frees the loaded model. Returns `false` if nothing was loaded.
727 */
728 open func unloadModel()async -> Bool {
729 return
730 try! await uniffiRustCallAsync(
731 rustFutureFunc: {
732 uniffi_demucs_ffi_fn_method_ffidemucsengine_unload_model(
733 self.uniffiCloneHandle()
734
735 )
736 },
737 pollFunc: ffi_demucs_ffi_rust_future_poll_i8,
738 completeFunc: ffi_demucs_ffi_rust_future_complete_i8,
739 freeFunc: ffi_demucs_ffi_rust_future_free_i8,
740 liftFunc: FfiConverterBool.lift,
741 errorHandler: nil
742
743 )
744 }
745
746 /**
747 * Runs a dummy separation so the first real one does not pay for shader
748 * compilation.
749 */
750 open func warmup()async throws {
751 return
752 try await uniffiRustCallAsync(
753 rustFutureFunc: {
754 uniffi_demucs_ffi_fn_method_ffidemucsengine_warmup(
755 self.uniffiCloneHandle()
756
757 )
758 },
759 pollFunc: ffi_demucs_ffi_rust_future_poll_void,
760 completeFunc: ffi_demucs_ffi_rust_future_complete_void,
761 freeFunc: ffi_demucs_ffi_rust_future_free_void,
762 liftFunc: { $0 },
763 errorHandler: FfiConverterTypeFfiDemucsError_lift
764 )
765 }
766
767
768
769 }
770
771
772 #if swift(>=5.8)
773 @_documentation(visibility: private)
774 #endif
775 public struct FfiConverterTypeFfiDemucsEngine: FfiConverter {
776 typealias FfiType = UInt64
777 typealias SwiftType = FfiDemucsEngine
778
779 public static func lift(_ handle: UInt64) throws -> FfiDemucsEngine {
780 return FfiDemucsEngine(unsafeFromHandle: handle)
781 }
782
783 public static func lower(_ value: FfiDemucsEngine) -> UInt64 {
784 return value.uniffiCloneHandle()
785 }
786
787 public static func read(from buf: inout (data: Data, offset: Data.Index)) throws -> FfiDemucsEngine {
788 let handle: UInt64 = try readInt(&buf)
789 return try lift(handle)
790 }
791
792 public static func write(_ value: FfiDemucsEngine, into buf: inout [UInt8]) {
793 writeInt(&buf, lower(value))
794 }
795 }
796
797
798 #if swift(>=5.8)
799 @_documentation(visibility: private)
800 #endif
801 public func FfiConverterTypeFfiDemucsEngine_lift(_ handle: UInt64) throws -> FfiDemucsEngine {
802 return try FfiConverterTypeFfiDemucsEngine.lift(handle)
803 }
804
805 #if swift(>=5.8)
806 @_documentation(visibility: private)
807 #endif
808 public func FfiConverterTypeFfiDemucsEngine_lower(_ value: FfiDemucsEngine) -> UInt64 {
809 return FfiConverterTypeFfiDemucsEngine.lower(value)
810 }
811
812
813
814
815 public struct FfiDownloadProgress: Equatable, Hashable {
816 public var downloadedBytes: UInt64
817 /**
818 * From `Content-Length`, or the model's nominal size when the server
819 * does not send one.
820 */
821 public var totalBytes: UInt64
822 public var fraction: Double
823
824 // Default memberwise initializers are never public by default, so we
825 // declare one manually.
826 public init(downloadedBytes: UInt64,
827 /**
828 * From `Content-Length`, or the model's nominal size when the server
829 * does not send one.
830 */totalBytes: UInt64, fraction: Double) {
831 self.downloadedBytes = downloadedBytes
832 self.totalBytes = totalBytes
833 self.fraction = fraction
834 }
835
836
837
838
839 }
840
841 #if compiler(>=6)
842 extension FfiDownloadProgress: Sendable {}
843 #endif
844
845 #if swift(>=5.8)
846 @_documentation(visibility: private)
847 #endif
848 public struct FfiConverterTypeFfiDownloadProgress: FfiConverterRustBuffer {
849 public static func read(from buf: inout (data: Data, offset: Data.Index)) throws -> FfiDownloadProgress {
850 return
851 try FfiDownloadProgress(
852 downloadedBytes: FfiConverterUInt64.read(from: &buf),
853 totalBytes: FfiConverterUInt64.read(from: &buf),
854 fraction: FfiConverterDouble.read(from: &buf)
855 )
856 }
857
858 public static func write(_ value: FfiDownloadProgress, into buf: inout [UInt8]) {
859 FfiConverterUInt64.write(value.downloadedBytes, into: &buf)
860 FfiConverterUInt64.write(value.totalBytes, into: &buf)
861 FfiConverterDouble.write(value.fraction, into: &buf)
862 }
863 }
864
865
866 #if swift(>=5.8)
867 @_documentation(visibility: private)
868 #endif
869 public func FfiConverterTypeFfiDownloadProgress_lift(_ buf: RustBuffer) throws -> FfiDownloadProgress {
870 return try FfiConverterTypeFfiDownloadProgress.lift(buf)
871 }
872
873 #if swift(>=5.8)
874 @_documentation(visibility: private)
875 #endif
876 public func FfiConverterTypeFfiDownloadProgress_lower(_ value: FfiDownloadProgress) -> RustBuffer {
877 return FfiConverterTypeFfiDownloadProgress.lower(value)
878 }
879
880
881 public struct FfiModelMetadata: Equatable, Hashable {
882 public var model: FfiDemucsModel
883 public var id: String
884 public var label: String
885 public var description: String
886 public var sizeMb: UInt32
887 public var stems: [FfiStemKind]
888
889 // Default memberwise initializers are never public by default, so we
890 // declare one manually.
891 public init(model: FfiDemucsModel, id: String, label: String, description: String, sizeMb: UInt32, stems: [FfiStemKind]) {
892 self.model = model
893 self.id = id
894 self.label = label
895 self.description = description
896 self.sizeMb = sizeMb
897 self.stems = stems
898 }
899
900
901
902
903 }
904
905 #if compiler(>=6)
906 extension FfiModelMetadata: Sendable {}
907 #endif
908
909 #if swift(>=5.8)
910 @_documentation(visibility: private)
911 #endif
912 public struct FfiConverterTypeFfiModelMetadata: FfiConverterRustBuffer {
913 public static func read(from buf: inout (data: Data, offset: Data.Index)) throws -> FfiModelMetadata {
914 return
915 try FfiModelMetadata(
916 model: FfiConverterTypeFfiDemucsModel.read(from: &buf),
917 id: FfiConverterString.read(from: &buf),
918 label: FfiConverterString.read(from: &buf),
919 description: FfiConverterString.read(from: &buf),
920 sizeMb: FfiConverterUInt32.read(from: &buf),
921 stems: FfiConverterSequenceTypeFfiStemKind.read(from: &buf)
922 )
923 }
924
925 public static func write(_ value: FfiModelMetadata, into buf: inout [UInt8]) {
926 FfiConverterTypeFfiDemucsModel.write(value.model, into: &buf)
927 FfiConverterString.write(value.id, into: &buf)
928 FfiConverterString.write(value.label, into: &buf)
929 FfiConverterString.write(value.description, into: &buf)
930 FfiConverterUInt32.write(value.sizeMb, into: &buf)
931 FfiConverterSequenceTypeFfiStemKind.write(value.stems, into: &buf)
932 }
933 }
934
935
936 #if swift(>=5.8)
937 @_documentation(visibility: private)
938 #endif
939 public func FfiConverterTypeFfiModelMetadata_lift(_ buf: RustBuffer) throws -> FfiModelMetadata {
940 return try FfiConverterTypeFfiModelMetadata.lift(buf)
941 }
942
943 #if swift(>=5.8)
944 @_documentation(visibility: private)
945 #endif
946 public func FfiConverterTypeFfiModelMetadata_lower(_ value: FfiModelMetadata) -> RustBuffer {
947 return FfiConverterTypeFfiModelMetadata.lower(value)
948 }
949
950
951 public struct FfiSeparationProgress: Equatable, Hashable {
952 public var fraction: Double
953 public var chunkIndex: UInt64
954 public var totalChunks: UInt64
955
956 // Default memberwise initializers are never public by default, so we
957 // declare one manually.
958 public init(fraction: Double, chunkIndex: UInt64, totalChunks: UInt64) {
959 self.fraction = fraction
960 self.chunkIndex = chunkIndex
961 self.totalChunks = totalChunks
962 }
963
964
965
966
967 }
968
969 #if compiler(>=6)
970 extension FfiSeparationProgress: Sendable {}
971 #endif
972
973 #if swift(>=5.8)
974 @_documentation(visibility: private)
975 #endif
976 public struct FfiConverterTypeFfiSeparationProgress: FfiConverterRustBuffer {
977 public static func read(from buf: inout (data: Data, offset: Data.Index)) throws -> FfiSeparationProgress {
978 return
979 try FfiSeparationProgress(
980 fraction: FfiConverterDouble.read(from: &buf),
981 chunkIndex: FfiConverterUInt64.read(from: &buf),
982 totalChunks: FfiConverterUInt64.read(from: &buf)
983 )
984 }
985
986 public static func write(_ value: FfiSeparationProgress, into buf: inout [UInt8]) {
987 FfiConverterDouble.write(value.fraction, into: &buf)
988 FfiConverterUInt64.write(value.chunkIndex, into: &buf)
989 FfiConverterUInt64.write(value.totalChunks, into: &buf)
990 }
991 }
992
993
994 #if swift(>=5.8)
995 @_documentation(visibility: private)
996 #endif
997 public func FfiConverterTypeFfiSeparationProgress_lift(_ buf: RustBuffer) throws -> FfiSeparationProgress {
998 return try FfiConverterTypeFfiSeparationProgress.lift(buf)
999 }
1000
1001 #if swift(>=5.8)
1002 @_documentation(visibility: private)
1003 #endif
1004 public func FfiConverterTypeFfiSeparationProgress_lower(_ value: FfiSeparationProgress) -> RustBuffer {
1005 return FfiConverterTypeFfiSeparationProgress.lower(value)
1006 }
1007
1008
1009 /**
1010 * One separated source. `left` and `right` are at the input sample rate and
1011 * have the same length as the input channels.
1012 */
1013 public struct FfiStem: Equatable, Hashable {
1014 public var kind: FfiStemKind
1015 public var left: [Float]
1016 public var right: [Float]
1017
1018 // Default memberwise initializers are never public by default, so we
1019 // declare one manually.
1020 public init(kind: FfiStemKind, left: [Float], right: [Float]) {
1021 self.kind = kind
1022 self.left = left
1023 self.right = right
1024 }
1025
1026
1027
1028
1029 }
1030
1031 #if compiler(>=6)
1032 extension FfiStem: Sendable {}
1033 #endif
1034
1035 #if swift(>=5.8)
1036 @_documentation(visibility: private)
1037 #endif
1038 public struct FfiConverterTypeFfiStem: FfiConverterRustBuffer {
1039 public static func read(from buf: inout (data: Data, offset: Data.Index)) throws -> FfiStem {
1040 return
1041 try FfiStem(
1042 kind: FfiConverterTypeFfiStemKind.read(from: &buf),
1043 left: FfiConverterSequenceFloat.read(from: &buf),
1044 right: FfiConverterSequenceFloat.read(from: &buf)
1045 )
1046 }
1047
1048 public static func write(_ value: FfiStem, into buf: inout [UInt8]) {
1049 FfiConverterTypeFfiStemKind.write(value.kind, into: &buf)
1050 FfiConverterSequenceFloat.write(value.left, into: &buf)
1051 FfiConverterSequenceFloat.write(value.right, into: &buf)
1052 }
1053 }
1054
1055
1056 #if swift(>=5.8)
1057 @_documentation(visibility: private)
1058 #endif
1059 public func FfiConverterTypeFfiStem_lift(_ buf: RustBuffer) throws -> FfiStem {
1060 return try FfiConverterTypeFfiStem.lift(buf)
1061 }
1062
1063 #if swift(>=5.8)
1064 @_documentation(visibility: private)
1065 #endif
1066 public func FfiConverterTypeFfiStem_lower(_ value: FfiStem) -> RustBuffer {
1067 return FfiConverterTypeFfiStem.lower(value)
1068 }
1069
1070
1071 public enum FfiDemucsError: Swift.Error, Equatable, Hashable, Foundation.LocalizedError {
1072
1073
1074
1075 case Cancelled
1076 case NotLoaded
1077 case NotCached(modelId: String
1078 )
1079 case InvalidInput(reason: String
1080 )
1081 case Download(reason: String
1082 )
1083 case Io(reason: String
1084 )
1085 case Inference(reason: String
1086 )
1087
1088
1089
1090
1091
1092
1093 public var errorDescription: String? {
1094 String(reflecting: self)
1095 }
1096
1097 }
1098
1099 #if compiler(>=6)
1100 extension FfiDemucsError: Sendable {}
1101 #endif
1102
1103 #if swift(>=5.8)
1104 @_documentation(visibility: private)
1105 #endif
1106 public struct FfiConverterTypeFfiDemucsError: FfiConverterRustBuffer {
1107 typealias SwiftType = FfiDemucsError
1108
1109 public static func read(from buf: inout (data: Data, offset: Data.Index)) throws -> FfiDemucsError {
1110 let variant: Int32 = try readInt(&buf)
1111 switch variant {
1112
1113
1114
1115
1116 case 1: return .Cancelled
1117 case 2: return .NotLoaded
1118 case 3: return .NotCached(
1119 modelId: try FfiConverterString.read(from: &buf)
1120 )
1121 case 4: return .InvalidInput(
1122 reason: try FfiConverterString.read(from: &buf)
1123 )
1124 case 5: return .Download(
1125 reason: try FfiConverterString.read(from: &buf)
1126 )
1127 case 6: return .Io(
1128 reason: try FfiConverterString.read(from: &buf)
1129 )
1130 case 7: return .Inference(
1131 reason: try FfiConverterString.read(from: &buf)
1132 )
1133
1134 default: throw UniffiInternalError.unexpectedEnumCase
1135 }
1136 }
1137
1138 public static func write(_ value: FfiDemucsError, into buf: inout [UInt8]) {
1139 switch value {
1140
1141
1142
1143
1144
1145 case .Cancelled:
1146 writeInt(&buf, Int32(1))
1147
1148
1149 case .NotLoaded:
1150 writeInt(&buf, Int32(2))
1151
1152
1153 case let .NotCached(modelId):
1154 writeInt(&buf, Int32(3))
1155 FfiConverterString.write(modelId, into: &buf)
1156
1157
1158 case let .InvalidInput(reason):
1159 writeInt(&buf, Int32(4))
1160 FfiConverterString.write(reason, into: &buf)
1161
1162
1163 case let .Download(reason):
1164 writeInt(&buf, Int32(5))
1165 FfiConverterString.write(reason, into: &buf)
1166
1167
1168 case let .Io(reason):
1169 writeInt(&buf, Int32(6))
1170 FfiConverterString.write(reason, into: &buf)
1171
1172
1173 case let .Inference(reason):
1174 writeInt(&buf, Int32(7))
1175 FfiConverterString.write(reason, into: &buf)
1176
1177 }
1178 }
1179 }
1180
1181
1182 #if swift(>=5.8)
1183 @_documentation(visibility: private)
1184 #endif
1185 public func FfiConverterTypeFfiDemucsError_lift(_ buf: RustBuffer) throws -> FfiDemucsError {
1186 return try FfiConverterTypeFfiDemucsError.lift(buf)
1187 }
1188
1189 #if swift(>=5.8)
1190 @_documentation(visibility: private)
1191 #endif
1192 public func FfiConverterTypeFfiDemucsError_lower(_ value: FfiDemucsError) -> RustBuffer {
1193 return FfiConverterTypeFfiDemucsError.lower(value)
1194 }
1195
1196 // Note that we don't yet support `indirect` for enums.
1197 // See https://github.com/mozilla/uniffi-rs/issues/396 for further discussion.
1198 /**
1199 * Which model variant to download or load.
1200 *
1201 * `FineTuned` runs one sub-model per requested stem, so asking for fewer
1202 * stems is proportionally faster. It only knows drums, bass, other and
1203 * vocals; an empty list or any other stem is rejected at load time.
1204 */
1205
1206 public enum FfiDemucsModel: Equatable, Hashable {
1207
1208 case fourStem
1209 case sixStem
1210 case fineTuned(stems: [FfiStemKind]
1211 )
1212
1213
1214
1215
1216
1217 }
1218
1219 #if compiler(>=6)
1220 extension FfiDemucsModel: Sendable {}
1221 #endif
1222
1223 #if swift(>=5.8)
1224 @_documentation(visibility: private)
1225 #endif
1226 public struct FfiConverterTypeFfiDemucsModel: FfiConverterRustBuffer {
1227 typealias SwiftType = FfiDemucsModel
1228
1229 public static func read(from buf: inout (data: Data, offset: Data.Index)) throws -> FfiDemucsModel {
1230 let variant: Int32 = try readInt(&buf)
1231 switch variant {
1232
1233 case 1: return .fourStem
1234
1235 case 2: return .sixStem
1236
1237 case 3: return .fineTuned(stems: try FfiConverterSequenceTypeFfiStemKind.read(from: &buf)
1238 )
1239
1240 default: throw UniffiInternalError.unexpectedEnumCase
1241 }
1242 }
1243
1244 public static func write(_ value: FfiDemucsModel, into buf: inout [UInt8]) {
1245 switch value {
1246
1247
1248 case .fourStem:
1249 writeInt(&buf, Int32(1))
1250
1251
1252 case .sixStem:
1253 writeInt(&buf, Int32(2))
1254
1255
1256 case let .fineTuned(stems):
1257 writeInt(&buf, Int32(3))
1258 FfiConverterSequenceTypeFfiStemKind.write(stems, into: &buf)
1259
1260 }
1261 }
1262 }
1263
1264
1265 #if swift(>=5.8)
1266 @_documentation(visibility: private)
1267 #endif
1268 public func FfiConverterTypeFfiDemucsModel_lift(_ buf: RustBuffer) throws -> FfiDemucsModel {
1269 return try FfiConverterTypeFfiDemucsModel.lift(buf)
1270 }
1271
1272 #if swift(>=5.8)
1273 @_documentation(visibility: private)
1274 #endif
1275 public func FfiConverterTypeFfiDemucsModel_lower(_ value: FfiDemucsModel) -> RustBuffer {
1276 return FfiConverterTypeFfiDemucsModel.lower(value)
1277 }
1278
1279
1280 // Note that we don't yet support `indirect` for enums.
1281 // See https://github.com/mozilla/uniffi-rs/issues/396 for further discussion.
1282
1283 public enum FfiStemKind: Equatable, Hashable {
1284
1285 case drums
1286 case bass
1287 case other
1288 case vocals
1289 case guitar
1290 case piano
1291
1292
1293
1294
1295
1296 }
1297
1298 #if compiler(>=6)
1299 extension FfiStemKind: Sendable {}
1300 #endif
1301
1302 #if swift(>=5.8)
1303 @_documentation(visibility: private)
1304 #endif
1305 public struct FfiConverterTypeFfiStemKind: FfiConverterRustBuffer {
1306 typealias SwiftType = FfiStemKind
1307
1308 public static func read(from buf: inout (data: Data, offset: Data.Index)) throws -> FfiStemKind {
1309 let variant: Int32 = try readInt(&buf)
1310 switch variant {
1311
1312 case 1: return .drums
1313
1314 case 2: return .bass
1315
1316 case 3: return .other
1317
1318 case 4: return .vocals
1319
1320 case 5: return .guitar
1321
1322 case 6: return .piano
1323
1324 default: throw UniffiInternalError.unexpectedEnumCase
1325 }
1326 }
1327
1328 public static func write(_ value: FfiStemKind, into buf: inout [UInt8]) {
1329 switch value {
1330
1331
1332 case .drums:
1333 writeInt(&buf, Int32(1))
1334
1335
1336 case .bass:
1337 writeInt(&buf, Int32(2))
1338
1339
1340 case .other:
1341 writeInt(&buf, Int32(3))
1342
1343
1344 case .vocals:
1345 writeInt(&buf, Int32(4))
1346
1347
1348 case .guitar:
1349 writeInt(&buf, Int32(5))
1350
1351
1352 case .piano:
1353 writeInt(&buf, Int32(6))
1354
1355 }
1356 }
1357 }
1358
1359
1360 #if swift(>=5.8)
1361 @_documentation(visibility: private)
1362 #endif
1363 public func FfiConverterTypeFfiStemKind_lift(_ buf: RustBuffer) throws -> FfiStemKind {
1364 return try FfiConverterTypeFfiStemKind.lift(buf)
1365 }
1366
1367 #if swift(>=5.8)
1368 @_documentation(visibility: private)
1369 #endif
1370 public func FfiConverterTypeFfiStemKind_lower(_ value: FfiStemKind) -> RustBuffer {
1371 return FfiConverterTypeFfiStemKind.lower(value)
1372 }
1373
1374
1375
1376
1377
1378 /**
1379 * Called from a background thread. Return `false` to cancel the download.
1380 */
1381 public protocol FfiDownloadListener: AnyObject, Sendable {
1382
1383 func onProgress(progress: FfiDownloadProgress) -> Bool
1384
1385 }
1386
1387
1388 // Put the implementation in a struct so we don't pollute the top-level namespace
1389 fileprivate struct UniffiCallbackInterfaceFfiDownloadListener {
1390
1391 // Create the VTable using a series of closures.
1392 // Swift automatically converts these into C callback functions.
1393 //
1394 // This creates 1-element array, since this seems to be the only way to construct a const
1395 // pointer that we can pass to the Rust code.
1396 static let vtable: [UniffiVTableCallbackInterfaceFfiDownloadListener] = [UniffiVTableCallbackInterfaceFfiDownloadListener(
1397 uniffiFree: { (uniffiHandle: UInt64) -> () in
1398 do {
1399 try FfiConverterCallbackInterfaceFfiDownloadListener.handleMap.remove(handle: uniffiHandle)
1400 } catch {
1401 print("Uniffi callback interface FfiDownloadListener: handle missing in uniffiFree")
1402 }
1403 },
1404 uniffiClone: { (uniffiHandle: UInt64) -> UInt64 in
1405 do {
1406 return try FfiConverterCallbackInterfaceFfiDownloadListener.handleMap.clone(handle: uniffiHandle)
1407 } catch {
1408 fatalError("Uniffi callback interface FfiDownloadListener: handle missing in uniffiClone")
1409 }
1410 },
1411 onProgress: { (
1412 uniffiHandle: UInt64,
1413 progress: RustBuffer,
1414 uniffiOutReturn: UnsafeMutablePointer<Int8>,
1415 uniffiCallStatus: UnsafeMutablePointer<RustCallStatus>
1416 ) in
1417 let makeCall = {
1418 () throws -> Bool in
1419 guard let uniffiObj = try? FfiConverterCallbackInterfaceFfiDownloadListener.handleMap.get(handle: uniffiHandle) else {
1420 throw UniffiInternalError.unexpectedStaleHandle
1421 }
1422 return uniffiObj.onProgress(
1423 progress: try FfiConverterTypeFfiDownloadProgress_lift(progress)
1424 )
1425 }
1426
1427
1428 let writeReturn = { uniffiOutReturn.pointee = FfiConverterBool.lower($0) }
1429 uniffiTraitInterfaceCall(
1430 callStatus: uniffiCallStatus,
1431 makeCall: makeCall,
1432 writeReturn: writeReturn
1433 )
1434 }
1435 )]
1436 }
1437
1438 private func uniffiCallbackInitFfiDownloadListener() {
1439 uniffi_demucs_ffi_fn_init_callback_vtable_ffidownloadlistener(UniffiCallbackInterfaceFfiDownloadListener.vtable)
1440 }
1441
1442 // FfiConverter protocol for callback interfaces
1443 #if swift(>=5.8)
1444 @_documentation(visibility: private)
1445 #endif
1446 fileprivate struct FfiConverterCallbackInterfaceFfiDownloadListener {
1447 fileprivate static let handleMap = UniffiHandleMap<FfiDownloadListener>()
1448 }
1449
1450 #if swift(>=5.8)
1451 @_documentation(visibility: private)
1452 #endif
1453 extension FfiConverterCallbackInterfaceFfiDownloadListener : FfiConverter {
1454 typealias SwiftType = FfiDownloadListener
1455 typealias FfiType = UInt64
1456
1457 #if swift(>=5.8)
1458 @_documentation(visibility: private)
1459 #endif
1460 public static func lift(_ handle: UInt64) throws -> SwiftType {
1461 try handleMap.get(handle: handle)
1462 }
1463
1464 #if swift(>=5.8)
1465 @_documentation(visibility: private)
1466 #endif
1467 public static func read(from buf: inout (data: Data, offset: Data.Index)) throws -> SwiftType {
1468 let handle: UInt64 = try readInt(&buf)
1469 return try lift(handle)
1470 }
1471
1472 #if swift(>=5.8)
1473 @_documentation(visibility: private)
1474 #endif
1475 public static func lower(_ v: SwiftType) -> UInt64 {
1476 return handleMap.insert(obj: v)
1477 }
1478
1479 #if swift(>=5.8)
1480 @_documentation(visibility: private)
1481 #endif
1482 public static func write(_ v: SwiftType, into buf: inout [UInt8]) {
1483 writeInt(&buf, lower(v))
1484 }
1485 }
1486
1487
1488 #if swift(>=5.8)
1489 @_documentation(visibility: private)
1490 #endif
1491 public func FfiConverterCallbackInterfaceFfiDownloadListener_lift(_ handle: UInt64) throws -> FfiDownloadListener {
1492 return try FfiConverterCallbackInterfaceFfiDownloadListener.lift(handle)
1493 }
1494
1495 #if swift(>=5.8)
1496 @_documentation(visibility: private)
1497 #endif
1498 public func FfiConverterCallbackInterfaceFfiDownloadListener_lower(_ v: FfiDownloadListener) -> UInt64 {
1499 return FfiConverterCallbackInterfaceFfiDownloadListener.lower(v)
1500 }
1501
1502
1503
1504
1505 /**
1506 * Called from a background thread. Return `false` to cancel; cancellation
1507 * takes effect at the next chunk boundary (every ~7.8 s of audio), so audio
1508 * short enough to fit in one chunk always runs to completion.
1509 */
1510 public protocol FfiSeparationListener: AnyObject, Sendable {
1511
1512 func onProgress(progress: FfiSeparationProgress) -> Bool
1513
1514 }
1515
1516
1517 // Put the implementation in a struct so we don't pollute the top-level namespace
1518 fileprivate struct UniffiCallbackInterfaceFfiSeparationListener {
1519
1520 // Create the VTable using a series of closures.
1521 // Swift automatically converts these into C callback functions.
1522 //
1523 // This creates 1-element array, since this seems to be the only way to construct a const
1524 // pointer that we can pass to the Rust code.
1525 static let vtable: [UniffiVTableCallbackInterfaceFfiSeparationListener] = [UniffiVTableCallbackInterfaceFfiSeparationListener(
1526 uniffiFree: { (uniffiHandle: UInt64) -> () in
1527 do {
1528 try FfiConverterCallbackInterfaceFfiSeparationListener.handleMap.remove(handle: uniffiHandle)
1529 } catch {
1530 print("Uniffi callback interface FfiSeparationListener: handle missing in uniffiFree")
1531 }
1532 },
1533 uniffiClone: { (uniffiHandle: UInt64) -> UInt64 in
1534 do {
1535 return try FfiConverterCallbackInterfaceFfiSeparationListener.handleMap.clone(handle: uniffiHandle)
1536 } catch {
1537 fatalError("Uniffi callback interface FfiSeparationListener: handle missing in uniffiClone")
1538 }
1539 },
1540 onProgress: { (
1541 uniffiHandle: UInt64,
1542 progress: RustBuffer,
1543 uniffiOutReturn: UnsafeMutablePointer<Int8>,
1544 uniffiCallStatus: UnsafeMutablePointer<RustCallStatus>
1545 ) in
1546 let makeCall = {
1547 () throws -> Bool in
1548 guard let uniffiObj = try? FfiConverterCallbackInterfaceFfiSeparationListener.handleMap.get(handle: uniffiHandle) else {
1549 throw UniffiInternalError.unexpectedStaleHandle
1550 }
1551 return uniffiObj.onProgress(
1552 progress: try FfiConverterTypeFfiSeparationProgress_lift(progress)
1553 )
1554 }
1555
1556
1557 let writeReturn = { uniffiOutReturn.pointee = FfiConverterBool.lower($0) }
1558 uniffiTraitInterfaceCall(
1559 callStatus: uniffiCallStatus,
1560 makeCall: makeCall,
1561 writeReturn: writeReturn
1562 )
1563 }
1564 )]
1565 }
1566
1567 private func uniffiCallbackInitFfiSeparationListener() {
1568 uniffi_demucs_ffi_fn_init_callback_vtable_ffiseparationlistener(UniffiCallbackInterfaceFfiSeparationListener.vtable)
1569 }
1570
1571 // FfiConverter protocol for callback interfaces
1572 #if swift(>=5.8)
1573 @_documentation(visibility: private)
1574 #endif
1575 fileprivate struct FfiConverterCallbackInterfaceFfiSeparationListener {
1576 fileprivate static let handleMap = UniffiHandleMap<FfiSeparationListener>()
1577 }
1578
1579 #if swift(>=5.8)
1580 @_documentation(visibility: private)
1581 #endif
1582 extension FfiConverterCallbackInterfaceFfiSeparationListener : FfiConverter {
1583 typealias SwiftType = FfiSeparationListener
1584 typealias FfiType = UInt64
1585
1586 #if swift(>=5.8)
1587 @_documentation(visibility: private)
1588 #endif
1589 public static func lift(_ handle: UInt64) throws -> SwiftType {
1590 try handleMap.get(handle: handle)
1591 }
1592
1593 #if swift(>=5.8)
1594 @_documentation(visibility: private)
1595 #endif
1596 public static func read(from buf: inout (data: Data, offset: Data.Index)) throws -> SwiftType {
1597 let handle: UInt64 = try readInt(&buf)
1598 return try lift(handle)
1599 }
1600
1601 #if swift(>=5.8)
1602 @_documentation(visibility: private)
1603 #endif
1604 public static func lower(_ v: SwiftType) -> UInt64 {
1605 return handleMap.insert(obj: v)
1606 }
1607
1608 #if swift(>=5.8)
1609 @_documentation(visibility: private)
1610 #endif
1611 public static func write(_ v: SwiftType, into buf: inout [UInt8]) {
1612 writeInt(&buf, lower(v))
1613 }
1614 }
1615
1616
1617 #if swift(>=5.8)
1618 @_documentation(visibility: private)
1619 #endif
1620 public func FfiConverterCallbackInterfaceFfiSeparationListener_lift(_ handle: UInt64) throws -> FfiSeparationListener {
1621 return try FfiConverterCallbackInterfaceFfiSeparationListener.lift(handle)
1622 }
1623
1624 #if swift(>=5.8)
1625 @_documentation(visibility: private)
1626 #endif
1627 public func FfiConverterCallbackInterfaceFfiSeparationListener_lower(_ v: FfiSeparationListener) -> UInt64 {
1628 return FfiConverterCallbackInterfaceFfiSeparationListener.lower(v)
1629 }
1630
1631 #if swift(>=5.8)
1632 @_documentation(visibility: private)
1633 #endif
1634 fileprivate struct FfiConverterOptionString: FfiConverterRustBuffer {
1635 typealias SwiftType = String?
1636
1637 public static func write(_ value: SwiftType, into buf: inout [UInt8]) {
1638 guard let value = value else {
1639 writeInt(&buf, Int8(0))
1640 return
1641 }
1642 writeInt(&buf, Int8(1))
1643 FfiConverterString.write(value, into: &buf)
1644 }
1645
1646 public static func read(from buf: inout (data: Data, offset: Data.Index)) throws -> SwiftType {
1647 switch try readInt(&buf) as Int8 {
1648 case 0: return nil
1649 case 1: return try FfiConverterString.read(from: &buf)
1650 default: throw UniffiInternalError.unexpectedOptionalTag
1651 }
1652 }
1653 }
1654
1655 #if swift(>=5.8)
1656 @_documentation(visibility: private)
1657 #endif
1658 fileprivate struct FfiConverterOptionTypeFfiDemucsModel: FfiConverterRustBuffer {
1659 typealias SwiftType = FfiDemucsModel?
1660
1661 public static func write(_ value: SwiftType, into buf: inout [UInt8]) {
1662 guard let value = value else {
1663 writeInt(&buf, Int8(0))
1664 return
1665 }
1666 writeInt(&buf, Int8(1))
1667 FfiConverterTypeFfiDemucsModel.write(value, into: &buf)
1668 }
1669
1670 public static func read(from buf: inout (data: Data, offset: Data.Index)) throws -> SwiftType {
1671 switch try readInt(&buf) as Int8 {
1672 case 0: return nil
1673 case 1: return try FfiConverterTypeFfiDemucsModel.read(from: &buf)
1674 default: throw UniffiInternalError.unexpectedOptionalTag
1675 }
1676 }
1677 }
1678
1679 #if swift(>=5.8)
1680 @_documentation(visibility: private)
1681 #endif
1682 fileprivate struct FfiConverterSequenceFloat: FfiConverterRustBuffer {
1683 typealias SwiftType = [Float]
1684
1685 public static func write(_ value: [Float], into buf: inout [UInt8]) {
1686 let len = Int32(value.count)
1687 writeInt(&buf, len)
1688 for item in value {
1689 FfiConverterFloat.write(item, into: &buf)
1690 }
1691 }
1692
1693 public static func read(from buf: inout (data: Data, offset: Data.Index)) throws -> [Float] {
1694 let len: Int32 = try readInt(&buf)
1695 var seq = [Float]()
1696 seq.reserveCapacity(Int(len))
1697 for _ in 0 ..< len {
1698 seq.append(try FfiConverterFloat.read(from: &buf))
1699 }
1700 return seq
1701 }
1702 }
1703
1704 #if swift(>=5.8)
1705 @_documentation(visibility: private)
1706 #endif
1707 fileprivate struct FfiConverterSequenceTypeFfiModelMetadata: FfiConverterRustBuffer {
1708 typealias SwiftType = [FfiModelMetadata]
1709
1710 public static func write(_ value: [FfiModelMetadata], into buf: inout [UInt8]) {
1711 let len = Int32(value.count)
1712 writeInt(&buf, len)
1713 for item in value {
1714 FfiConverterTypeFfiModelMetadata.write(item, into: &buf)
1715 }
1716 }
1717
1718 public static func read(from buf: inout (data: Data, offset: Data.Index)) throws -> [FfiModelMetadata] {
1719 let len: Int32 = try readInt(&buf)
1720 var seq = [FfiModelMetadata]()
1721 seq.reserveCapacity(Int(len))
1722 for _ in 0 ..< len {
1723 seq.append(try FfiConverterTypeFfiModelMetadata.read(from: &buf))
1724 }
1725 return seq
1726 }
1727 }
1728
1729 #if swift(>=5.8)
1730 @_documentation(visibility: private)
1731 #endif
1732 fileprivate struct FfiConverterSequenceTypeFfiStem: FfiConverterRustBuffer {
1733 typealias SwiftType = [FfiStem]
1734
1735 public static func write(_ value: [FfiStem], into buf: inout [UInt8]) {
1736 let len = Int32(value.count)
1737 writeInt(&buf, len)
1738 for item in value {
1739 FfiConverterTypeFfiStem.write(item, into: &buf)
1740 }
1741 }
1742
1743 public static func read(from buf: inout (data: Data, offset: Data.Index)) throws -> [FfiStem] {
1744 let len: Int32 = try readInt(&buf)
1745 var seq = [FfiStem]()
1746 seq.reserveCapacity(Int(len))
1747 for _ in 0 ..< len {
1748 seq.append(try FfiConverterTypeFfiStem.read(from: &buf))
1749 }
1750 return seq
1751 }
1752 }
1753
1754 #if swift(>=5.8)
1755 @_documentation(visibility: private)
1756 #endif
1757 fileprivate struct FfiConverterSequenceTypeFfiStemKind: FfiConverterRustBuffer {
1758 typealias SwiftType = [FfiStemKind]
1759
1760 public static func write(_ value: [FfiStemKind], into buf: inout [UInt8]) {
1761 let len = Int32(value.count)
1762 writeInt(&buf, len)
1763 for item in value {
1764 FfiConverterTypeFfiStemKind.write(item, into: &buf)
1765 }
1766 }
1767
1768 public static func read(from buf: inout (data: Data, offset: Data.Index)) throws -> [FfiStemKind] {
1769 let len: Int32 = try readInt(&buf)
1770 var seq = [FfiStemKind]()
1771 seq.reserveCapacity(Int(len))
1772 for _ in 0 ..< len {
1773 seq.append(try FfiConverterTypeFfiStemKind.read(from: &buf))
1774 }
1775 return seq
1776 }
1777 }
1778 private let UNIFFI_RUST_FUTURE_POLL_READY: Int8 = 0
1779 private let UNIFFI_RUST_FUTURE_POLL_WAKE: Int8 = 1
1780
1781 fileprivate let uniffiContinuationHandleMap = UniffiHandleMap<UnsafeContinuation<Int8, Never>>()
1782
1783 fileprivate func uniffiRustCallAsync<F, T>(
1784 rustFutureFunc: () -> UInt64,
1785 pollFunc: (UInt64, @escaping UniffiRustFutureContinuationCallback, UInt64) -> (),
1786 completeFunc: (UInt64, UnsafeMutablePointer<RustCallStatus>) -> F,
1787 freeFunc: (UInt64) -> (),
1788 liftFunc: (F) throws -> T,
1789 errorHandler: ((RustBuffer) throws -> Swift.Error)?
1790 ) async throws -> T {
1791 // Make sure to call the ensure init function since future creation doesn't have a
1792 // RustCallStatus param, so doesn't use makeRustCall()
1793 uniffiEnsureDemucsFfiInitialized()
1794 let rustFuture = rustFutureFunc()
1795 defer {
1796 freeFunc(rustFuture)
1797 }
1798 var pollResult: Int8;
1799 repeat {
1800 pollResult = await withUnsafeContinuation {
1801 pollFunc(
1802 rustFuture,
1803 { handle, pollResult in
1804 uniffiFutureContinuationCallback(handle: handle, pollResult: pollResult)
1805 },
1806 uniffiContinuationHandleMap.insert(obj: $0)
1807 )
1808 }
1809 } while pollResult != UNIFFI_RUST_FUTURE_POLL_READY
1810
1811 return try liftFunc(makeRustCall(
1812 { completeFunc(rustFuture, $0) },
1813 errorHandler: errorHandler
1814 ))
1815 }
1816
1817 // Callback handlers for an async calls. These are invoked by Rust when the future is ready. They
1818 // lift the return value or error and resume the suspended function.
1819 fileprivate func uniffiFutureContinuationCallback(handle: UInt64, pollResult: Int8) {
1820 if let continuation = try? uniffiContinuationHandleMap.remove(handle: handle) {
1821 continuation.resume(returning: pollResult)
1822 } else {
1823 print("uniffiFutureContinuationCallback invalid handle")
1824 }
1825 }
1826 public func allModels() -> [FfiModelMetadata] {
1827 return try! FfiConverterSequenceTypeFfiModelMetadata.lift(try! rustCall() {
1828 uniffi_demucs_ffi_fn_func_all_models($0
1829 )
1830 })
1831 }
1832 public func cachedModelPath(model: FfiDemucsModel) -> String? {
1833 return try! FfiConverterOptionString.lift(try! rustCall() {
1834 uniffi_demucs_ffi_fn_func_cached_model_path(
1835 FfiConverterTypeFfiDemucsModel_lower(model),$0
1836 )
1837 })
1838 }
1839 /**
1840 * Samples per chunk at 44.1 kHz.
1841 */
1842 public func chunkLength() -> UInt64 {
1843 return try! FfiConverterUInt64.lift(try! rustCall() {
1844 uniffi_demucs_ffi_fn_func_chunk_length($0
1845 )
1846 })
1847 }
1848 /**
1849 * Sets where model weights are stored. Sandboxed apps should call this once
1850 * at launch with a directory inside their container. Without it, weights go
1851 * to the platform cache directory under `demucs-rs/`.
1852 */
1853 public func configureCacheDir(path: String) {try! rustCall() {
1854 uniffi_demucs_ffi_fn_func_configure_cache_dir(
1855 FfiConverterString.lower(path),$0
1856 )
1857 }
1858 }
1859 /**
1860 * Returns `true` if a file was removed.
1861 */
1862 public func deleteCachedModel(model: FfiDemucsModel) -> Bool {
1863 return try! FfiConverterBool.lift(try! rustCall() {
1864 uniffi_demucs_ffi_fn_func_delete_cached_model(
1865 FfiConverterTypeFfiDemucsModel_lower(model),$0
1866 )
1867 })
1868 }
1869 /**
1870 * Downloads the model's weights from HuggingFace into the cache directory.
1871 * Returns immediately if they are already there.
1872 */
1873 public func downloadModel(model: FfiDemucsModel, listener: FfiDownloadListener)async throws {
1874 return
1875 try await uniffiRustCallAsync(
1876 rustFutureFunc: {
1877 uniffi_demucs_ffi_fn_func_download_model(FfiConverterTypeFfiDemucsModel_lower(model),FfiConverterCallbackInterfaceFfiDownloadListener_lower(listener)
1878 )
1879 },
1880 pollFunc: ffi_demucs_ffi_rust_future_poll_void,
1881 completeFunc: ffi_demucs_ffi_rust_future_complete_void,
1882 freeFunc: ffi_demucs_ffi_rust_future_free_void,
1883 liftFunc: { $0 },
1884 errorHandler: FfiConverterTypeFfiDemucsError_lift
1885 )
1886 }
1887 /**
1888 * All fine-tuned stem selections share one weights file, so this answers the
1889 * same for every `FineTuned` value.
1890 */
1891 public func isModelCached(model: FfiDemucsModel) -> Bool {
1892 return try! FfiConverterBool.lift(try! rustCall() {
1893 uniffi_demucs_ffi_fn_func_is_model_cached(
1894 FfiConverterTypeFfiDemucsModel_lower(model),$0
1895 )
1896 })
1897 }
1898 public func modelMetadata(model: FfiDemucsModel) -> FfiModelMetadata {
1899 return try! FfiConverterTypeFfiModelMetadata_lift(try! rustCall() {
1900 uniffi_demucs_ffi_fn_func_model_metadata(
1901 FfiConverterTypeFfiDemucsModel_lower(model),$0
1902 )
1903 })
1904 }
1905 /**
1906 * How many chunks `separate` will split this many input samples into, for
1907 * sizing progress UI up front. `sample_rate` is the input rate; audio is
1908 * chunked after resampling to 44.1 kHz.
1909 */
1910 public func numChunks(nSamples: UInt64, sampleRate: UInt32) -> UInt64 {
1911 return try! FfiConverterUInt64.lift(try! rustCall() {
1912 uniffi_demucs_ffi_fn_func_num_chunks(
1913 FfiConverterUInt64.lower(nSamples),
1914 FfiConverterUInt32.lower(sampleRate),$0
1915 )
1916 })
1917 }
1918
1919 private enum InitializationResult {
1920 case ok
1921 case contractVersionMismatch
1922 case apiChecksumMismatch
1923 }
1924 // Use a global variable to perform the versioning checks. Swift ensures that
1925 // the code inside is only computed once.
1926 private let initializationResult: InitializationResult = {
1927 // Get the bindings contract version from our ComponentInterface
1928 let bindings_contract_version = 30
1929 // Get the scaffolding contract version by calling the into the dylib
1930 let scaffolding_contract_version = ffi_demucs_ffi_uniffi_contract_version()
1931 if bindings_contract_version != scaffolding_contract_version {
1932 return InitializationResult.contractVersionMismatch
1933 }
1934 if (uniffi_demucs_ffi_checksum_func_all_models() != 35841) {
1935 return InitializationResult.apiChecksumMismatch
1936 }
1937 if (uniffi_demucs_ffi_checksum_func_cached_model_path() != 60660) {
1938 return InitializationResult.apiChecksumMismatch
1939 }
1940 if (uniffi_demucs_ffi_checksum_func_chunk_length() != 30511) {
1941 return InitializationResult.apiChecksumMismatch
1942 }
1943 if (uniffi_demucs_ffi_checksum_func_configure_cache_dir() != 17121) {
1944 return InitializationResult.apiChecksumMismatch
1945 }
1946 if (uniffi_demucs_ffi_checksum_func_delete_cached_model() != 32733) {
1947 return InitializationResult.apiChecksumMismatch
1948 }
1949 if (uniffi_demucs_ffi_checksum_func_download_model() != 18057) {
1950 return InitializationResult.apiChecksumMismatch
1951 }
1952 if (uniffi_demucs_ffi_checksum_func_is_model_cached() != 62970) {
1953 return InitializationResult.apiChecksumMismatch
1954 }
1955 if (uniffi_demucs_ffi_checksum_func_model_metadata() != 60733) {
1956 return InitializationResult.apiChecksumMismatch
1957 }
1958 if (uniffi_demucs_ffi_checksum_func_num_chunks() != 4306) {
1959 return InitializationResult.apiChecksumMismatch
1960 }
1961 if (uniffi_demucs_ffi_checksum_method_ffidemucsengine_is_loaded() != 13782) {
1962 return InitializationResult.apiChecksumMismatch
1963 }
1964 if (uniffi_demucs_ffi_checksum_method_ffidemucsengine_load_model() != 18700) {
1965 return InitializationResult.apiChecksumMismatch
1966 }
1967 if (uniffi_demucs_ffi_checksum_method_ffidemucsengine_loaded_model() != 27072) {
1968 return InitializationResult.apiChecksumMismatch
1969 }
1970 if (uniffi_demucs_ffi_checksum_method_ffidemucsengine_separate() != 27889) {
1971 return InitializationResult.apiChecksumMismatch
1972 }
1973 if (uniffi_demucs_ffi_checksum_method_ffidemucsengine_unload_model() != 21923) {
1974 return InitializationResult.apiChecksumMismatch
1975 }
1976 if (uniffi_demucs_ffi_checksum_method_ffidemucsengine_warmup() != 4128) {
1977 return InitializationResult.apiChecksumMismatch
1978 }
1979 if (uniffi_demucs_ffi_checksum_constructor_ffidemucsengine_new() != 48414) {
1980 return InitializationResult.apiChecksumMismatch
1981 }
1982 if (uniffi_demucs_ffi_checksum_method_ffidownloadlistener_on_progress() != 42698) {
1983 return InitializationResult.apiChecksumMismatch
1984 }
1985 if (uniffi_demucs_ffi_checksum_method_ffiseparationlistener_on_progress() != 32252) {
1986 return InitializationResult.apiChecksumMismatch
1987 }
1988
1989 uniffiCallbackInitFfiDownloadListener()
1990 uniffiCallbackInitFfiSeparationListener()
1991 return InitializationResult.ok
1992 }()
1993
1994 // Make the ensure init function public so that other modules which have external type references to
1995 // our types can call it.
1996 public func uniffiEnsureDemucsFfiInitialized() {
1997 switch initializationResult {
1998 case .ok:
1999 break
2000 case .contractVersionMismatch:
2001 fatalError("UniFFI contract version mismatch: try cleaning and rebuilding your project")
2002 case .apiChecksumMismatch:
2003 fatalError("UniFFI API checksum mismatch: try cleaning and rebuilding your project")
2004 }
2005 }
2006
2007 // swiftlint:enable all