removed unwanted bar now with waveforms, major updates
This commit is contained in:
+49
-11
@@ -23,16 +23,20 @@ import CoreAudio
|
||||
@Published var loopEnabled = false { didSet {
|
||||
if loopEnabled { prepareNativeLoop() }
|
||||
else {
|
||||
loopBufferTask?.cancel();loopBufferTask = nil;loopBuffer = nil
|
||||
if nativeLoopActive { let position = displayTime;nativeLoopActive = false;schedule(at:position,play:playing) }
|
||||
loopBufferTask?.cancel();loopBufferTask = nil
|
||||
if nativeLoopActive,!exitNativeLoopWithoutRestart() { let position = displayTime;nativeLoopActive = false;schedule(at:position,play:playing) }
|
||||
loopBuffer = nil;preparedRawLoop = nil
|
||||
}
|
||||
} }
|
||||
private var loopBufferTask: Task<Void,Never>?
|
||||
private var loopBuffer: AVAudioPCMBuffer?
|
||||
private var preparedRawLoop: AVAudioPCMBuffer?
|
||||
private var scheduledRawLoop: AVAudioPCMBuffer?
|
||||
private var preparedLoop: ClosedRange<Double>?
|
||||
private var scheduledLoop: ClosedRange<Double>?
|
||||
private var pendingLoopSwitch: (at: Double,range: ClosedRange<Double>)?
|
||||
private var pendingLoopSwitch: (at: Double,range: ClosedRange<Double>,raw: AVAudioPCMBuffer)?
|
||||
private(set) var loopAudioRestartCount = 0
|
||||
private(set) var audioScheduleRestartCount = 0
|
||||
private var rawAudioPosition: Double {
|
||||
guard let file,let render = node.lastRenderTime,let current = node.playerTime(forNodeTime:render) else { return time }
|
||||
return anchor+Double(current.sampleTime)/file.processingFormat.sampleRate
|
||||
@@ -47,19 +51,53 @@ import CoreAudio
|
||||
guard let range = scheduledLoop,position >= range.upperBound else { return position }
|
||||
return range.lowerBound+(position-range.upperBound).truncatingRemainder(dividingBy:range.upperBound-range.lowerBound)
|
||||
}
|
||||
private func exitNativeLoopWithoutRestart() -> Bool {
|
||||
guard playing,let file,let render = node.lastRenderTime,let clock = node.playerTime(forNodeTime:render) else { return false }
|
||||
let sourceTime = rawAudioPosition,pending = pendingLoopSwitch
|
||||
let range = pending.map{sourceTime >= $0.at ? $0.range : scheduledLoop} ?? scheduledLoop
|
||||
let raw = pending.map{sourceTime >= $0.at ? $0.raw : scheduledRawLoop} ?? scheduledRawLoop
|
||||
guard let range,let raw,let source = raw.floatChannelData,!raw.format.isInterleaved else { return false }
|
||||
let position = displayTime,rate = file.processingFormat.sampleRate
|
||||
let offset = max(0,min(Int(raw.frameLength)-1,Int((position-range.lowerBound)*rate)))
|
||||
let count = min(2048,Int(raw.frameLength)-offset)
|
||||
guard count > 0,let bridge = AVAudioPCMBuffer(pcmFormat:raw.format,frameCapacity:AVAudioFrameCount(count)),let output = bridge.floatChannelData else { return false }
|
||||
bridge.frameLength = AVAudioFrameCount(count)
|
||||
for channel in 0..<Int(raw.format.channelCount) { memcpy(output[channel],source[channel].advanced(by:offset),count*MemoryLayout<Float>.size) }
|
||||
let now = mach_absolute_time(),elapsed = render.isHostTimeValid && now >= render.hostTime ? min(0.1,AVAudioTime.seconds(forHostTime:now-render.hostTime))*tempo : 0
|
||||
anchor = position-Double(clock.sampleTime)/rate-elapsed;time = position
|
||||
generation = UUID();let token = generation
|
||||
nativeLoopActive = false;pendingLoopSwitch = nil;scheduledLoop = nil;scheduledRawLoop = nil
|
||||
// Interrupt only the scheduled loop, leaving the running node and its clock intact.
|
||||
node.scheduleBuffer(bridge,at:nil,options:.interrupts,completionHandler:nil)
|
||||
let next = min(file.length,AVAudioFramePosition(position*rate)+AVAudioFramePosition(count))
|
||||
if next < file.length {
|
||||
node.scheduleSegment(file,startingFrame:next,frameCount:AVAudioFrameCount(min(file.length-next,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.timer?.invalidate();self.timer = nil;self.render();self.onFinished?() }
|
||||
}
|
||||
}
|
||||
}
|
||||
startTimer();self.render();return true
|
||||
}
|
||||
private func prepareNativeLoop() {
|
||||
loopBufferTask?.cancel()
|
||||
guard loopEnabled,let start = loopIn,let end = loopOut,end > start,let url = audioURL else { return }
|
||||
// Bound memory for long manual loops; common beat loops stay sample-timed.
|
||||
guard let file,(end-start)*file.processingFormat.sampleRate*Double(file.processingFormat.channelCount)*4 <= 64*1024*1024 else { return }
|
||||
guard let file,(end-start)*file.processingFormat.sampleRate*Double(file.processingFormat.channelCount)*8 <= 64*1024*1024 else { return }
|
||||
let songID = currentSongID
|
||||
loopBufferTask = Task { @MainActor [weak self] in
|
||||
let worker = Task.detached(priority:.userInitiated) { () throws -> AVAudioPCMBuffer in
|
||||
let worker = Task.detached(priority:.userInitiated) { () throws -> (AVAudioPCMBuffer,AVAudioPCMBuffer) in
|
||||
let source = try AVAudioFile(forReading:url)
|
||||
let first = AVAudioFramePosition(start*source.processingFormat.sampleRate)
|
||||
let count = AVAudioFrameCount(max(1,min(source.length-first,AVAudioFramePosition((end-start)*source.processingFormat.sampleRate))))
|
||||
guard let buffer = AVAudioPCMBuffer(pcmFormat:source.processingFormat,frameCapacity:count) else { throw LibraryError.message("Cannot prepare loop audio") }
|
||||
source.framePosition = first;try source.read(into:buffer,frameCount:count);try Task.checkCancellation()
|
||||
guard let raw = AVAudioPCMBuffer(pcmFormat:buffer.format,frameCapacity:buffer.frameLength) else { throw LibraryError.message("Cannot prepare loop continuation") }
|
||||
raw.frameLength = buffer.frameLength
|
||||
let sourceBuffers = UnsafeMutableAudioBufferListPointer(buffer.mutableAudioBufferList),rawBuffers = UnsafeMutableAudioBufferListPointer(raw.mutableAudioBufferList)
|
||||
for i in sourceBuffers.indices { if let source = sourceBuffers[i].mData,let target = rawBuffers[i].mData { memcpy(target,source,Int(sourceBuffers[i].mDataByteSize)) } }
|
||||
// Meet the first sample at the loop seam without changing its beat length.
|
||||
if let data = buffer.floatChannelData {
|
||||
let frames = Int(buffer.frameLength),stride = Int(buffer.stride)
|
||||
@@ -74,13 +112,13 @@ import CoreAudio
|
||||
}
|
||||
}
|
||||
}
|
||||
return buffer
|
||||
return (buffer,raw)
|
||||
}
|
||||
do {
|
||||
let buffer = try await withTaskCancellationHandler(operation:{try await worker.value},onCancel:{worker.cancel()})
|
||||
let (buffer,raw) = try await withTaskCancellationHandler(operation:{try await worker.value},onCancel:{worker.cancel()})
|
||||
guard !Task.isCancelled,let self,self.currentSongID == songID,self.loopEnabled,self.loopIn == start,self.loopOut == end else { return }
|
||||
let position = self.displayTime,resume = self.playing
|
||||
self.loopBuffer = buffer;self.preparedLoop = start...end
|
||||
self.loopBuffer = buffer;self.preparedRawLoop = raw;self.preparedLoop = start...end
|
||||
if self.nativeLoopActive,resume {
|
||||
let raw = self.rawAudioPosition
|
||||
let activeRange: ClosedRange<Double>
|
||||
@@ -88,7 +126,7 @@ import CoreAudio
|
||||
else { activeRange = self.scheduledLoop ?? start...end }
|
||||
let remaining = max(0,activeRange.upperBound-self.loopPosition(raw))
|
||||
self.node.scheduleBuffer(buffer,at:nil,options:[.loops,.interruptsAtLoop],completionHandler:nil)
|
||||
self.pendingLoopSwitch = (raw+remaining,start...end)
|
||||
self.pendingLoopSwitch = (raw+remaining,start...end,self.preparedRawLoop!)
|
||||
} else {
|
||||
self.loopAudioRestartCount += 1
|
||||
self.schedule(at:position < end ? position : start,play:resume,notifyPlayback:false)
|
||||
@@ -382,7 +420,7 @@ import CoreAudio
|
||||
private func schedule(at seconds: Double, play: Bool,notifyPlayback: Bool = true) {
|
||||
guard let file else { return }
|
||||
cancelPendingPlayback();generation = UUID(); let token = generation
|
||||
node.stop();if !fading { setFade(1) }
|
||||
node.stop();audioScheduleRestartCount += 1;if !fading { setFade(1) }
|
||||
let rate = file.processingFormat.sampleRate
|
||||
let start = min(file.length,max(0,AVAudioFramePosition(seconds*rate)))
|
||||
anchor = Double(start)/rate; time = anchor
|
||||
@@ -393,7 +431,7 @@ import CoreAudio
|
||||
let remainder = AVAudioFrameCount(max(1,endFrame-start))
|
||||
node.scheduleSegment(file,startingFrame:start,frameCount:remainder,at:nil)
|
||||
node.scheduleBuffer(loopBuffer,at:nil,options:.loops)
|
||||
nativeLoopActive = true;scheduledLoop = range
|
||||
nativeLoopActive = true;scheduledLoop = range;scheduledRawLoop = preparedRawLoop
|
||||
if play { if notifyPlayback { startNodePlayback() } else { node.play() } }
|
||||
playing = play;render();return
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user