Initial Commit

This commit is contained in:
Mark Gregory
2026-11-03 12:53:05 +00:00
commit 83acfc63c9
136 changed files with 19465 additions and 0 deletions
@@ -0,0 +1,311 @@
// !$*UTF8*$!
{
archiveVersion = 1;
classes = {
};
objectVersion = 56;
objects = {
AB0000000000000000000001 = {isa = PBXFileReference; lastKnownFileType = folder; path = Fixtures; sourceTree = "<group>";};
AB0000000000000000000002 = {isa = PBXBuildFile; fileRef = AB0000000000000000000001;};
AB0000000000000000000003 = {isa = PBXResourcesBuildPhase; buildActionMask = 2147483647; files = (AB0000000000000000000002); runOnlyForDeploymentPostprocessing = 0;};
/* Begin PBXBuildFile section */
000000000000000000000065 /* KJamsCloneApp.swift in Sources */ = {isa = PBXBuildFile; fileRef = 000000000000000000000001 /* KJamsCloneApp.swift */; };
000000000000000000000066 /* Library.swift in Sources */ = {isa = PBXBuildFile; fileRef = 000000000000000000000002 /* Library.swift */; };
000000000000000000000067 /* CDG.swift in Sources */ = {isa = PBXBuildFile; fileRef = 000000000000000000000003 /* CDG.swift */; };
000000000000000000000068 /* Importer.swift in Sources */ = {isa = PBXBuildFile; fileRef = 000000000000000000000004 /* Importer.swift */; };
000000000000000000000069 /* Player.swift in Sources */ = {isa = PBXBuildFile; fileRef = 000000000000000000000005 /* Player.swift */; };
A00000000000000000000004 /* KJamsCloneTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = A00000000000000000000003 /* KJamsCloneTests.swift */; };
/* End PBXBuildFile section */
/* Begin PBXContainerItemProxy section */
D00000000000000000000003 /* PBXContainerItemProxy */ = {
isa = PBXContainerItemProxy;
containerPortal = F00000000000000000000001 /* Project object */;
proxyType = 1;
remoteGlobalIDString = D00000000000000000000001;
remoteInfo = KJamsClone;
};
/* End PBXContainerItemProxy section */
/* Begin PBXFileReference section */
000000000000000000000001 /* KJamsCloneApp.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = KJamsCloneApp.swift; sourceTree = "<group>"; };
000000000000000000000002 /* Library.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = Library.swift; sourceTree = "<group>"; };
000000000000000000000003 /* CDG.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = CDG.swift; sourceTree = "<group>"; };
000000000000000000000004 /* Importer.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = Importer.swift; sourceTree = "<group>"; };
000000000000000000000005 /* Player.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = Player.swift; sourceTree = "<group>"; };
A00000000000000000000001 /* KJamsClone.app */ = {isa = PBXFileReference; explicitFileType = wrapper.application; path = KJamsClone.app; sourceTree = BUILT_PRODUCTS_DIR; };
A00000000000000000000002 /* KJamsCloneTests.xctest */ = {isa = PBXFileReference; explicitFileType = wrapper.cfbundle; path = KJamsCloneTests.xctest; sourceTree = BUILT_PRODUCTS_DIR; };
A00000000000000000000003 /* KJamsCloneTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = KJamsCloneTests.swift; sourceTree = "<group>"; };
/* End PBXFileReference section */
/* Begin PBXGroup section */
B00000000000000000000001 = {
isa = PBXGroup;
children = (
AB0000000000000000000001 /* Fixtures */,
B00000000000000000000002 /* KJamsClone */,
B00000000000000000000003 /* KJamsCloneTests */,
B00000000000000000000004 /* Products */,
);
sourceTree = "<group>";
};
B00000000000000000000002 /* KJamsClone */ = {
isa = PBXGroup;
children = (
000000000000000000000001 /* KJamsCloneApp.swift */,
000000000000000000000002 /* Library.swift */,
000000000000000000000003 /* CDG.swift */,
000000000000000000000004 /* Importer.swift */,
000000000000000000000005 /* Player.swift */,
);
path = KJamsClone;
sourceTree = "<group>";
};
B00000000000000000000003 /* KJamsCloneTests */ = {
isa = PBXGroup;
children = (
A00000000000000000000003 /* KJamsCloneTests.swift */,
);
path = KJamsCloneTests;
sourceTree = "<group>";
};
B00000000000000000000004 /* Products */ = {
isa = PBXGroup;
children = (
A00000000000000000000001 /* KJamsClone.app */,
A00000000000000000000002 /* KJamsCloneTests.xctest */,
);
name = Products;
sourceTree = "<group>";
};
/* End PBXGroup section */
/* Begin PBXNativeTarget section */
D00000000000000000000001 /* KJamsClone */ = {
isa = PBXNativeTarget;
buildConfigurationList = E00000000000000000000002 /* Build configuration list for PBXNativeTarget "KJamsClone" */;
buildPhases = (
C00000000000000000000001 /* Sources */,
);
buildRules = (
);
dependencies = (
);
name = KJamsClone;
productName = KJamsClone;
productReference = A00000000000000000000001 /* KJamsClone.app */;
productType = "com.apple.product-type.application";
};
D00000000000000000000002 /* KJamsCloneTests */ = {
isa = PBXNativeTarget;
buildConfigurationList = E00000000000000000000003 /* Build configuration list for PBXNativeTarget "KJamsCloneTests" */;
buildPhases = (
C00000000000000000000002 /* Sources */,
AB0000000000000000000003 /* Resources */,
);
buildRules = (
);
dependencies = (
D00000000000000000000004 /* PBXTargetDependency */,
);
name = KJamsCloneTests;
productName = KJamsCloneTests;
productReference = A00000000000000000000002 /* KJamsCloneTests.xctest */;
productType = "com.apple.product-type.bundle.unit-test";
};
/* End PBXNativeTarget section */
/* Begin PBXProject section */
F00000000000000000000001 /* Project object */ = {
isa = PBXProject;
attributes = {
LastUpgradeCheck = 1600;
};
buildConfigurationList = E00000000000000000000001 /* Build configuration list for PBXProject "KJamsClone" */;
compatibilityVersion = "Xcode 14.0";
developmentRegion = en;
hasScannedForEncodings = 0;
knownRegions = (
en,
Base,
);
mainGroup = B00000000000000000000001;
productRefGroup = B00000000000000000000004 /* Products */;
projectDirPath = "";
projectRoot = "";
targets = (
D00000000000000000000001 /* KJamsClone */,
D00000000000000000000002 /* KJamsCloneTests */,
);
};
/* End PBXProject section */
/* Begin PBXSourcesBuildPhase section */
C00000000000000000000001 /* Sources */ = {
isa = PBXSourcesBuildPhase;
buildActionMask = 2147483647;
files = (
000000000000000000000065 /* KJamsCloneApp.swift in Sources */,
000000000000000000000066 /* Library.swift in Sources */,
000000000000000000000067 /* CDG.swift in Sources */,
000000000000000000000068 /* Importer.swift in Sources */,
000000000000000000000069 /* Player.swift in Sources */,
);
runOnlyForDeploymentPostprocessing = 0;
};
C00000000000000000000002 /* Sources */ = {
isa = PBXSourcesBuildPhase;
buildActionMask = 2147483647;
files = (
A00000000000000000000004 /* KJamsCloneTests.swift in Sources */,
);
runOnlyForDeploymentPostprocessing = 0;
};
/* End PBXSourcesBuildPhase section */
/* Begin PBXTargetDependency section */
D00000000000000000000004 /* PBXTargetDependency */ = {
isa = PBXTargetDependency;
target = D00000000000000000000001 /* KJamsClone */;
targetProxy = D00000000000000000000003 /* PBXContainerItemProxy */;
};
/* End PBXTargetDependency section */
/* Begin XCBuildConfiguration section */
F10000000000000000000000 /* Debug */ = {
isa = XCBuildConfiguration;
buildSettings = {
CLANG_ENABLE_MODULES = YES;
ENABLE_TESTABILITY = YES;
MACOSX_DEPLOYMENT_TARGET = 13.0;
SDKROOT = macosx;
SWIFT_OPTIMIZATION_LEVEL = "-Onone";
SWIFT_VERSION = 5.0;
};
name = Debug;
};
F10000000000000000000001 /* Release */ = {
isa = XCBuildConfiguration;
buildSettings = {
CLANG_ENABLE_MODULES = YES;
MACOSX_DEPLOYMENT_TARGET = 13.0;
SDKROOT = macosx;
SWIFT_OPTIMIZATION_LEVEL = "-O";
SWIFT_VERSION = 5.0;
};
name = Release;
};
F20000000000000000000000 /* Debug */ = {
isa = XCBuildConfiguration;
buildSettings = {
CLANG_ENABLE_MODULES = YES;
CODE_SIGN_STYLE = Automatic;
CURRENT_PROJECT_VERSION = 7;
DEVELOPMENT_TEAM = 39R6U3437D;
ENABLE_APP_SANDBOX = NO;
ENABLE_TESTABILITY = YES;
GENERATE_INFOPLIST_FILE = YES;
INFOPLIST_KEY_LSApplicationCategoryType = "public.app-category.music";
MACOSX_DEPLOYMENT_TARGET = 13.0;
MARKETING_VERSION = 0.3.2;
OTHER_LDFLAGS = "-lsqlite3";
PRODUCT_BUNDLE_IDENTIFIER = com.kjamsclone.app;
PRODUCT_NAME = "$(TARGET_NAME)";
SDKROOT = macosx;
SWIFT_OPTIMIZATION_LEVEL = "-Onone";
SWIFT_VERSION = 5.0;
};
name = Debug;
};
F20000000000000000000001 /* Release */ = {
isa = XCBuildConfiguration;
buildSettings = {
CLANG_ENABLE_MODULES = YES;
CODE_SIGN_STYLE = Automatic;
CURRENT_PROJECT_VERSION = 7;
DEVELOPMENT_TEAM = 39R6U3437D;
ENABLE_APP_SANDBOX = NO;
GENERATE_INFOPLIST_FILE = YES;
INFOPLIST_KEY_LSApplicationCategoryType = "public.app-category.music";
MACOSX_DEPLOYMENT_TARGET = 13.0;
MARKETING_VERSION = 0.3.2;
OTHER_LDFLAGS = "-lsqlite3";
PRODUCT_BUNDLE_IDENTIFIER = com.kjamsclone.app;
PRODUCT_NAME = "$(TARGET_NAME)";
SDKROOT = macosx;
SWIFT_OPTIMIZATION_LEVEL = "-O";
SWIFT_VERSION = 5.0;
};
name = Release;
};
F30000000000000000000000 /* Debug */ = {
isa = XCBuildConfiguration;
buildSettings = {
BUNDLE_LOADER = "$(TEST_HOST)";
CLANG_ENABLE_MODULES = YES;
ENABLE_TESTABILITY = YES;
GENERATE_INFOPLIST_FILE = YES;
MACOSX_DEPLOYMENT_TARGET = 13.0;
OTHER_LDFLAGS = "-lsqlite3";
PRODUCT_BUNDLE_IDENTIFIER = com.kjamsclone.tests;
PRODUCT_NAME = "$(TARGET_NAME)";
SDKROOT = macosx;
SWIFT_OPTIMIZATION_LEVEL = "-Onone";
SWIFT_VERSION = 5.0;
TEST_HOST = "$(BUILT_PRODUCTS_DIR)/KJamsClone.app/Contents/MacOS/KJamsClone";
};
name = Debug;
};
F30000000000000000000001 /* Release */ = {
isa = XCBuildConfiguration;
buildSettings = {
BUNDLE_LOADER = "$(TEST_HOST)";
CLANG_ENABLE_MODULES = YES;
GENERATE_INFOPLIST_FILE = YES;
MACOSX_DEPLOYMENT_TARGET = 13.0;
OTHER_LDFLAGS = "-lsqlite3";
PRODUCT_BUNDLE_IDENTIFIER = com.kjamsclone.tests;
PRODUCT_NAME = "$(TARGET_NAME)";
SDKROOT = macosx;
SWIFT_OPTIMIZATION_LEVEL = "-O";
SWIFT_VERSION = 5.0;
TEST_HOST = "$(BUILT_PRODUCTS_DIR)/KJamsClone.app/Contents/MacOS/KJamsClone";
};
name = Release;
};
/* End XCBuildConfiguration section */
/* Begin XCConfigurationList section */
E00000000000000000000001 /* Build configuration list for PBXProject "KJamsClone" */ = {
isa = XCConfigurationList;
buildConfigurations = (
F10000000000000000000000 /* Debug */,
F10000000000000000000001 /* Release */,
);
defaultConfigurationIsVisible = 0;
defaultConfigurationName = Release;
};
E00000000000000000000002 /* Build configuration list for PBXNativeTarget "KJamsClone" */ = {
isa = XCConfigurationList;
buildConfigurations = (
F20000000000000000000000 /* Debug */,
F20000000000000000000001 /* Release */,
);
defaultConfigurationIsVisible = 0;
defaultConfigurationName = Release;
};
E00000000000000000000003 /* Build configuration list for PBXNativeTarget "KJamsCloneTests" */ = {
isa = XCConfigurationList;
buildConfigurations = (
F30000000000000000000000 /* Debug */,
F30000000000000000000001 /* Release */,
);
defaultConfigurationIsVisible = 0;
defaultConfigurationName = Release;
};
/* End XCConfigurationList section */
};
rootObject = F00000000000000000000001 /* Project object */;
}
@@ -0,0 +1,7 @@
<?xml version="1.0" encoding="UTF-8"?>
<Scheme LastUpgradeVersion="1600" version="1.3">
<BuildAction parallelizeBuildables="YES" buildImplicitDependencies="YES"><BuildActionEntries><BuildActionEntry buildForTesting="YES" buildForRunning="YES" buildForProfiling="YES" buildForArchiving="YES" buildForAnalyzing="YES"><BuildableReference BuildableIdentifier="primary" BlueprintIdentifier="D00000000000000000000001" BuildableName="KJamsClone.app" BlueprintName="KJamsClone" ReferencedContainer="container:KJamsClone.xcodeproj"/></BuildActionEntry></BuildActionEntries></BuildAction>
<TestAction buildConfiguration="Debug" selectedDebuggerIdentifier="Xcode.DebuggerFoundation.Debugger.LLDB" selectedLauncherIdentifier="Xcode.IDEFoundation.Launcher.LLDB" shouldUseLaunchSchemeArgsEnv="YES"><Testables><TestableReference skipped="NO"><BuildableReference BuildableIdentifier="primary" BlueprintIdentifier="D00000000000000000000002" BuildableName="KJamsCloneTests.xctest" BlueprintName="KJamsCloneTests" ReferencedContainer="container:KJamsClone.xcodeproj"/></TestableReference></Testables></TestAction>
<LaunchAction buildConfiguration="Debug" selectedDebuggerIdentifier="Xcode.DebuggerFoundation.Debugger.LLDB" selectedLauncherIdentifier="Xcode.IDEFoundation.Launcher.LLDB" launchStyle="0" useCustomWorkingDirectory="NO" ignoresPersistentStateOnLaunch="NO" debugDocumentVersioning="YES" debugServiceExtension="internal" allowLocationSimulation="YES"><BuildableProductRunnable runnableDebuggingMode="0"><BuildableReference BuildableIdentifier="primary" BlueprintIdentifier="D00000000000000000000001" BuildableName="KJamsClone.app" BlueprintName="KJamsClone" ReferencedContainer="container:KJamsClone.xcodeproj"/></BuildableProductRunnable></LaunchAction>
<ProfileAction buildConfiguration="Release" shouldUseLaunchSchemeArgsEnv="YES" savedToolIdentifier="" useCustomWorkingDirectory="NO" debugDocumentVersioning="YES"/><AnalyzeAction buildConfiguration="Debug"/><ArchiveAction buildConfiguration="Release" revealArchiveInOrganizer="YES"/>
</Scheme>
@@ -0,0 +1,68 @@
import Foundation
import CoreGraphics
/// CD+G packet decoder. Packet parity is ignored; malformed coordinates are rejected.
struct CDGDecoder {
private(set) var pixels = [UInt8](repeating: 0, count: 300 * 216)
private(set) var palette = [UInt32](repeating: 0x000000FF, count: 16)
private(set) var packetIndex = 0
private(set) var horizontalOffset = 0
private(set) var verticalOffset = 0
private var transparent: UInt8?
mutating func render(_ data: Data, at seconds: Double) {
let target = min(data.count / 24, max(0, Int(max(0, seconds) * 300)))
if target < packetIndex { self = CDGDecoder() }
while packetIndex < target {
apply(Array(data[(packetIndex * 24)..<(packetIndex * 24 + 24)]))
packetIndex += 1
}
}
mutating func apply(_ packet: [UInt8]) {
guard packet.count == 24, packet[0] & 63 == 9 else { return }
let d = packet[4..<20].map { Int($0 & 63) }
switch packet[1] & 63 {
case 1:
if d[1] == 0 { pixels = .init(repeating: UInt8(d[0] & 15), count: pixels.count) }
case 2:
for y in 0..<216 { for x in 0..<300 where x < 6 || x >= 294 || y < 12 || y >= 204 { pixels[y * 300 + x] = UInt8(d[0] & 15) } }
case 6, 38:
let row = d[2] & 31, col = d[3] & 63
guard row < 18, col < 50 else { return }
for y in 0..<12 { for x in 0..<6 {
let color = UInt8(d[(y + 4)] & (1 << (5 - x)) == 0 ? d[0] & 15 : d[1] & 15)
let i = (row * 12 + y) * 300 + col * 6 + x
if packet[1] & 63 == 38 { pixels[i] ^= color } else { pixels[i] = color }
} }
case 20, 24:
horizontalOffset = min(d[1] & 7, 5); verticalOffset = min(d[2] & 15, 11)
let hx = (d[1] >> 4) & 3, vy = (d[2] >> 4) & 3
let dx = hx == 1 ? 6 : hx == 2 ? -6 : 0
let dy = vy == 1 ? 12 : vy == 2 ? -12 : 0
let old = pixels
for y in 0..<216 { for x in 0..<300 {
let sx = x - dx, sy = y - dy
if packet[1] & 63 == 24 || (sx >= 0 && sx < 300 && sy >= 0 && sy < 216) {
pixels[y * 300 + x] = old[((sy + 216) % 216) * 300 + (sx + 300) % 300]
} else { pixels[y * 300 + x] = UInt8(d[0] & 15) }
} }
case 28: transparent = UInt8(d[0] & 15)
case 30, 31:
let start = packet[1] & 63 == 30 ? 0 : 8
for i in 0..<8 {
let v = (d[i * 2] << 6) | d[i * 2 + 1]
palette[start + i] = UInt32(((v >> 8) & 15) * 17) << 24 | UInt32(((v >> 4) & 15) * 17) << 16 | UInt32((v & 15) * 17) << 8 | 255
}
default: break
}
}
func image() -> CGImage? {
var rgba = [UInt8](); rgba.reserveCapacity(288 * 192 * 4)
for y in 12..<204 { for x in 6..<294 {
let index = pixels[(y + verticalOffset) * 300 + x + horizontalOffset]
let c = palette[Int(index)]
rgba += [UInt8((c >> 24) & 255), UInt8((c >> 16) & 255), UInt8((c >> 8) & 255), index == transparent ? 0 : 255]
} }
guard let provider = CGDataProvider(data: Data(rgba) as CFData) else { return nil }
return CGImage(width: 288, height: 192, bitsPerComponent: 8, bitsPerPixel: 32, bytesPerRow: 288 * 4, space: CGColorSpaceCreateDeviceRGB(), bitmapInfo: CGBitmapInfo(rawValue: CGImageAlphaInfo.last.rawValue), provider: provider, decode: nil, shouldInterpolate: false, intent: .defaultIntent)
}
}
@@ -0,0 +1,68 @@
import Foundation
import CryptoKit
import AVFoundation
struct Importer {
let media: URL
func run(_ urls: [URL], library: Library) throws {
try FileManager.default.createDirectory(at: media, withIntermediateDirectories: true)
var files = urls
var temporary = [URL]()
defer { for url in temporary { try? FileManager.default.removeItem(at: url) } }
for zip in urls where zip.pathExtension.lowercased() == "zip" {
let folder = FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString)
try FileManager.default.createDirectory(at: folder, withIntermediateDirectories: true)
temporary.append(folder)
// Validate names before extraction; reject path traversal and symlinks afterwards.
let details = try process(["-Z", "-l", zip.path])
guard !details.split(separator: "\n").contains(where: { $0.hasPrefix("l") }) else { throw LibraryError.message("ZIP symlinks are unsupported") }
let list = try process(["-Z1", zip.path])
let names = list.split(separator: "\n").map(String.init)
guard !names.isEmpty, names.allSatisfy({ !$0.hasPrefix("/") && !$0.split(separator: "/").contains("..") && !$0.contains("\\") }) else { throw LibraryError.message("Unsafe or empty ZIP") }
_ = try process(["-q", zip.path, "-d", folder.path])
let extracted = FileManager.default.enumerator(at: folder, includingPropertiesForKeys: [.isSymbolicLinkKey,.isRegularFileKey])!
for case let url as URL in extracted {
let values = try url.resourceValues(forKeys: [.isSymbolicLinkKey,.isRegularFileKey])
guard values.isSymbolicLink != true else { throw LibraryError.message("ZIP symlinks are unsupported") }
if values.isRegularFile == true { files.append(url) }
}
}
for cdg in files.filter({ $0.pathExtension.lowercased() == "cdg" }) {
let siblings = try FileManager.default.contentsOfDirectory(at:cdg.deletingLastPathComponent(),includingPropertiesForKeys:nil)
if let audio = siblings.first(where: { ["mp3","wav","m4a"].contains($0.pathExtension.lowercased()) && $0.deletingPathExtension().lastPathComponent.caseInsensitiveCompare(cdg.deletingPathExtension().lastPathComponent) == .orderedSame }) { files.append(audio) }
}
var imported = 0
for audio in Set(files) where ["mp3","wav","m4a"].contains(audio.pathExtension.lowercased()) {
let siblings = try FileManager.default.contentsOfDirectory(at: audio.deletingLastPathComponent(), includingPropertiesForKeys: nil)
let cdg = siblings.first { $0.pathExtension.lowercased() == "cdg" && $0.deletingPathExtension().lastPathComponent.caseInsensitiveCompare(audio.deletingPathExtension().lastPathComponent) == .orderedSame }
let hash = SHA256.hash(data: try Data(contentsOf: audio)).map { String(format: "%02x", $0) }.joined()
let dest = media.appendingPathComponent(hash + "." + audio.pathExtension.lowercased())
if !FileManager.default.fileExists(atPath: dest.path) { try FileManager.default.copyItem(at: audio, to: dest) }
var graphics: String?
if let cdg {
let target = media.appendingPathComponent(hash + ".cdg")
if !FileManager.default.fileExists(atPath: target.path) { try FileManager.default.copyItem(at: cdg, to: target) }
graphics = target.path
}
imported += 1
let metadata = AVURLAsset(url:audio).commonMetadata
func tag(_ key: AVMetadataKey) -> String { metadata.first { $0.commonKey == key }?.stringValue ?? "" }
let taggedTitle = tag(.commonKeyTitle)
try library.add(title:taggedTitle.isEmpty ? audio.deletingPathExtension().lastPathComponent : taggedTitle,audio:dest.path,cdg:graphics,artist:tag(.commonKeyArtist),album:tag(.commonKeyAlbumName),label:tag(.commonKeyPublisher),duration:audioDuration(audio))
}
guard imported > 0 else { throw LibraryError.message("No audio found. Keep the MP3 and matching CDG together, or import an MP3+G ZIP.") }
}
private func audioDuration(_ url: URL) -> Double {
guard let file = try? AVAudioFile(forReading:url) else { return 0 }
return Double(file.length)/file.processingFormat.sampleRate
}
private func process(_ arguments: [String]) throws -> String {
let task = Process(); task.executableURL = URL(fileURLWithPath: "/usr/bin/unzip"); task.arguments = arguments
let out = Pipe(); task.standardOutput = out
let err = FileHandle.nullDevice; task.standardError = err
try task.run()
let bytes = out.fileHandleForReading.readDataToEndOfFile(); task.waitUntilExit()
guard task.terminationStatus == 0 else { throw LibraryError.message("Cannot read ZIP archive") }
return String(decoding: bytes, as: UTF8.self)
}
}
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,348 @@
import Foundation
import SQLite3
struct Song: Identifiable, Hashable {
var id: Int64
var title: String
var audio: String
var cdg: String?
var rating: Int
var plays: Int
var artist: String = ""
var album: String = ""
var label: String = ""
var duration: Double = 0
}
struct MusicStore: Identifiable, Hashable {
var id: Int64
var name: String
var url: String
var searchTemplate: String
func destination(query: String = "") throws -> URL {
let query = query.trimmingCharacters(in:.whitespacesAndNewlines)
let encoded = query.addingPercentEncoding(withAllowedCharacters:CharacterSet(charactersIn:"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-._~")) ?? ""
let value = query.isEmpty || searchTemplate.isEmpty ? url : searchTemplate.replacingOccurrences(of:"{query}",with:encoded)
guard let result = URL(string:value), ["http","https"].contains(result.scheme?.lowercased() ?? ""), result.host?.isEmpty == false, result.user == nil, result.password == nil else { throw LibraryError.message("Use a valid http:// or https:// store URL without credentials") }
return result
}
}
struct PersonPlace: Identifiable, Hashable { var id: Int64; var name: String }
struct SongPreference: Equatable {
var pitch: Double = 0
var tempo: Double = 1
var rating: Int = 0
}
struct Performance: Identifiable {
var id: Int64
var song: String
var singer: String
var venue: String
var date: String
var singerID: Int64?
var songID: Int64?
}
struct QueueEntry: Identifiable {
var id: Int64
var songID: Int64
var singerID: Int64?
var title: String
var singer: String
}
enum LibraryError: LocalizedError {
case message(String)
var errorDescription: String? { if case .message(let s) = self { return s }; return nil }
}
final class Library {
private var db: OpaquePointer?
init(url: URL) throws {
guard sqlite3_open(url.path, &db) == SQLITE_OK else { throw LibraryError.message("Cannot open library") }
try execute("PRAGMA foreign_keys=ON")
try execute("CREATE TABLE IF NOT EXISTS songs(id INTEGER PRIMARY KEY,title TEXT NOT NULL,audio TEXT UNIQUE NOT NULL,cdg TEXT,rating INTEGER NOT NULL DEFAULT 0 CHECK(rating BETWEEN 0 AND 5),plays INTEGER NOT NULL DEFAULT 0)")
try execute("CREATE TABLE IF NOT EXISTS singers(id INTEGER PRIMARY KEY,name TEXT UNIQUE NOT NULL)")
try execute("CREATE TABLE IF NOT EXISTS venues(id INTEGER PRIMARY KEY,name TEXT UNIQUE NOT NULL)")
try execute("CREATE TABLE IF NOT EXISTS history(id INTEGER PRIMARY KEY,song INTEGER REFERENCES songs(id),singer INTEGER REFERENCES singers(id),venue INTEGER REFERENCES venues(id),played TEXT DEFAULT CURRENT_TIMESTAMP)")
// Additive migration: preserve older libraries and infer existing memberships from history.
for column in ["artist", "album", "label"] {
if try !columns("songs").contains(column) { try execute("ALTER TABLE songs ADD COLUMN \(column) TEXT NOT NULL DEFAULT ''") }
}
try execute("CREATE TABLE IF NOT EXISTS venue_singers(venue INTEGER NOT NULL REFERENCES venues(id) ON DELETE CASCADE,singer INTEGER NOT NULL REFERENCES singers(id) ON DELETE CASCADE,PRIMARY KEY(venue,singer))")
if try schemaVersion() < 3 { try execute("INSERT OR IGNORE INTO venue_singers SELECT DISTINCT venue,singer FROM history WHERE venue IS NOT NULL AND singer IS NOT NULL") }
try execute("CREATE TABLE IF NOT EXISTS settings(key TEXT PRIMARY KEY,value TEXT)")
try execute("CREATE TABLE IF NOT EXISTS preferences(song INTEGER NOT NULL REFERENCES songs(id) ON DELETE CASCADE,singer INTEGER NOT NULL REFERENCES singers(id) ON DELETE CASCADE,pitch REAL NOT NULL DEFAULT 0 CHECK(pitch BETWEEN -12 AND 12),tempo REAL NOT NULL DEFAULT 1 CHECK(tempo BETWEEN 0.5 AND 1.5),rating INTEGER NOT NULL DEFAULT 0 CHECK(rating BETWEEN 0 AND 5),PRIMARY KEY(song,singer))")
try execute("CREATE TABLE IF NOT EXISTS queue(id INTEGER PRIMARY KEY,venue INTEGER REFERENCES venues(id) ON DELETE CASCADE,song INTEGER NOT NULL REFERENCES songs(id) ON DELETE CASCADE,singer INTEGER REFERENCES singers(id) ON DELETE CASCADE,position INTEGER NOT NULL)")
try execute("CREATE TABLE IF NOT EXISTS playlists(id INTEGER PRIMARY KEY,name TEXT UNIQUE NOT NULL)")
try execute("CREATE TABLE IF NOT EXISTS playlist_songs(playlist INTEGER NOT NULL REFERENCES playlists(id) ON DELETE CASCADE,song INTEGER NOT NULL REFERENCES songs(id) ON DELETE CASCADE,position INTEGER NOT NULL,PRIMARY KEY(playlist,song))")
try execute("CREATE TABLE IF NOT EXISTS singer_songs(singer INTEGER NOT NULL REFERENCES singers(id) ON DELETE CASCADE,song INTEGER NOT NULL REFERENCES songs(id) ON DELETE CASCADE,position INTEGER NOT NULL,PRIMARY KEY(singer,song))")
if try schemaVersion() < 4 {
try execute("INSERT OR IGNORE INTO singer_songs(singer,song,position) SELECT singer,song,MIN(id) FROM history WHERE singer IS NOT NULL AND song IS NOT NULL GROUP BY singer,song")
try execute("INSERT OR IGNORE INTO singer_songs(singer,song,position) SELECT singer,song,0 FROM preferences")
}
if try !columns("songs").contains("duration") { try execute("ALTER TABLE songs ADD COLUMN duration REAL NOT NULL DEFAULT 0") }
if try !columns("singer_songs").contains("favourite") { try execute("ALTER TABLE singer_songs ADD COLUMN favourite INTEGER NOT NULL DEFAULT 0 CHECK(favourite IN (0,1))") }
if try schemaVersion() < 5 { try execute("UPDATE singer_songs SET favourite=1 WHERE EXISTS(SELECT 1 FROM preferences WHERE preferences.singer=singer_songs.singer AND preferences.song=singer_songs.song AND preferences.rating>=4)") }
try execute("CREATE TABLE IF NOT EXISTS song_settings(song INTEGER PRIMARY KEY REFERENCES songs(id) ON DELETE CASCADE,pitch REAL NOT NULL DEFAULT 0 CHECK(pitch BETWEEN -12 AND 12),tempo REAL NOT NULL DEFAULT 1 CHECK(tempo BETWEEN 0.5 AND 1.5))")
try execute("CREATE TABLE IF NOT EXISTS music_stores(id INTEGER PRIMARY KEY,name TEXT UNIQUE NOT NULL,url TEXT NOT NULL,search_template TEXT NOT NULL DEFAULT '')")
if try !columns("songs").contains("metadata_edited") { try execute("ALTER TABLE songs ADD COLUMN metadata_edited INTEGER NOT NULL DEFAULT 0") }
try execute("CREATE TABLE IF NOT EXISTS singer_tonight(venue INTEGER NOT NULL,singer INTEGER NOT NULL,song INTEGER NOT NULL REFERENCES songs(id) ON DELETE CASCADE,position INTEGER NOT NULL,PRIMARY KEY(venue,singer,song),FOREIGN KEY(venue,singer) REFERENCES venue_singers(venue,singer) ON DELETE CASCADE)")
if try schemaVersion() < 7 {
try execute("INSERT OR IGNORE INTO singer_tonight(venue,singer,song,position) SELECT queue.venue,queue.singer,queue.song,MIN(queue.position) FROM queue JOIN venue_singers ON venue_singers.venue=queue.venue AND venue_singers.singer=queue.singer WHERE queue.singer IS NOT NULL GROUP BY queue.venue,queue.singer,queue.song")
}
try execute("PRAGMA user_version=7")
}
deinit { sqlite3_close(db) }
private func statement(_ sql: String, _ values: [String?]) throws -> OpaquePointer {
var s: OpaquePointer?
guard sqlite3_prepare_v2(db, sql, -1, &s, nil) == SQLITE_OK, let s else { throw error() }
for (i,v) in values.enumerated() {
let code = v.map { sqlite3_bind_text(s, Int32(i + 1), $0, -1, unsafeBitCast(-1, to: sqlite3_destructor_type.self)) } ?? sqlite3_bind_null(s, Int32(i + 1))
if code != SQLITE_OK { sqlite3_finalize(s); throw error() }
}
return s
}
private func error() -> LibraryError { .message(String(cString: sqlite3_errmsg(db))) }
func execute(_ sql: String, _ values: [String?] = []) throws {
let s = try statement(sql, values); defer { sqlite3_finalize(s) }
guard sqlite3_step(s) == SQLITE_DONE else { throw error() }
}
func songs() throws -> [Song] {
let s = try statement("SELECT id,title,audio,cdg,rating,plays,artist,album,label,duration FROM songs ORDER BY title COLLATE NOCASE", []); defer { sqlite3_finalize(s) }
var result = [Song]()
while true {
let code = sqlite3_step(s); if code == SQLITE_DONE { break }; guard code == SQLITE_ROW else { throw error() }
result.append(Song(id: sqlite3_column_int64(s,0), title: String(cString: sqlite3_column_text(s,1)), audio: String(cString: sqlite3_column_text(s,2)), cdg: sqlite3_column_text(s,3).map { String(cString:$0) }, rating: Int(sqlite3_column_int(s,4)), plays: Int(sqlite3_column_int(s,5)), artist: text(s,6), album: text(s,7), label: text(s,8),duration:sqlite3_column_double(s,9)))
}
return result
}
func add(title: String, audio: String, cdg: String?, artist: String = "", album: String = "", label: String = "", duration: Double = 0) throws {
try execute("INSERT INTO songs(title,audio,cdg,artist,album,label,duration) VALUES(?,?,?,?,?,?,?) ON CONFLICT(audio) DO UPDATE SET cdg=COALESCE(excluded.cdg,songs.cdg),artist=CASE WHEN songs.metadata_edited=0 AND excluded.artist!='' THEN excluded.artist ELSE songs.artist END,album=CASE WHEN songs.metadata_edited=0 AND excluded.album!='' THEN excluded.album ELSE songs.album END,label=CASE WHEN songs.metadata_edited=0 AND excluded.label!='' THEN excluded.label ELSE songs.label END,duration=CASE WHEN excluded.duration>0 THEN excluded.duration ELSE songs.duration END", [title,audio,cdg,artist,album,label,String(duration)])
}
func rate(_ id: Int64, _ rating: Int) throws { try execute("UPDATE songs SET rating=? WHERE id=?", [String(rating),String(id)]) }
func entities(_ table: String) throws -> [PersonPlace] {
precondition(["singers","venues","playlists"].contains(table))
let s = try statement("SELECT id,name FROM \(table) ORDER BY name", []); defer { sqlite3_finalize(s) }
var rows = [PersonPlace]()
while sqlite3_step(s) == SQLITE_ROW { rows.append(.init(id: sqlite3_column_int64(s,0), name: String(cString: sqlite3_column_text(s,1)))) }
return rows
}
func addEntity(_ table: String, name: String) throws {
precondition(["singers","venues","playlists"].contains(table))
let name = name.trimmingCharacters(in: .whitespacesAndNewlines)
guard !name.isEmpty else { throw LibraryError.message("Enter a name") }
try execute("INSERT OR IGNORE INTO \(table)(name) VALUES(?)", [name])
}
func record(_ song: Int64, singer: Int64?, venue: Int64?) throws {
try execute("BEGIN IMMEDIATE")
do {
if let singer { try assignSong(song,singer:singer) }
try execute("INSERT INTO history(song,singer,venue) VALUES(?,?,?)", [String(song),singer.map(String.init),venue.map(String.init)])
try execute("UPDATE songs SET plays=plays+1 WHERE id=?", [String(song)])
try execute("COMMIT")
} catch { try? execute("ROLLBACK"); throw error }
}
private func text(_ s: OpaquePointer, _ index: Int32) -> String { sqlite3_column_text(s,index).map { String(cString:$0) } ?? "" }
private func schemaVersion() throws -> Int {
let s = try statement("PRAGMA user_version",[]); defer { sqlite3_finalize(s) }
return sqlite3_step(s) == SQLITE_ROW ? Int(sqlite3_column_int(s,0)) : 0
}
private func columns(_ table: String) throws -> Set<String> {
let s = try statement("PRAGMA table_info(\(table))", []); defer { sqlite3_finalize(s) }
var result = Set<String>(); while sqlite3_step(s) == SQLITE_ROW { result.insert(text(s,1)) }; return result
}
func members(of venue: Int64) throws -> [PersonPlace] {
let s = try statement("SELECT singers.id,singers.name FROM singers JOIN venue_singers ON singers.id=venue_singers.singer WHERE venue=? ORDER BY name", [String(venue)]); defer { sqlite3_finalize(s) }
var result = [PersonPlace](); while sqlite3_step(s) == SQLITE_ROW { result.append(.init(id:sqlite3_column_int64(s,0),name:text(s,1))) }; return result
}
func setMembership(singer: Int64, venue: Int64, included: Bool) throws {
try execute(included ? "INSERT OR IGNORE INTO venue_singers(venue,singer) VALUES(?,?)" : "DELETE FROM venue_singers WHERE venue=? AND singer=?", [String(venue),String(singer)])
if !included { try execute("DELETE FROM queue WHERE venue=? AND singer=?",[String(venue),String(singer)]) }
}
func currentVenue() throws -> Int64? {
let s = try statement("SELECT venues.id FROM venues JOIN settings ON CAST(settings.value AS INTEGER)=venues.id WHERE settings.key='currentVenue'", []); defer { sqlite3_finalize(s) }
return sqlite3_step(s) == SQLITE_ROW ? sqlite3_column_int64(s,0) : nil
}
func selectVenue(_ id: Int64?) throws {
if let id {
guard try entities("venues").contains(where: { $0.id == id }) else { throw LibraryError.message("Venue no longer exists") }
}
try execute("INSERT INTO settings(key,value) VALUES('currentVenue',?) ON CONFLICT(key) DO UPDATE SET value=excluded.value",[id.map(String.init)])
}
func rename(_ table: String, id: Int64, name: String) throws {
precondition(["singers","venues","playlists"].contains(table))
let name = name.trimmingCharacters(in:.whitespacesAndNewlines)
guard !name.isEmpty else { throw LibraryError.message("Enter a name") }
try execute("UPDATE \(table) SET name=? WHERE id=?",[name,String(id)])
}
func deleteEntity(_ table: String, id: Int64) throws {
precondition(["singers","venues","playlists"].contains(table))
try execute("BEGIN IMMEDIATE")
do {
if table == "singers" { try execute("UPDATE history SET singer=NULL WHERE singer=?",[String(id)]) }
if table == "venues" {
try execute("UPDATE history SET venue=NULL WHERE venue=?",[String(id)])
try execute("DELETE FROM settings WHERE key='currentVenue' AND value=?",[String(id)])
}
try execute("DELETE FROM \(table) WHERE id=?",[String(id)])
try execute("COMMIT")
} catch { try? execute("ROLLBACK"); throw error }
}
func preference(song: Int64, singer: Int64) throws -> SongPreference {
let s = try statement("SELECT pitch,tempo,rating FROM preferences WHERE song=? AND singer=?",[String(song),String(singer)]); defer { sqlite3_finalize(s) }
guard sqlite3_step(s) == SQLITE_ROW else { return try defaultPreference(song:song) }
return .init(pitch:sqlite3_column_double(s,0),tempo:sqlite3_column_double(s,1),rating:Int(sqlite3_column_int(s,2)))
}
func savePreference(song: Int64, singer: Int64, value: SongPreference) throws {
try execute("INSERT INTO preferences(song,singer,pitch,tempo,rating) VALUES(?,?,?,?,?) ON CONFLICT(song,singer) DO UPDATE SET pitch=excluded.pitch,tempo=excluded.tempo,rating=excluded.rating",[String(song),String(singer),String(value.pitch),String(value.tempo),String(value.rating)])
}
func history(venue: Int64?, singer: Int64? = nil) throws -> [Performance] {
let s = try statement("SELECT history.id,COALESCE(songs.title,'Deleted song'),COALESCE(singers.name,'—'),COALESCE(venues.name,'—'),played,history.singer,history.song FROM history LEFT JOIN songs ON songs.id=history.song LEFT JOIN singers ON singers.id=history.singer LEFT JOIN venues ON venues.id=history.venue WHERE (? IS NULL OR history.venue=?) AND (? IS NULL OR history.singer=?) ORDER BY history.id DESC",[venue.map(String.init),venue.map(String.init),singer.map(String.init),singer.map(String.init)]); defer { sqlite3_finalize(s) }
var result = [Performance](); while sqlite3_step(s) == SQLITE_ROW { result.append(.init(id:sqlite3_column_int64(s,0),song:text(s,1),singer:text(s,2),venue:text(s,3),date:text(s,4),singerID:sqlite3_column_type(s,5) == SQLITE_NULL ? nil : sqlite3_column_int64(s,5),songID:sqlite3_column_type(s,6) == SQLITE_NULL ? nil : sqlite3_column_int64(s,6))) }; return result
}
func enqueue(song: Int64, singer: Int64?, venue: Int64?) throws {
guard let venue else { throw LibraryError.message("Select a current venue before adding to its queue") }
if let singer, try !members(of:venue).contains(where: { $0.id == singer }) { throw LibraryError.message("Add this singer to the current venue first") }
try execute("BEGIN IMMEDIATE")
do {
if let singer {
try assignSong(song,singer:singer)
try execute("INSERT OR IGNORE INTO singer_tonight(venue,singer,song,position) VALUES(?,?,?,(SELECT COALESCE(MAX(position),0)+1 FROM singer_tonight WHERE venue=? AND singer=?))",[String(venue),String(singer),String(song),String(venue),String(singer)])
}
try execute("INSERT INTO queue(venue,song,singer,position) VALUES(?,?,?,(SELECT COALESCE(MAX(position),0)+1 FROM queue WHERE venue=?))",[String(venue),String(song),singer.map(String.init),String(venue)])
try execute("COMMIT")
} catch { try? execute("ROLLBACK");throw error }
}
func queue(venue: Int64?) throws -> [QueueEntry] {
guard let venue else { return [] }
let s = try statement("SELECT queue.id,queue.song,queue.singer,songs.title,COALESCE(singers.name,'No singer') FROM queue JOIN songs ON songs.id=queue.song LEFT JOIN singers ON singers.id=queue.singer WHERE queue.venue=? ORDER BY queue.position,queue.id",[String(venue)]); defer { sqlite3_finalize(s) }
var result = [QueueEntry](); while sqlite3_step(s) == SQLITE_ROW { result.append(.init(id:sqlite3_column_int64(s,0),songID:sqlite3_column_int64(s,1),singerID:sqlite3_column_type(s,2) == SQLITE_NULL ? nil : sqlite3_column_int64(s,2),title:text(s,3),singer:text(s,4))) }; return result
}
func removeQueue(_ id: Int64) throws { try execute("DELETE FROM queue WHERE id=?",[String(id)]) }
func moveQueue(_ id: Int64, venue: Int64, by offset: Int) throws {
var rows = try queue(venue:venue)
guard let index = rows.firstIndex(where: { $0.id == id }), rows.indices.contains(index+offset) else { return }
rows.swapAt(index,index+offset)
try execute("BEGIN IMMEDIATE")
do { for (i,row) in rows.enumerated() { try execute("UPDATE queue SET position=? WHERE id=?",[String(i),String(row.id)]) }; try execute("COMMIT") }
catch { try? execute("ROLLBACK"); throw error }
}
func addToPlaylist(_ playlist: Int64, song: Int64) throws {
try execute("INSERT OR IGNORE INTO playlist_songs(playlist,song,position) VALUES(?,?,(SELECT COALESCE(MAX(position),0)+1 FROM playlist_songs WHERE playlist=?))",[String(playlist),String(song),String(playlist)])
}
func playlistSongIDs(_ playlist: Int64) throws -> [Int64] {
let s = try statement("SELECT song FROM playlist_songs WHERE playlist=? ORDER BY position",[String(playlist)]); defer { sqlite3_finalize(s) }
var ids = [Int64](); while sqlite3_step(s) == SQLITE_ROW { ids.append(sqlite3_column_int64(s,0)) }; return ids
}
func removeFromPlaylist(_ playlist: Int64, song: Int64) throws { try execute("DELETE FROM playlist_songs WHERE playlist=? AND song=?",[String(playlist),String(song)]) }
func assignSong(_ song: Int64, singer: Int64) throws {
try execute("INSERT OR IGNORE INTO singer_songs(singer,song,position) VALUES(?,?,(SELECT COALESCE(MAX(position),0)+1 FROM singer_songs WHERE singer=?))",[String(singer),String(song),String(singer)])
}
func removeSingerSong(_ song: Int64, singer: Int64) throws {
try execute("DELETE FROM singer_songs WHERE singer=? AND song=?",[String(singer),String(song)])
}
func singerSongIDs() throws -> [Int64:[Int64]] {
let s = try statement("SELECT singer,song FROM singer_songs ORDER BY singer,position,song",[]); defer { sqlite3_finalize(s) }
var result = [Int64:[Int64]]()
while sqlite3_step(s) == SQLITE_ROW { result[sqlite3_column_int64(s,0),default:[]].append(sqlite3_column_int64(s,1)) }
return result
}
func defaultPreference(song: Int64) throws -> SongPreference {
let s = try statement("SELECT pitch,tempo FROM song_settings WHERE song=?",[String(song)]);defer { sqlite3_finalize(s) }
guard sqlite3_step(s) == SQLITE_ROW else { return .init() }
return .init(pitch:sqlite3_column_double(s,0),tempo:sqlite3_column_double(s,1),rating:0)
}
func saveDefaultPreference(song: Int64, value: SongPreference) throws {
try execute("INSERT INTO song_settings(song,pitch,tempo) VALUES(?,?,?) ON CONFLICT(song) DO UPDATE SET pitch=excluded.pitch,tempo=excluded.tempo",[String(song),String(value.pitch),String(value.tempo)])
}
func updateDuration(_ song: Int64, seconds: Double) throws {
guard seconds.isFinite && seconds >= 0 else { return }
try execute("UPDATE songs SET duration=? WHERE id=?",[String(seconds),String(song)])
}
func setFavourite(song: Int64, singer: Int64, included: Bool) throws {
if included { try assignSong(song,singer:singer) }
try execute("UPDATE singer_songs SET favourite=? WHERE singer=? AND song=?",[included ? "1" : "0",String(singer),String(song)])
}
func favouriteSongIDs() throws -> [Int64:Set<Int64>] {
let s = try statement("SELECT singer,song FROM singer_songs WHERE favourite=1",[]);defer { sqlite3_finalize(s) }
var result = [Int64:Set<Int64>]()
while sqlite3_step(s) == SQLITE_ROW { result[sqlite3_column_int64(s,0),default:[]].insert(sqlite3_column_int64(s,1)) };return result
}
func stores() throws -> [MusicStore] {
let s = try statement("SELECT id,name,url,search_template FROM music_stores ORDER BY name",[]);defer { sqlite3_finalize(s) }
var result = [MusicStore]()
while sqlite3_step(s) == SQLITE_ROW { result.append(.init(id:sqlite3_column_int64(s,0),name:text(s,1),url:text(s,2),searchTemplate:text(s,3))) };return result
}
func saveStore(_ store: MusicStore) throws {
let name = store.name.trimmingCharacters(in:.whitespacesAndNewlines),url = store.url.trimmingCharacters(in:.whitespacesAndNewlines),search = store.searchTemplate.trimmingCharacters(in:.whitespacesAndNewlines)
guard !name.isEmpty else { throw LibraryError.message("Enter a store name") }
let cleaned = MusicStore(id:store.id,name:name,url:url,searchTemplate:search)
_ = try cleaned.destination()
if !search.isEmpty {
guard search.contains("{query}") else { throw LibraryError.message("Search URL must contain {query}") }
_ = try cleaned.destination(query:"test")
}
if store.id == 0 { try execute("INSERT INTO music_stores(name,url,search_template) VALUES(?,?,?)",[name,url,search]) }
else { try execute("UPDATE music_stores SET name=?,url=?,search_template=? WHERE id=?",[name,url,search,String(store.id)]) }
}
func deleteStore(_ id: Int64) throws { try execute("DELETE FROM music_stores WHERE id=?",[String(id)]) }
func updateMetadata(song: Int64,title: String,artist: String,album: String,label: String,rating: Int) throws {
let title = title.trimmingCharacters(in:.whitespacesAndNewlines)
guard !title.isEmpty else { throw LibraryError.message("Song title cannot be empty") }
try execute("UPDATE songs SET title=?,artist=?,album=?,label=?,rating=?,metadata_edited=1 WHERE id=?",[title,artist.trimmingCharacters(in:.whitespacesAndNewlines),album.trimmingCharacters(in:.whitespacesAndNewlines),label.trimmingCharacters(in:.whitespacesAndNewlines),String(rating),String(song)])
guard sqlite3_changes(db) == 1 else { throw LibraryError.message("Song no longer exists") }
}
func tonightSongIDs(venue: Int64?) throws -> [Int64:[Int64]] {
guard let venue else { return [:] }
let s = try statement("SELECT singer,song FROM singer_tonight WHERE venue=? ORDER BY position,song",[String(venue)]);defer { sqlite3_finalize(s) }
var result = [Int64:[Int64]]()
while sqlite3_step(s) == SQLITE_ROW { result[sqlite3_column_int64(s,0),default:[]].append(sqlite3_column_int64(s,1)) };return result
}
func addTonight(song: Int64,singer: Int64,venue: Int64) throws {
guard try members(of:venue).contains(where:{ $0.id == singer }) else { throw LibraryError.message("This singer is not a member of the current venue") }
try execute("BEGIN IMMEDIATE")
do {
try assignSong(song,singer:singer)
try execute("INSERT OR IGNORE INTO singer_tonight(venue,singer,song,position) VALUES(?,?,?,(SELECT COALESCE(MAX(position),0)+1 FROM singer_tonight WHERE venue=? AND singer=?))",[String(venue),String(singer),String(song),String(venue),String(singer)])
try execute("INSERT INTO queue(venue,song,singer,position) SELECT ?,?,?,(SELECT COALESCE(MAX(position),0)+1 FROM queue WHERE venue=?) WHERE NOT EXISTS(SELECT 1 FROM queue WHERE venue=? AND singer=? AND song=?)",[String(venue),String(song),String(singer),String(venue),String(venue),String(singer),String(song)])
try execute("COMMIT")
} catch { try? execute("ROLLBACK");throw error }
}
func removeTonight(song: Int64,singer: Int64,venue: Int64) throws {
try execute("BEGIN IMMEDIATE")
do {
try execute("DELETE FROM singer_tonight WHERE venue=? AND singer=? AND song=?",[String(venue),String(singer),String(song)])
try execute("DELETE FROM queue WHERE venue=? AND singer=? AND song=?",[String(venue),String(singer),String(song)])
try execute("COMMIT")
} catch { try? execute("ROLLBACK");throw error }
}
/// Atomically adds/copies or reorders a request, retaining other singers' queue slots.
func placeTonight(song: Int64,singer: Int64,venue: Int64,before: Int64?,addIfNeeded: Bool) throws {
guard try members(of:venue).contains(where:{ $0.id == singer }) else { throw LibraryError.message("This singer is not in the target venue") }
try execute("BEGIN IMMEDIATE")
do {
var ids = try tonightSongIDs(venue:venue)[singer] ?? []
if let before, !ids.contains(before) { throw LibraryError.message("The drop target changed. Please drop again.") }
if !ids.contains(song) && !addIfNeeded { throw LibraryError.message("This Tonight request no longer exists") }
if addIfNeeded {
try assignSong(song,singer:singer)
try execute("INSERT OR IGNORE INTO singer_tonight(venue,singer,song,position) VALUES(?,?,?,0)",[String(venue),String(singer),String(song)])
try execute("INSERT INTO queue(venue,song,singer,position) SELECT ?,?,?,(SELECT COALESCE(MAX(position),0)+1 FROM queue WHERE venue=?) WHERE NOT EXISTS(SELECT 1 FROM queue WHERE venue=? AND singer=? AND song=?)",[String(venue),String(song),String(singer),String(venue),String(venue),String(singer),String(song)])
}
if before != song {
ids.removeAll { $0 == song }
if let before,let index = ids.firstIndex(of:before) { ids.insert(song,at:index) } else { ids.append(song) }
}
for (index,id) in ids.enumerated() { try execute("UPDATE singer_tonight SET position=? WHERE venue=? AND singer=? AND song=?",[String(index),String(venue),String(singer),String(id)]) }
let all = try queue(venue:venue)
let slots = all.indices.filter { all[$0].singerID == singer }
let rank = Dictionary(uniqueKeysWithValues:ids.enumerated().map { ($0.element,$0.offset) })
let requests = slots.enumerated().map { (original:$0.offset,row:all[$0.element]) }.sorted {
let a = rank[$0.row.songID] ?? Int.max,b = rank[$1.row.songID] ?? Int.max
return a == b ? $0.original < $1.original : a < b
}
var ordered = all
for (slot,request) in zip(slots,requests) { ordered[slot] = request.row }
for (index,row) in ordered.enumerated() { try execute("UPDATE queue SET position=? WHERE id=?",[String(index),String(row.id)]) }
try execute("COMMIT")
} catch { try? execute("ROLLBACK");throw error }
}
}
@@ -0,0 +1,277 @@
import SwiftUI
import AVFoundation
import CryptoKit
/// CDG follows consumed source frames, so tempo adjustment preserves graphics timing.
@MainActor final class Player: ObservableObject {
@Published var image: CGImage?
@Published private(set) var waveform = [Float]()
@Published private(set) var waveformBands = [WaveformBands]()
@Published var lowGain: Double = 0 { didSet { updateTone() } }
@Published var midGain: Double = 0 { didSet { updateTone() } }
@Published var highGain: Double = 0 { didSet { updateTone() } }
@Published var filter: Double = 0 { didSet { updateTone() } }
@Published var toneEnabled = true { didSet { updateTone() } }
@Published private(set) var leftLevel: Float = 0
@Published private(set) var rightLevel: Float = 0
private let tone = AVAudioUnitEQ(numberOfBands:4)
private let meter = AudioLevelMeter()
private var metering = false
@Published private(set) var waveformLoading = false
@Published private(set) var waveformUnavailable = false
@Published private(set) var waveformFromCache = false
@Published private(set) var waveformSaved = false
private let waveformCacheDirectory: URL
private var audioURL: URL?
private var waveformTask: Task<Void, Never>?
private var waveformGeneration = UUID()
@Published var playing = false
@Published var time: Double = 0
@Published var duration: Double = 0
@Published var title = "Select a song"
@Published var volume: Double = 0.8 { didSet { engine.mainMixerNode.outputVolume = Float(volume) } }
@Published var repeating = false
@Published var pitch: Double = 0 { didSet { effect.pitch = Float(pitch * 100) } }
@Published var tempo: Double = 1 { didSet { effect.rate = Float(tempo) } }
@Published var graphicsOffset: Double = 0
private(set) var currentSongID: Int64?
var onFinished: (() -> Void)?
private let engine = AVAudioEngine()
private let node = AVAudioPlayerNode()
private let effect = AVAudioUnitTimePitch()
private var file: AVAudioFile?
private var anchor: Double = 0
private var generation = UUID()
private var cdg = Data()
private var decoder = CDGDecoder()
private var timer: Timer?
init(waveformCacheDirectory: URL? = nil) {
self.waveformCacheDirectory = waveformCacheDirectory ?? FileManager.default.urls(for:.applicationSupportDirectory,in:.userDomainMask)[0].appendingPathComponent("KJamsClone/Waveforms")
engine.attach(node);engine.attach(effect);engine.attach(tone);updateTone()
}
func reanalyseWaveform() { if let audioURL { analyseWaveform(audioURL,force:true) } }
func resetTone() { lowGain = 0; midGain = 0; highGain = 0; filter = 0; toneEnabled = true }
private func updateTone() {
AudioTone.configure(tone,sampleRate:file?.processingFormat.sampleRate ?? 44100,low:lowGain,mid:midGain,high:highGain,filter:filter,enabled:toneEnabled)
}
func load(_ song: Song, preference: SongPreference = .init()) throws {
stop()
do {
let loaded = try AVAudioFile(forReading:URL(fileURLWithPath:song.audio))
let graphics = try song.cdg.map { try Data(contentsOf:URL(fileURLWithPath:$0)) } ?? Data()
guard loaded.length > 0 else { throw LibraryError.message("Audio file is empty") }
engine.connect(node,to:effect,format:loaded.processingFormat)
engine.connect(effect,to:tone,format:loaded.processingFormat)
engine.connect(tone,to:engine.mainMixerNode,format:loaded.processingFormat)
file = loaded; cdg = graphics; decoder = CDGDecoder()
duration = Double(loaded.length)/loaded.processingFormat.sampleRate
title = song.title; currentSongID = song.id
pitch = preference.pitch; tempo = preference.tempo
updateTone()
let meter = self.meter
engine.mainMixerNode.installTap(onBus:0,bufferSize:1024,format:nil) { buffer, _ in meter.consume(buffer) }
metering = true
engine.mainMixerNode.outputVolume = Float(volume)
engine.prepare(); try engine.start()
schedule(at:0,play:true); startTimer(); tick()
audioURL = URL(fileURLWithPath:song.audio)
analyseWaveform(audioURL!)
} catch { stop(); throw error }
}
private func analyseWaveform(_ url: URL, force: Bool = false) {
waveformTask?.cancel()
let token = UUID();waveformGeneration = token;waveformLoading = true;waveformUnavailable = false
let directory = waveformCacheDirectory
waveformTask = Task.detached(priority:.utility) { [weak self] in
let result: Result<AudioWaveform.Analysis,Error>
var cached = false,saved = false
do {
if !force,let analysis = try? WaveformCache.load(audio:url,directory:directory) {
result = .success(analysis);cached = true;saved = true
} else {
let analysis = try AudioWaveform.analyse(url:url,cancelled:{ Task.isCancelled })
if !Task.isCancelled { saved = (try? WaveformCache.save(analysis,audio:url,directory:directory)) != nil }
result = .success(analysis)
}
} catch { result = .failure(error) }
guard !Task.isCancelled else { return }
let loadedFromCache = cached,analysisSaved = saved
await MainActor.run { [weak self] in
guard let self,self.waveformGeneration == token else { return }
self.waveformLoading = false;self.waveformFromCache = loadedFromCache;self.waveformSaved = analysisSaved
switch result {
case .success(let analysis):self.waveform = analysis.levels;self.waveformBands = analysis.bands
case .failure:self.waveformUnavailable = true
}
}
}
}
private func schedule(at seconds: Double, play: Bool) {
guard let file else { return }
generation = UUID(); let token = generation
node.stop()
let rate = file.processingFormat.sampleRate
let start = min(file.length,max(0,AVAudioFramePosition(seconds*rate)))
anchor = Double(start)/rate; time = anchor
guard start < file.length else { playing = false; render(); return }
node.scheduleSegment(file,startingFrame:start,frameCount:AVAudioFrameCount(min(file.length-start,Int64(UInt32.max))),at:nil,completionCallbackType:.dataPlayedBack) { [weak self] _ in
Task { @MainActor in
guard let self, self.generation == token else { return }
if self.repeating { self.schedule(at:0,play:true) }
else {
self.playing = false; self.time = self.duration; self.render()
self.timer?.invalidate(); self.timer = nil; self.onFinished?()
}
}
}
if play { node.play() }; playing = play; render()
}
private func startTimer() {
timer?.invalidate()
timer = Timer.scheduledTimer(withTimeInterval:1.0/30,repeats:true) { [weak self] _ in Task { @MainActor in self?.tick() } }
}
func toggle() {
guard file != nil else { return }
if playing { tick(); node.pause(); playing = false }
else if time >= duration { schedule(at:0,play:true); startTimer() }
else { node.play(); playing = true; startTimer() }
}
func stop() {
waveformTask?.cancel(); waveformTask = nil; waveformGeneration = UUID()
waveform = [];waveformBands = [];waveformLoading = false;waveformUnavailable = false;waveformFromCache = false;waveformSaved = false;audioURL = nil
generation = UUID(); timer?.invalidate(); timer = nil; node.stop(); engine.stop()
if metering { engine.mainMixerNode.removeTap(onBus:0); metering = false }
meter.reset(); leftLevel = 0; rightLevel = 0
engine.disconnectNodeOutput(node); engine.disconnectNodeOutput(effect); engine.disconnectNodeOutput(tone)
file = nil; playing = false; time = 0; anchor = 0; duration = 0; image = nil; currentSongID = nil; title = "Select a song"
}
func seek(_ value: Double) {
guard file != nil, value.isFinite else { return }
schedule(at:min(max(value,0),duration),play:playing); startTimer()
}
private func render() { decoder.render(cdg,at:max(0,time+graphicsOffset)); image = cdg.isEmpty ? nil : decoder.image() }
private func tick() {
let levels = meter.snapshot()
leftLevel = playing ? levels.0 : 0; rightLevel = playing ? levels.1 : 0
if playing, let file, let renderTime = node.lastRenderTime, let playerTime = node.playerTime(forNodeTime:renderTime) {
time = min(duration,max(0,anchor+Double(playerTime.sampleTime)/file.processingFormat.sampleRate))
}
render()
}
}
/// Streams fixed-size PCM chunks into a bounded RMS envelope, independent of playback.
/// A separate AVAudioFile keeps analysis away from the player's scheduling/read position.
enum AudioWaveform {
struct Analysis: Codable, Sendable { var levels: [Float]; var bands: [WaveformBands] }
static func read(url: URL, bins: Int = 4096, cancelled: () -> Bool = { false }) throws -> [Float] {
try analyse(url:url,bins:bins,cancelled:cancelled).levels
}
static func analyse(url: URL, bins: Int = 4096, cancelled: () -> Bool = { false }) throws -> Analysis {
guard bins > 0 else { return .init(levels:[],bands:[]) }
let file = try AVAudioFile(forReading: url, commonFormat: .pcmFormatFloat32, interleaved: false)
guard file.length > 0, let buffer = AVAudioPCMBuffer(pcmFormat: file.processingFormat, frameCapacity: 16384) else { return .init(levels:[],bands:[]) }
var energy = [Double](repeating: 0, count: bins)
var counts = [Int](repeating: 0, count: bins)
var position: Int64 = 0
let channels = Int(file.processingFormat.channelCount)
let rate = file.processingFormat.sampleRate
let lowAlpha = exp(-2*Double.pi*250/rate), highAlpha = exp(-2*Double.pi*2500/rate)
var lowState = [Double](repeating:0,count:channels), highState = lowState
var lows = [Double](repeating:0,count:bins), mids = lows, highs = lows
while position < file.length {
if cancelled() { throw CancellationError() }
try file.read(into: buffer, frameCount: AVAudioFrameCount(min(16384, file.length-position)))
let frames = Int(buffer.frameLength)
guard frames > 0, let data = buffer.floatChannelData else { break }
for frame in 0..<frames {
let bin = min(bins-1, Int((position+Int64(frame))*Int64(bins)/file.length))
var sum: Double = 0
for channel in 0..<channels {
let sample = Double(data[channel][frame])
if sample.isFinite {
sum += sample * sample
lowState[channel] = lowAlpha*lowState[channel]+(1-lowAlpha)*sample
highState[channel] = highAlpha*highState[channel]+(1-highAlpha)*sample
let low = lowState[channel], mid = highState[channel]-low, high = sample-highState[channel]
lows[bin] += low*low; mids[bin] += mid*mid; highs[bin] += high*high
}
}
energy[bin] += sum / Double(max(channels,1)); counts[bin] += 1
}
position += Int64(frames)
}
let rms = zip(energy, counts).map { $1 > 0 ? sqrt($0/Double($1)) : 0 }
let peak = rms.max() ?? 0
let levels = peak > 0 ? rms.map { Float(pow(min(1,$0/peak),0.7)) } : [Float](repeating:0,count:bins)
let bands = (0..<bins).map { i in WaveformBands(low:Float(sqrt(lows[i])),mid:Float(sqrt(mids[i])),high:Float(sqrt(highs[i]))) }
return .init(levels:levels,bands:bands)
}
}
struct WaveformBands: Codable, Sendable {
var low: Float
var mid: Float
var high: Float
}
/// Four real audio filters; the filter knob is low-pass left, bypass at centre, high-pass right.
enum AudioTone {
static func configure(_ eq: AVAudioUnitEQ, sampleRate: Double, low: Double, mid: Double, high: Double, filter: Double, enabled: Bool) {
eq.bypass = !enabled
let frequencies = [160.0,1000.0,6000.0]
let types: [AVAudioUnitEQFilterType] = [.lowShelf,.parametric,.highShelf]
for i in 0..<3 {
let band = eq.bands[i];band.filterType = types[i];band.frequency = Float(min(frequencies[i],sampleRate*0.4))
band.bandwidth = 1;band.gain = Float(min(12,max(-12,[low,mid,high][i])));band.bypass = false
}
let value = min(1,max(-1,filter))
let band = eq.bands[3];band.bypass = abs(value) < 0.01;band.bandwidth = 0.7
band.filterType = value < 0 ? .lowPass : .highPass
let frequency = value < 0 ? 20000*pow(0.004,-value) : 20*pow(400,value)
band.frequency = Float(min(sampleRate*0.45,max(20,frequency)))
}
}
/// The audio callback only updates a tiny locked snapshot; UI reads it on the existing clock.
final class AudioLevelMeter: @unchecked Sendable {
private let lock = NSLock()
private var levels: (Float,Float) = (0,0)
func consume(_ buffer: AVAudioPCMBuffer) {
guard let data = buffer.floatChannelData else { return }
let channels = Int(buffer.format.channelCount), frames = Int(buffer.frameLength)
var left: Float = 0, right: Float = 0
for i in 0..<frames {
left = max(left,abs(data[0][i]));right = max(right,abs(data[min(1,channels-1)][i]))
}
lock.lock();levels = (left,right);lock.unlock()
}
func snapshot() -> (Float,Float) { lock.lock();defer { lock.unlock() };return levels }
func reset() { lock.lock();levels = (0,0);lock.unlock() }
}
/// Persistent analysis cache: file path, size, modification time and analyser version form its key.
/// Invalid or obsolete entries are treated as misses, never as playback errors.
enum WaveformCache {
static func location(audio: URL,directory: URL) throws -> URL {
let values = try FileManager.default.attributesOfItem(atPath:audio.path)
let stamp = (values[.modificationDate] as? Date)?.timeIntervalSince1970 ?? 0
let size = (values[.size] as? NSNumber)?.int64Value ?? 0
let signature = "rgb-rms-v2-4096|\(audio.standardizedFileURL.path)|\(size)|\(stamp)"
let key = SHA256.hash(data:Data(signature.utf8)).map { String(format:"%02x",$0) }.joined()
return directory.appendingPathComponent(key+".waveform")
}
static func load(audio: URL,directory: URL) throws -> AudioWaveform.Analysis {
let url = try location(audio:audio,directory:directory)
let data = try Data(contentsOf:url)
guard data.count < 4_000_000 else { throw LibraryError.message("Invalid waveform cache") }
let analysis = try PropertyListDecoder().decode(AudioWaveform.Analysis.self,from:data)
guard analysis.levels.count == 4096,analysis.bands.count == 4096,
analysis.levels.allSatisfy({ $0.isFinite && $0 >= 0 && $0 <= 1 }),
analysis.bands.allSatisfy({ $0.low.isFinite && $0.mid.isFinite && $0.high.isFinite && $0.low >= 0 && $0.mid >= 0 && $0.high >= 0 }) else { throw LibraryError.message("Invalid waveform cache") }
return analysis
}
static func save(_ analysis: AudioWaveform.Analysis,audio: URL,directory: URL) throws {
try FileManager.default.createDirectory(at:directory,withIntermediateDirectories:true)
let encoder = PropertyListEncoder();encoder.outputFormat = .binary
try encoder.encode(analysis).write(to:location(audio:audio,directory:directory),options:.atomic)
}
}
+4
View File
@@ -0,0 +1,4 @@
#!/bin/bash
set -euo pipefail
cd "$(dirname "$0")/.."
xcodebuild -project KJamsClone.xcodeproj -scheme KJamsClone -configuration Debug -destination 'platform=macOS' -derivedDataPath "${DERIVED_DATA:-$PWD/build}" CODE_SIGNING_ALLOWED=NO build "$@"
@@ -0,0 +1,100 @@
#!/usr/bin/env python3
"""Original synthetic MP3+G test media. Regeneration requires ffmpeg; playback does not."""
from pathlib import Path
import wave,struct,math,subprocess,zipfile,shutil
root=Path(__file__).resolve().parents[1]/'Fixtures';root.mkdir(exist_ok=True)
font={
'A':['01110','10001','10001','11111','10001','10001','10001'],
'C':['01111','10000','10000','10000','10000','10000','01111'],
'D':['11110','10001','10001','10001','10001','10001','11110'],
'E':['11111','10000','10000','11110','10000','10000','11111'],
'F':['11111','10000','10000','11110','10000','10000','10000'],
'G':['01111','10000','10000','10111','10001','10001','01111'],
'H':['10001','10001','10001','11111','10001','10001','10001'],
'I':['11111','00100','00100','00100','00100','00100','11111'],
'J':['00111','00010','00010','00010','10010','10010','01100'],
'K':['10001','10010','10100','11000','10100','10010','10001'],
'L':['10000','10000','10000','10000','10000','10000','11111'],
'M':['10001','11011','10101','10101','10001','10001','10001'],
'N':['10001','11001','10101','10011','10001','10001','10001'],
'O':['01110','10001','10001','10001','10001','10001','01110'],
'P':['11110','10001','10001','11110','10000','10000','10000'],
'R':['11110','10001','10001','11110','10100','10010','10001'],
'S':['01111','10000','10000','01110','00001','00001','11110'],
'T':['11111','00100','00100','00100','00100','00100','00100'],
'U':['10001','10001','10001','10001','10001','10001','01110'],
'V':['10001','10001','10001','10001','10001','01010','00100'],
'W':['10001','10001','10001','10101','10101','11011','10001'],
'Y':['10001','10001','01010','00100','00100','00100','00100'],
'3':['11110','00001','00001','01110','00001','00001','11110'],
' ':['00000']*7,
}
def packet(inst,data):return bytes([9,inst,0,0]+(data+[0]*16)[:16]+[0]*4)
packets=[bytes(24) for _ in range(6000)]
def put(index,seq):
for p in seq:
assert packets[index]==bytes(24),'overlapping instructions'
packets[index]=p;index+=1
return index
colors=[0x013,0xfff,0xfd0,0x0cf]+[0]*12
def palette(offset):
data=[]
for c in colors[offset:offset+8]:data.extend([(c>>6)&63,c&63])
return packet(30 if offset==0 else 31,data)
put(0,[palette(0),palette(8),packet(1,[0,0]),packet(2,[0])])
def frame(lines):
pixels=[[0]*300 for _ in range(216)]
for line,(text,y) in enumerate(lines):
x=(300-len(text)*12)//2
for char in text:
for gy,row in enumerate(font[char]):
for gx,bit in enumerate(row):
if bit=='1':
for dy in range(2):
for dx in range(2):pixels[y+gy*2+dy][x+gx*2+dx]=1
x+=12
return pixels
def tiles(pixels,xor=False):
result=[]
for row in range(1,17):
for col in range(1,49):
bits=[]
for y in range(12):
v=0
for x in range(6):v=(v<<1)|pixels[row*12+y][col*6+x]
bits.append(v)
if any(bits):result.append(packet(38 if xor else 6,[0,3 if xor else 1,row,col]+bits))
return result
scenes=[[("KJAMS CLONE",66),("MP3 PLUS G TEST",114)],[("ONE TWO THREE FOUR",66),("SING ALONG",114)],[("WITH THE TEST TONE",66),("PLAY PAUSE SEEK",114)],[("MP3 PLUS G TEST",66),("TEST COMPLETE",114)]]
for index,lines in enumerate(scenes):
start=index*1500+(5 if index==0 else 0)
pixels=frame(lines)
put(start,([packet(1,[0,0])] if index else [])+tiles(pixels))
# Highlight each word after the initial white text has been drawn.
for line,(text,y) in enumerate(lines):
left=(300-len(text)*12)//2
words=text.split();cursor=0
for wi,word in enumerate(words):
mask=[[0]*300 for _ in range(216)]
for py in range(y,y+14):
for px in range(left+cursor*12,left+(cursor+len(word))*12):mask[py][px]=pixels[py][px]
put(index*1500+240+line*600+wi*100,tiles(mask,True))
cursor+=len(word)+1
(root/'TestTrack.cdg').write_bytes(b''.join(packets))
rate=44100;duration=20;notes=[261.63,329.63,392.0,523.25,392.0,329.63,293.66,261.63]
with wave.open(str(root/'TestTrack.wav'),'w') as out:
out.setparams((1,2,rate,0,'NONE','not compressed'))
for beat in range(duration*2):
freq=notes[beat%len(notes)]
data=bytearray()
for i in range(rate//2):
t=i/rate;fade=min(1,t/0.015,(0.5-t)/0.04)
data.extend(struct.pack('<h',int(3000*max(0,fade)*math.sin(2*math.pi*freq*t))))
out.writeframes(data)
ffmpeg=shutil.which('ffmpeg')
if not ffmpeg:raise SystemExit('ffmpeg is needed only to regenerate the included MP3 test file')
subprocess.run([ffmpeg,'-y','-loglevel','error','-i',str(root/'TestTrack.wav'),'-codec:a','libmp3lame','-q:a','5','-metadata','title=MP3 Plus G Test','-metadata','artist=KJamsClone Test Generator','-metadata','album=Original Test Media',str(root/'TestTrack.mp3')],check=True)
with zipfile.ZipFile(root/'TestTrack.zip','w',zipfile.ZIP_DEFLATED) as z:
for name in ['TestTrack.mp3','TestTrack.cdg']:z.write(root/name,name)
(root/'TEST-MEDIA.txt').write_text('Original synthetic 20-second low-volume tone melody and original test text. No vocals or commercial song. Free to use. Import TestTrack.zip, or keep TestTrack.mp3 and TestTrack.cdg together and import the MP3. CDG has timed white-to-yellow word highlighting. Test pause, seek, tempo and key changes. Demo.* remains the original 4-second regression fixture. Unsafe.zip is a deliberately invalid traversal test fixture, not playable media.\n')
print('Created original TestTrack.cdg, TestTrack.mp3, TestTrack.zip and WAV source.')
+6
View File
@@ -0,0 +1,6 @@
#!/bin/bash
set -euo pipefail
cd "$(dirname "$0")/.."
xcodebuild -project KJamsClone.xcodeproj -scheme KJamsClone -configuration Release -destination 'platform=macOS' -derivedDataPath "$PWD/build-release" CODE_SIGNING_ALLOWED=NO build "$@"
mkdir -p dist
/usr/bin/ditto -c -k --sequesterRsrc --keepParent build-release/Build/Products/Release/KJamsClone.app dist/KJamsClone-unsigned-macOS.zip
+4
View File
@@ -0,0 +1,4 @@
#!/bin/bash
set -euo pipefail
cd "$(dirname "$0")/.."
xcodebuild -project KJamsClone.xcodeproj -scheme KJamsClone -configuration Debug -destination 'platform=macOS' -derivedDataPath "${DERIVED_DATA:-$PWD/build}" CODE_SIGNING_ALLOWED=NO test "$@"