Branchwell

PulseCanvas / app / Sources / PulseCanvas / ProjectMEngine.swift

1#if !STORE_BUILD
2import Foundation
3import Darwin
4import OpenGL
5import OpenGL.GL3
6import IOSurface
7import CoreVideo
8@preconcurrency import Metal
9
10private final class ProjectMAPI {
11 typealias Handle = UnsafeMutableRawPointer
12 let library: UnsafeMutableRawPointer
13 let create: @convention(c) () -> Handle?
14 let destroy: @convention(c) (Handle) -> Void
15 let load: @convention(c) (Handle, UnsafePointer<CChar>, Bool) -> Void
16 let loadData: @convention(c) (Handle, UnsafePointer<CChar>, Bool) -> Void
17 let size: @convention(c) (Handle, Int, Int) -> Void
18 let frameTime: @convention(c) (Handle, Double) -> Void
19 let fps: @convention(c) (Handle, Int32) -> Void
20 let lock: @convention(c) (Handle, Bool) -> Void
21 let clean: @convention(c) (Handle, Bool) -> Void
22 let pcm: @convention(c) (Handle, UnsafePointer<Float>, UInt32, Int32) -> Void
23 let render: @convention(c) (Handle, UInt32) -> Void
24 let texturePaths: @convention(c) (Handle, UnsafePointer<UnsafePointer<CChar>?>, Int) -> Void
25 typealias Failure = @convention(c) (UnsafePointer<CChar>?, UnsafePointer<CChar>?, UnsafeMutableRawPointer?) -> Void
26 let failure: @convention(c) (Handle, Failure?, UnsafeMutableRawPointer?) -> Void
27
28 init() throws {
29 let candidates = [Bundle.main.privateFrameworksURL?.appendingPathComponent("libprojectM.dylib"),
30 URL(fileURLWithPath: FileManager.default.currentDirectoryPath).appendingPathComponent(".build/projectm/install/lib/libprojectM-4.4.2.0.dylib")]
31 guard let path = candidates.compactMap({$0}).first(where: {FileManager.default.fileExists(atPath: $0.path)}),
32 let library = dlopen(path.path, RTLD_NOW | RTLD_LOCAL) else { throw ProjectMError("ProjectM engine is missing. Build with scripts/build-projectm.sh.") }
33 self.library = library
34 func symbol<T>(_ name: String, _ type: T.Type) throws -> T {
35 guard let address = dlsym(library, name) else { throw ProjectMError("ProjectM API is missing \(name)") }
36 return unsafeBitCast(address, to: type)
37 }
38 create = try symbol("projectm_create", (@convention(c) () -> Handle?).self)
39 destroy = try symbol("projectm_destroy", (@convention(c) (Handle) -> Void).self)
40 load = try symbol("projectm_load_preset_file", (@convention(c) (Handle, UnsafePointer<CChar>, Bool) -> Void).self)
41 loadData = try symbol("projectm_load_preset_data", (@convention(c) (Handle, UnsafePointer<CChar>, Bool) -> Void).self)
42 size = try symbol("projectm_set_window_size", (@convention(c) (Handle, Int, Int) -> Void).self)
43 frameTime = try symbol("projectm_set_frame_time", (@convention(c) (Handle, Double) -> Void).self)
44 fps = try symbol("projectm_set_fps", (@convention(c) (Handle, Int32) -> Void).self)
45 lock = try symbol("projectm_set_preset_locked", (@convention(c) (Handle, Bool) -> Void).self)
46 clean = try symbol("projectm_set_preset_start_clean", (@convention(c) (Handle, Bool) -> Void).self)
47 pcm = try symbol("projectm_pcm_add_float", (@convention(c) (Handle, UnsafePointer<Float>, UInt32, Int32) -> Void).self)
48 render = try symbol("projectm_opengl_render_frame_fbo", (@convention(c) (Handle, UInt32) -> Void).self)
49 texturePaths = try symbol("projectm_set_texture_search_paths", (@convention(c) (Handle, UnsafePointer<UnsafePointer<CChar>?>, Int) -> Void).self)
50 failure = try symbol("projectm_set_preset_switch_failed_event_callback", (@convention(c) (Handle, Failure?, UnsafeMutableRawPointer?) -> Void).self)
51 }
52 // Retain the loaded library for process lifetime: upstream caches GL entry points.
53}
54
55/// A separate OpenGL context hosts the unmodified ProjectM engine. IOSurface
56/// shares its frames with Metal; no glReadPixels or CPU image copies are used.
57final class ProjectMEngine {
58 private let api: ProjectMAPI
59 private let context: CGLContextObj
60 private var instance: ProjectMAPI.Handle?
61 private var surface: IOSurfaceRef?
62 private var metalTexture: MTLTexture?
63 private var glTexture: GLuint = 0
64 private var framebuffer: GLuint = 0
65 private var activePath: String?
66 private var previousTime: Double?
67 private var previousSourceTime: Double?
68 private var loadError: String?
69 private var timeOrigin: Double = 0
70 private var previousChaos: Float?
71
72 init() throws {
73 api = try ProjectMAPI()
74 var format: CGLPixelFormatObj?, count: GLint = 0
75 var attributes: [CGLPixelFormatAttribute] = [kCGLPFAOpenGLProfile, CGLPixelFormatAttribute(rawValue: UInt32(kCGLOGLPVersion_3_2_Core.rawValue)), kCGLPFAAccelerated, CGLPixelFormatAttribute(rawValue: 0)]
76 guard CGLChoosePixelFormat(&attributes, &format, &count) == kCGLNoError, let format else { throw ProjectMError("OpenGL acceleration is unavailable") }
77 defer { CGLDestroyPixelFormat(format) }
78 var created: CGLContextObj?
79 guard CGLCreateContext(format, nil, &created) == kCGLNoError, let created else { throw ProjectMError("Cannot create ProjectM graphics context") }
80 context = created
81 }
82 deinit {
83 let old = CGLGetCurrentContext(); CGLSetCurrentContext(context)
84 if let instance { api.destroy(instance) }
85 glDeleteFramebuffers(1, &framebuffer); glDeleteTextures(1, &glTexture)
86 CGLSetCurrentContext(old); CGLDestroyContext(context)
87 }
88
89 func frame(preset: URL, texturePaths: [URL], device: MTLDevice, width: Int, height: Int,
90 time: Double, sourceTime: Double, pcm: [Float], chaos: Float, fps: Int = 60) throws -> MTLTexture {
91 let old = CGLGetCurrentContext(); CGLSetCurrentContext(context)
92 defer { CGLSetCurrentContext(old) }
93 // Presets own frame counters, feedback and audio filter history. A new
94 // local clock must start with a new instance; rewinding a retained
95 // instance makes its delta/progress negative and can corrupt beat values.
96 let reset = instance == nil || activePath != preset.path || (previousTime.map {time < $0 - 0.001} ?? false) || (chaos == 0 && (previousChaos ?? 0) > 0)
97 if reset {
98 if let instance { api.destroy(instance) }
99 instance = nil
100 guard let created = api.create() else { throw ProjectMError("Cannot start ProjectM") }
101 instance = created; activePath = nil
102 api.failure(created, { _, message, user in
103 guard let user else { return }
104 let engine = Unmanaged<ProjectMEngine>.fromOpaque(user).takeUnretainedValue()
105 engine.loadError = message.map {String(cString: $0)} ?? "Preset could not load"
106 }, Unmanaged.passUnretained(self).toOpaque())
107 api.frameTime(created, 0); api.fps(created, Int32(fps)); api.lock(created, true); api.clean(created, true)
108 }
109 if activePath != preset.path, let instance {
110 timeOrigin = time; activePath = preset.path; loadError = nil; previousTime = nil; previousSourceTime = nil
111 let strings = texturePaths.map {strdup($0.path)}
112 defer { strings.forEach {free($0)} }
113 let pointers = strings.map { $0.map {UnsafePointer<CChar>($0)} }
114 pointers.withUnsafeBufferPointer { api.texturePaths(instance, $0.baseAddress!, $0.count) }
115 api.size(instance, width, height)
116 api.frameTime(instance, 0)
117 preset.path.withCString {api.load(instance, $0, false)}
118 if loadError != nil, let repaired = try MilkdropCompatibility.normalizedData(at: preset) {
119 loadError = nil
120 repaired.withCString {api.loadData(instance, $0, false)}
121 }
122 }
123 if let loadError { throw ProjectMError("\(preset.lastPathComponent): \(loadError)") }
124 guard let instance else { throw ProjectMError("ProjectM did not initialize") }
125 let resized = metalTexture?.width != width || metalTexture?.height != height
126 if resized {
127 glDeleteFramebuffers(1, &framebuffer); glDeleteTextures(1, &glTexture)
128 // Window drawable widths are arbitrary. Metal requires aligned row
129 // strides even when the visible pixel width is not aligned.
130 let rowBytes = IOSurfaceAlignProperty(kIOSurfaceBytesPerRow, ((width * 4 + 255) / 256) * 256)
131 let allocationSize = IOSurfaceAlignProperty(kIOSurfaceAllocSize, rowBytes * height)
132 guard let surface = IOSurfaceCreate([kIOSurfaceWidth: width, kIOSurfaceHeight: height, kIOSurfaceBytesPerElement: 4, kIOSurfaceBytesPerRow: rowBytes, kIOSurfaceAllocSize: allocationSize, kIOSurfacePixelFormat: kCVPixelFormatType_32BGRA] as CFDictionary) else { throw ProjectMError("Cannot allocate ProjectM surface") }
133 let descriptor = MTLTextureDescriptor.texture2DDescriptor(pixelFormat: .bgra8Unorm, width: width, height: height, mipmapped: false)
134 descriptor.storageMode = .shared; descriptor.usage = [.shaderRead]
135 guard let texture = device.makeTexture(descriptor: descriptor, iosurface: surface, plane: 0) else { throw ProjectMError("Cannot share ProjectM surface with Metal") }
136 self.surface = surface; metalTexture = texture
137 glGenTextures(1, &glTexture); glBindTexture(GLenum(GL_TEXTURE_RECTANGLE), glTexture)
138 guard CGLTexImageIOSurface2D(context, GLenum(GL_TEXTURE_RECTANGLE), GLenum(GL_RGBA), GLsizei(width), GLsizei(height), GLenum(GL_BGRA), GLenum(GL_UNSIGNED_INT_8_8_8_8_REV), surface, 0) == kCGLNoError else { throw ProjectMError("Cannot share ProjectM surface with OpenGL") }
139 glGenFramebuffers(1, &framebuffer); glBindFramebuffer(GLenum(GL_FRAMEBUFFER), framebuffer)
140 glFramebufferTexture2D(GLenum(GL_FRAMEBUFFER), GLenum(GL_COLOR_ATTACHMENT0), GLenum(GL_TEXTURE_RECTANGLE), glTexture, 0)
141 guard glCheckFramebufferStatus(GLenum(GL_FRAMEBUFFER)) == GLenum(GL_FRAMEBUFFER_COMPLETE) else { throw ProjectMError("ProjectM framebuffer is incomplete") }
142 }
143 if !resized, previousTime == time, previousChaos == chaos, let metalTexture { return metalTexture }
144 api.size(instance, width, height); api.fps(instance, Int32(fps))
145 api.frameTime(instance, max(0, time - timeOrigin))
146 if previousSourceTime != sourceTime || previousChaos != chaos {
147 let samples = pcm.isEmpty ? [Float](repeating: 0, count: 1024) : pcm.map { min(1, max(-1, $0 * chaos)) }
148 samples.withUnsafeBufferPointer {api.pcm(instance, $0.baseAddress!, UInt32($0.count / (pcm.isEmpty ? 1 : 2)), pcm.isEmpty ? 1 : 2)}
149 }
150 api.render(instance, framebuffer)
151 // Complete OpenGL writes before the Metal compositor samples this IOSurface.
152 glFinish()
153 previousTime = time; previousSourceTime = sourceTime; previousChaos = chaos
154 return metalTexture!
155 }
156}
157
158/// Milkdrop packs sometimes wrap identifiers or numeric literals between numbered
159/// EEL lines. Retrying a failed preset with joined equation chunks preserves the
160/// expression; HLSL shaders and all successfully parsed presets remain untouched.
161enum MilkdropCompatibility {
162 static func normalizedData(at url: URL) throws -> String? {
163 let data = try Data(contentsOf: url)
164 guard let text = String(data: data, encoding: .utf8) ?? String(data: data, encoding: .isoLatin1) else {return nil}
165 let pattern = try NSRegularExpression(pattern: #"^(per_frame_init_|per_frame_|per_pixel_|wave_[0-9]+_(?:init|per_frame|per_point)|shape_[0-9]+_(?:init|per_frame))([0-9]+)$"#)
166 let numericSuffix = try NSRegularExpression(pattern: #"([0-9]+(?:\.[0-9]*)?)[lL]\b"#)
167 let assignment = try NSRegularExpression(pattern: #"^[A-Za-z_][A-Za-z_0-9]*\s*="#)
168 var groups: [String: [(Int, String)]] = [:], untouched: [String] = []
169 for line in text.components(separatedBy: .newlines) {
170 guard let equals = line.firstIndex(of: "=") else {untouched.append(line); continue}
171 let key = String(line[..<equals]).trimmingCharacters(in: .whitespaces)
172 let range = NSRange(key.startIndex..., in: key)
173 guard let match = pattern.firstMatch(in: key, range: range),
174 let prefixRange = Range(match.range(at: 1), in: key),
175 let indexRange = Range(match.range(at: 2), in: key), let index = Int(key[indexRange]) else {untouched.append(line); continue}
176 let raw = String(line[line.index(after:equals)...])
177 let code = String(raw.components(separatedBy: "//")[0]).trimmingCharacters(in: .whitespacesAndNewlines)
178 groups[String(key[prefixRange]), default: []].append((index, code))
179 }
180 guard !groups.isEmpty else {return nil}
181 for prefix in groups.keys.sorted() {
182 var combined = ""
183 for (_, chunk) in groups[prefix]!.sorted(by: {$0.0 < $1.0}) where !chunk.isEmpty {
184 // An assignment at a new chunk starts a statement unless it is
185 // still inside parentheses. Other chunks continue the same token.
186 if !combined.isEmpty && !combined.hasSuffix(";") && combined.filter({$0 == "("}).count == combined.filter({$0 == ")"}).count,
187 assignment.firstMatch(in:chunk,range:NSRange(chunk.startIndex...,in:chunk)) != nil {combined += ";"}
188 combined += chunk
189 }
190 combined = numericSuffix.stringByReplacingMatches(in:combined,range:NSRange(combined.startIndex...,in:combined),withTemplate:"$1")
191 if !combined.isEmpty && !combined.hasSuffix(";") {combined += ";"}
192 untouched.append(prefix+"1="+combined)
193 }
194 return untouched.joined(separator:"\n")
195 }
196}
197
198/// Retina window size must not silently turn an interactive preview into a 4K render.
199/// The Metal compositor scales this surface; offline export keeps its full resolution.
200enum ProjectMPreviewSize {
201 static func dimensions(width: Int, height: Int) -> (width: Int, height: Int) {
202 let scale = min(1, 1280 / Double(max(width, height)))
203 return (max(1, Int((Double(width) * scale).rounded())), max(1, Int((Double(height) * scale).rounded())))
204 }
205}
206
207#endif