From 7ac32284ffaa82d96fd5cdd3fd5df2577d5b95df Mon Sep 17 00:00:00 2001 From: Christopher Snowhill Date: Mon, 2 Oct 2023 07:04:26 -0700 Subject: [PATCH] Revert to previous low latency output system This reverts usage of the AVFoundation output to use the previous lower latency CoreAudio output, and paves the way for a change I am cooking up soon. Fixes several issues with playback and seeking latency. Signed-off-by: Christopher Snowhill --- Audio/AudioPlayer.m | 6 +- Audio/Chain/BufferChain.h | 5 +- Audio/Chain/BufferChain.m | 23 +- Audio/Chain/ConverterNode.h | 29 +- Audio/Chain/ConverterNode.m | 187 +++++++- Audio/Chain/Node.m | 2 +- Audio/Chain/OutputNode.h | 4 +- Audio/Chain/OutputNode.m | 5 +- Audio/CogAudio.xcodeproj/project.pbxproj | 52 +- Audio/Output/OutputCoreAudio.h | 4 +- Audio/Output/OutputCoreAudio.m | 262 +++------- Audio/ThirdParty/lvqcl/License/LICENSE.LGPL | 504 ++++++++++++++++++++ Audio/ThirdParty/lvqcl/License/License.txt | 39 ++ Audio/ThirdParty/lvqcl/lpc.c | 193 ++++++++ Audio/ThirdParty/lvqcl/lpc.h | 40 ++ Audio/ThirdParty/lvqcl/util.h | 55 +++ 16 files changed, 1184 insertions(+), 226 deletions(-) create mode 100644 Audio/ThirdParty/lvqcl/License/LICENSE.LGPL create mode 100644 Audio/ThirdParty/lvqcl/License/License.txt create mode 100644 Audio/ThirdParty/lvqcl/lpc.c create mode 100644 Audio/ThirdParty/lvqcl/lpc.h create mode 100644 Audio/ThirdParty/lvqcl/util.h diff --git a/Audio/AudioPlayer.m b/Audio/AudioPlayer.m index 5311815c0..0e378e860 100644 --- a/Audio/AudioPlayer.m +++ b/Audio/AudioPlayer.m @@ -91,7 +91,7 @@ bufferChain = [[BufferChain alloc] initWithController:self]; [self notifyStreamChanged:userInfo]; - while(![bufferChain open:url withUserInfo:userInfo withRGInfo:rgi]) { + while(![bufferChain open:url withOutputFormat:[output format] withUserInfo:userInfo withRGInfo:rgi]) { bufferChain = nil; [self requestNextStream:userInfo]; @@ -401,7 +401,7 @@ } if(pathsEqual || ([[nextStream scheme] isEqualToString:[[lastChain streamURL] scheme]] && (([nextStream host] == nil && [[lastChain streamURL] host] == nil) || [[nextStream host] isEqualToString:[[lastChain streamURL] host]]) && [[nextStream path] isEqualToString:[[lastChain streamURL] path]])) { - if([lastChain setTrack:nextStream] && [newChain openWithInput:[lastChain inputNode] withUserInfo:nextStreamUserInfo withRGInfo:nextStreamRGInfo]) { + if([lastChain setTrack:nextStream] && [newChain openWithInput:[lastChain inputNode] withOutputFormat:[output format] withUserInfo:nextStreamUserInfo withRGInfo:nextStreamRGInfo]) { [newChain setStreamURL:nextStream]; @synchronized(chainQueue) { @@ -420,7 +420,7 @@ NSURL *url = nextStream; - while(shouldContinue && ![newChain open:url withUserInfo:nextStreamUserInfo withRGInfo:nextStreamRGInfo]) { + while(shouldContinue && ![newChain open:url withOutputFormat:[output format] withUserInfo:nextStreamUserInfo withRGInfo:nextStreamRGInfo]) { if(nextStream == nil) { newChain = nil; if(output) diff --git a/Audio/Chain/BufferChain.h b/Audio/Chain/BufferChain.h index b9b84d8d9..0e649da23 100644 --- a/Audio/Chain/BufferChain.h +++ b/Audio/Chain/BufferChain.h @@ -28,13 +28,14 @@ - (id)initWithController:(id)c; - (void)buildChain; -- (BOOL)open:(NSURL *)url withUserInfo:(id)userInfo withRGInfo:(NSDictionary *)rgi; +- (BOOL)open:(NSURL *)url withOutputFormat:(AudioStreamBasicDescription)outputFormat withUserInfo:(id)userInfo withRGInfo:(NSDictionary *)rgi; // Used when changing tracks to reuse the same decoder -- (BOOL)openWithInput:(InputNode *)i withUserInfo:(id)userInfo withRGInfo:(NSDictionary *)rgi; +- (BOOL)openWithInput:(InputNode *)i withOutputFormat:(AudioStreamBasicDescription)outputFormat withUserInfo:(id)userInfo withRGInfo:(NSDictionary *)rgi; // Used when resetting the decoder on seek - (BOOL)openWithDecoder:(id)decoder + withOutputFormat:(AudioStreamBasicDescription)outputFormat withUserInfo:(id)userInfo withRGInfo:(NSDictionary *)rgi; diff --git a/Audio/Chain/BufferChain.m b/Audio/Chain/BufferChain.m index 1ff7a08c8..bccd2f56e 100644 --- a/Audio/Chain/BufferChain.m +++ b/Audio/Chain/BufferChain.m @@ -40,7 +40,7 @@ finalNode = converterNode; } -- (BOOL)open:(NSURL *)url withUserInfo:(id)userInfo withRGInfo:(NSDictionary *)rgi { +- (BOOL)open:(NSURL *)url withOutputFormat:(AudioStreamBasicDescription)outputFormat withUserInfo:(id)userInfo withRGInfo:(NSDictionary *)rgi { [self setStreamURL:url]; [self setUserInfo:userInfo]; @@ -66,7 +66,11 @@ if([properties valueForKey:@"channelConfig"]) inputChannelConfig = [[properties valueForKey:@"channelConfig"] unsignedIntValue]; - if(![converterNode setupWithInputFormat:inputFormat withInputConfig:inputChannelConfig isLossless:[[properties valueForKey:@"encoding"] isEqualToString:@"lossless"]]) + outputFormat.mChannelsPerFrame = inputFormat.mChannelsPerFrame; + outputFormat.mBytesPerFrame = ((outputFormat.mBitsPerChannel + 7) / 8) * outputFormat.mChannelsPerFrame; + outputFormat.mBytesPerPacket = outputFormat.mBytesPerFrame * outputFormat.mFramesPerPacket; + + if(![converterNode setupWithInputFormat:inputFormat withInputConfig:inputChannelConfig outputFormat:outputFormat isLossless:[[properties valueForKey:@"encoding"] isEqualToString:@"lossless"]]) return NO; [self setRGInfo:rgi]; @@ -76,7 +80,7 @@ return YES; } -- (BOOL)openWithInput:(InputNode *)i withUserInfo:(id)userInfo withRGInfo:(NSDictionary *)rgi { +- (BOOL)openWithInput:(InputNode *)i withOutputFormat:(AudioStreamBasicDescription)outputFormat withUserInfo:(id)userInfo withRGInfo:(NSDictionary *)rgi { DLog(@"New buffer chain!"); [self setUserInfo:userInfo]; [self buildChain]; @@ -91,8 +95,12 @@ if([properties valueForKey:@"channelConfig"]) inputChannelConfig = [[properties valueForKey:@"channelConfig"] unsignedIntValue]; + outputFormat.mChannelsPerFrame = inputFormat.mChannelsPerFrame; + outputFormat.mBytesPerFrame = ((outputFormat.mBitsPerChannel + 7) / 8) * outputFormat.mChannelsPerFrame; + outputFormat.mBytesPerPacket = outputFormat.mBytesPerFrame * outputFormat.mFramesPerPacket; + DLog(@"Input Properties: %@", properties); - if(![converterNode setupWithInputFormat:inputFormat withInputConfig:inputChannelConfig isLossless:[[properties objectForKey:@"encoding"] isEqualToString:@"lossless"]]) + if(![converterNode setupWithInputFormat:inputFormat withInputConfig:inputChannelConfig outputFormat:outputFormat isLossless:[[properties objectForKey:@"encoding"] isEqualToString:@"lossless"]]) return NO; [self setRGInfo:rgi]; @@ -101,6 +109,7 @@ } - (BOOL)openWithDecoder:(id)decoder + withOutputFormat:(AudioStreamBasicDescription)outputFormat withUserInfo:(id)userInfo withRGInfo:(NSDictionary *)rgi; { @@ -120,7 +129,11 @@ if([properties valueForKey:@"channelConfig"]) inputChannelConfig = [[properties valueForKey:@"channelConfig"] unsignedIntValue]; - if(![converterNode setupWithInputFormat:inputFormat withInputConfig:inputChannelConfig isLossless:[[properties objectForKey:@"encoding"] isEqualToString:@"lossless"]]) + outputFormat.mChannelsPerFrame = inputFormat.mChannelsPerFrame; + outputFormat.mBytesPerFrame = ((outputFormat.mBitsPerChannel + 7) / 8) * outputFormat.mChannelsPerFrame; + outputFormat.mBytesPerPacket = outputFormat.mBytesPerFrame * outputFormat.mFramesPerPacket; + + if(![converterNode setupWithInputFormat:inputFormat withInputConfig:inputChannelConfig outputFormat:outputFormat isLossless:[[properties objectForKey:@"encoding"] isEqualToString:@"lossless"]]) return NO; [self setRGInfo:rgi]; diff --git a/Audio/Chain/ConverterNode.h b/Audio/Chain/ConverterNode.h index c61612d5c..b96a70ba3 100644 --- a/Audio/Chain/ConverterNode.h +++ b/Audio/Chain/ConverterNode.h @@ -12,11 +12,15 @@ #import #import +#import + #import "Node.h" @interface ConverterNode : Node { NSDictionary *rgInfo; + soxr_t soxr; + void *inputBuffer; size_t inputBufferSize; size_t inpSize, inpOffset; @@ -25,12 +29,33 @@ BOOL convertEntered; BOOL paused; + BOOL skipResampler; + + unsigned int PRIME_LEN_; + unsigned int N_samples_to_add_; + unsigned int N_samples_to_drop_; + + BOOL is_preextrapolated_; + int is_postextrapolated_; + + int latencyEaten; + int latencyEatenPost; + + double sampleRatio; + float volumeScale; + void *floatBuffer; + size_t floatBufferSize; + + void *extrapolateBuffer; + size_t extrapolateBufferSize; + BOOL rememberedLossless; AudioStreamBasicDescription inputFormat; AudioStreamBasicDescription floatFormat; + AudioStreamBasicDescription outputFormat; uint32_t inputChannelConfig; @@ -43,7 +68,7 @@ - (id)initWithController:(id)c previous:(id)p; -- (BOOL)setupWithInputFormat:(AudioStreamBasicDescription)inputFormat withInputConfig:(uint32_t)inputConfig isLossless:(BOOL)lossless; +- (BOOL)setupWithInputFormat:(AudioStreamBasicDescription)inputFormat withInputConfig:(uint32_t)inputConfig outputFormat:(AudioStreamBasicDescription)outputFormat isLossless:(BOOL)lossless; - (void)cleanUp; - (void)process; @@ -51,6 +76,8 @@ - (void)setRGInfo:(NSDictionary *)rgi; +- (void)setOutputFormat:(AudioStreamBasicDescription)outputFormat; + - (void)inputFormatDidChange:(AudioStreamBasicDescription)format inputConfig:(uint32_t)inputConfig; - (void)refreshVolumeScaling; diff --git a/Audio/Chain/ConverterNode.m b/Audio/Chain/ConverterNode.m index d4ca808fc..5ae201bd4 100644 --- a/Audio/Chain/ConverterNode.m +++ b/Audio/Chain/ConverterNode.m @@ -16,6 +16,9 @@ #import "Logging.h" +#import "lpc.h" +#import "util.h" + #ifdef _DEBUG #import "BadSampleCleaner.h" #endif @@ -48,13 +51,21 @@ static void *kConverterNodeContext = &kConverterNodeContext; if(self) { rgInfo = nil; + soxr = 0; inputBuffer = NULL; inputBufferSize = 0; + floatBuffer = NULL; + floatBufferSize = 0; stopping = NO; convertEntered = NO; paused = NO; + skipResampler = YES; + + extrapolateBuffer = NULL; + extrapolateBufferSize = 0; + [[NSUserDefaultsController sharedUserDefaultsController] addObserver:self forKeyPath:@"values.volumeScaling" options:0 context:kConverterNodeContext]; } @@ -102,8 +113,10 @@ void scale_by_volume(float *buffer, size_t count, float volume) { } } if(streamFormatChanged) { - [self cleanUp]; - [self setupWithInputFormat:newInputFormat withInputConfig:newInputChannelConfig isLossless:rememberedLossless]; + @autoreleasepool { + [self cleanUp]; + [self setupWithInputFormat:newInputFormat withInputConfig:newInputChannelConfig outputFormat:self->outputFormat isLossless:rememberedLossless]; + } } } } @@ -173,6 +186,57 @@ void scale_by_volume(float *buffer, size_t count, float volume) { return nil; } + if(stopping || paused || streamFormatChanged || [self shouldContinue] == NO || [self endOfStream] == YES) { + if(!skipResampler) { + if(!is_postextrapolated_) { + is_postextrapolated_ = 1; + } + } else { + is_postextrapolated_ = 3; + } + } + + // Extrapolate start + if(!skipResampler && !is_preextrapolated_) { + size_t inputSamples = bytesReadFromInput / floatFormat.mBytesPerPacket; + size_t prime = MIN(inputSamples, PRIME_LEN_); + size_t _N_samples_to_add_ = N_samples_to_add_; + size_t newSize = _N_samples_to_add_ * floatFormat.mBytesPerPacket; + newSize += bytesReadFromInput; + + if(newSize > inputBufferSize) { + inputBuffer = realloc(inputBuffer, inputBufferSize = newSize * 3); + } + + memmove(inputBuffer + _N_samples_to_add_ * floatFormat.mBytesPerPacket, inputBuffer, bytesReadFromInput); + + lpc_extrapolate_bkwd(inputBuffer + _N_samples_to_add_ * floatFormat.mBytesPerPacket, inputSamples, prime, floatFormat.mChannelsPerFrame, LPC_ORDER, _N_samples_to_add_, &extrapolateBuffer, &extrapolateBufferSize); + + bytesReadFromInput += _N_samples_to_add_ * floatFormat.mBytesPerPacket; + latencyEaten = N_samples_to_drop_; + is_preextrapolated_ = YES; + } + + if(is_postextrapolated_ == 1) { + size_t inputSamples = bytesReadFromInput / floatFormat.mBytesPerPacket; + size_t prime = MIN(inputSamples, PRIME_LEN_); + size_t _N_samples_to_add_ = N_samples_to_add_; + + size_t newSize = bytesReadFromInput; + newSize += _N_samples_to_add_ * floatFormat.mBytesPerPacket; + if(newSize > inputBufferSize) { + inputBuffer = realloc(inputBuffer, inputBufferSize = newSize * 3); + } + + lpc_extrapolate_fwd(inputBuffer, inputSamples, prime, floatFormat.mChannelsPerFrame, LPC_ORDER, _N_samples_to_add_, &extrapolateBuffer, &extrapolateBufferSize); + + bytesReadFromInput += _N_samples_to_add_ * floatFormat.mBytesPerPacket; + latencyEatenPost = N_samples_to_drop_; + is_postextrapolated_ = 2; + } else if(is_postextrapolated_ == 3) { + latencyEatenPost = 0; + } + // Input now contains bytesReadFromInput worth of floats, in the input sample rate inpSize = bytesReadFromInput; inpOffset = 0; @@ -182,16 +246,77 @@ void scale_by_volume(float *buffer, size_t count, float volume) { ioNumberPackets -= ioNumberPackets % floatFormat.mBytesPerPacket; + if(ioNumberPackets) { + size_t inputSamples = ioNumberPackets / floatFormat.mBytesPerPacket; + ioNumberPackets = (UInt32)inputSamples; + ioNumberPackets = (UInt32)ceil((float)ioNumberPackets * sampleRatio); + ioNumberPackets = (ioNumberPackets + 255) & ~255; + + size_t newSize = ioNumberPackets * floatFormat.mBytesPerPacket; + if(!floatBuffer || floatBufferSize < newSize) { + floatBuffer = realloc(floatBuffer, floatBufferSize = newSize * 3); + } + + if(stopping) { + convertEntered = NO; + return nil; + } + + size_t inputDone = 0; + size_t outputDone = 0; + + if(!skipResampler) { + ioNumberPackets += soxr_delay(soxr); + soxr_process(soxr, (float *)(((uint8_t *)inputBuffer) + inpOffset), inputSamples, &inputDone, floatBuffer, ioNumberPackets, &outputDone); + + if(latencyEatenPost) { + // Post file or format change flush + size_t idone = 0, odone = 0; + + do { + soxr_process(soxr, NULL, 0, &idone, floatBuffer + outputDone * floatFormat.mBytesPerPacket, ioNumberPackets - outputDone, &odone); + outputDone += odone; + } while(odone > 0); + } + } else { + memcpy(floatBuffer, (((uint8_t *)inputBuffer) + inpOffset), inputSamples * floatFormat.mBytesPerPacket); + inputDone = inputSamples; + outputDone = inputSamples; + } + + inpOffset += inputDone * floatFormat.mBytesPerPacket; + + if(latencyEaten) { + if(outputDone > latencyEaten) { + outputDone -= latencyEaten; + memmove(floatBuffer, floatBuffer + latencyEaten * floatFormat.mBytesPerPacket, outputDone * floatFormat.mBytesPerPacket); + latencyEaten = 0; + } else { + latencyEaten -= outputDone; + outputDone = 0; + } + } + + if(latencyEatenPost) { + if(outputDone > latencyEatenPost) { + outputDone -= latencyEatenPost; + } else { + outputDone = 0; + } + latencyEatenPost = 0; + } + + ioNumberPackets = (UInt32)outputDone * floatFormat.mBytesPerPacket; + } + if(ioNumberPackets) { AudioChunk *chunk = [[AudioChunk alloc] init]; [chunk setFormat:nodeFormat]; if(nodeChannelConfig) { [chunk setChannelConfig:nodeChannelConfig]; } - scale_by_volume((float *)(((uint8_t *)inputBuffer) + inpOffset), ioNumberPackets / sizeof(float), volumeScale); - [chunk assignSamples:(((uint8_t *)inputBuffer) + inpOffset) frameCount:ioNumberPackets / floatFormat.mBytesPerPacket]; - - inpOffset += ioNumberPackets; + scale_by_volume(floatBuffer, ioNumberPackets / sizeof(float), volumeScale); + [chunk assignSamples:floatBuffer frameCount:ioNumberPackets / floatFormat.mBytesPerPacket]; convertEntered = NO; return chunk; } @@ -260,9 +385,10 @@ static float db_to_scale(float db) { volumeScale = scale; } -- (BOOL)setupWithInputFormat:(AudioStreamBasicDescription)inf withInputConfig:(uint32_t)inputConfig isLossless:(BOOL)lossless { +- (BOOL)setupWithInputFormat:(AudioStreamBasicDescription)inf withInputConfig:(uint32_t)inputConfig outputFormat:(AudioStreamBasicDescription)outf isLossless:(BOOL)lossless { // Make the converter inputFormat = inf; + outputFormat = outf; inputChannelConfig = inputConfig; @@ -289,11 +415,40 @@ static float db_to_scale(float db) { inpOffset = 0; inpSize = 0; - // This is a post resampler, post-down/upmix format + // This is a post resampler format nodeFormat = floatFormat; + nodeFormat.mSampleRate = outputFormat.mSampleRate; nodeChannelConfig = inputChannelConfig; + sampleRatio = (double)outputFormat.mSampleRate / (double)floatFormat.mSampleRate; + skipResampler = fabs(sampleRatio - 1.0) < 1e-7; + if(!skipResampler) { + soxr_quality_spec_t q_spec = soxr_quality_spec(SOXR_HQ, 0); + soxr_io_spec_t io_spec = soxr_io_spec(SOXR_FLOAT32_I, SOXR_FLOAT32_I); + soxr_runtime_spec_t runtime_spec = soxr_runtime_spec(0); + soxr_error_t error; + + soxr = soxr_create(floatFormat.mSampleRate, outputFormat.mSampleRate, floatFormat.mChannelsPerFrame, &error, &io_spec, &q_spec, &runtime_spec); + if(error) + return NO; + + PRIME_LEN_ = MAX(floatFormat.mSampleRate / 20, 1024u); + PRIME_LEN_ = MIN(PRIME_LEN_, 16384u); + PRIME_LEN_ = MAX(PRIME_LEN_, (unsigned int)(2 * LPC_ORDER + 1)); + + N_samples_to_add_ = floatFormat.mSampleRate; + N_samples_to_drop_ = outputFormat.mSampleRate; + + samples_len(&N_samples_to_add_, &N_samples_to_drop_, 20, 8192u); + + is_preextrapolated_ = NO; + is_postextrapolated_ = 0; + } + + latencyEaten = 0; + latencyEatenPost = 0; + PrintStreamDesc(&inf); PrintStreamDesc(&nodeFormat); @@ -324,7 +479,7 @@ static float db_to_scale(float db) { usleep(500); } [self cleanUp]; - [self setupWithInputFormat:format withInputConfig:inputConfig isLossless:rememberedLossless]; + [self setupWithInputFormat:format withInputConfig:inputConfig outputFormat:self->outputFormat isLossless:rememberedLossless]; } - (void)setRGInfo:(NSDictionary *)rgi { @@ -338,6 +493,20 @@ static float db_to_scale(float db) { while(convertEntered) { usleep(500); } + if(soxr) { + soxr_delete(soxr); + soxr = NULL; + } + if(extrapolateBuffer) { + free(extrapolateBuffer); + extrapolateBuffer = NULL; + extrapolateBufferSize = 0; + } + if(floatBuffer) { + free(floatBuffer); + floatBuffer = NULL; + floatBufferSize = 0; + } if(inputBuffer) { free(inputBuffer); inputBuffer = NULL; diff --git a/Audio/Chain/Node.m b/Audio/Chain/Node.m index 6af52ceb3..8a1979cd6 100644 --- a/Audio/Chain/Node.m +++ b/Audio/Chain/Node.m @@ -11,7 +11,7 @@ #import "BufferChain.h" #import "Logging.h" -#import "OutputAVFoundation.h" +#import "OutputCoreAudio.h" #import diff --git a/Audio/Chain/OutputNode.h b/Audio/Chain/OutputNode.h index a1219fa79..23e618dad 100644 --- a/Audio/Chain/OutputNode.h +++ b/Audio/Chain/OutputNode.h @@ -13,7 +13,7 @@ #import #import "Node.h" -#import "OutputAVFoundation.h" +#import "OutputCoreAudio.h" @interface OutputNode : Node { AudioStreamBasicDescription format; @@ -21,7 +21,7 @@ double amountPlayed; double amountPlayedInterval; - OutputAVFoundation *output; + OutputCoreAudio *output; BOOL paused; BOOL started; diff --git a/Audio/Chain/OutputNode.m b/Audio/Chain/OutputNode.m index cb9801b5a..9864e5569 100644 --- a/Audio/Chain/OutputNode.m +++ b/Audio/Chain/OutputNode.m @@ -9,7 +9,7 @@ #import "OutputNode.h" #import "AudioPlayer.h" #import "BufferChain.h" -#import "OutputAVFoundation.h" +#import "OutputCoreAudio.h" #import "Logging.h" @@ -23,7 +23,7 @@ started = NO; intervalReported = NO; - output = [[OutputAVFoundation alloc] initWithController:self]; + output = [[OutputCoreAudio alloc] initWithController:self]; [output setup]; } @@ -149,6 +149,7 @@ format.mBytesPerPacket = format.mBytesPerFrame * format.mFramesPerPacket; channelConfig = config; + [converter setOutputFormat:format]; [converter inputFormatDidChange:[bufferChain inputFormat] inputConfig:[bufferChain inputConfig]]; } } diff --git a/Audio/CogAudio.xcodeproj/project.pbxproj b/Audio/CogAudio.xcodeproj/project.pbxproj index 61b69c9e7..1ed1f7ee4 100644 --- a/Audio/CogAudio.xcodeproj/project.pbxproj +++ b/Audio/CogAudio.xcodeproj/project.pbxproj @@ -25,8 +25,6 @@ 17D21CA80B8BE4BA00D1EBDE /* Node.m in Sources */ = {isa = PBXBuildFile; fileRef = 17D21C7D0B8BE4BA00D1EBDE /* Node.m */; }; 17D21CA90B8BE4BA00D1EBDE /* OutputNode.h in Headers */ = {isa = PBXBuildFile; fileRef = 17D21C7E0B8BE4BA00D1EBDE /* OutputNode.h */; settings = {ATTRIBUTES = (Public, ); }; }; 17D21CAA0B8BE4BA00D1EBDE /* OutputNode.m in Sources */ = {isa = PBXBuildFile; fileRef = 17D21C7F0B8BE4BA00D1EBDE /* OutputNode.m */; }; - 17D21CC50B8BE4BA00D1EBDE /* OutputAVFoundation.h in Headers */ = {isa = PBXBuildFile; fileRef = 17D21C9C0B8BE4BA00D1EBDE /* OutputAVFoundation.h */; settings = {ATTRIBUTES = (Public, ); }; }; - 17D21CC60B8BE4BA00D1EBDE /* OutputAVFoundation.m in Sources */ = {isa = PBXBuildFile; fileRef = 17D21C9D0B8BE4BA00D1EBDE /* OutputAVFoundation.m */; }; 17D21CC70B8BE4BA00D1EBDE /* Status.h in Headers */ = {isa = PBXBuildFile; fileRef = 17D21C9E0B8BE4BA00D1EBDE /* Status.h */; settings = {ATTRIBUTES = (Public, ); }; }; 17D21CF30B8BE5EF00D1EBDE /* CogSemaphore.h in Headers */ = {isa = PBXBuildFile; fileRef = 17D21CF10B8BE5EF00D1EBDE /* CogSemaphore.h */; settings = {ATTRIBUTES = (Public, ); }; }; 17D21CF40B8BE5EF00D1EBDE /* CogSemaphore.m in Sources */ = {isa = PBXBuildFile; fileRef = 17D21CF20B8BE5EF00D1EBDE /* CogSemaphore.m */; }; @@ -66,6 +64,13 @@ 8350416D28646149006B32CC /* CoreMedia.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 8350416C28646149006B32CC /* CoreMedia.framework */; }; 835C88B1279811A500E28EAE /* hdcd_decode2.h in Headers */ = {isa = PBXBuildFile; fileRef = 835C88AF279811A500E28EAE /* hdcd_decode2.h */; }; 835C88B2279811A500E28EAE /* hdcd_decode2.c in Sources */ = {isa = PBXBuildFile; fileRef = 835C88B0279811A500E28EAE /* hdcd_decode2.c */; }; + 835DD2672ACAF1D90057E319 /* OutputCoreAudio.m in Sources */ = {isa = PBXBuildFile; fileRef = 835DD2652ACAF1D90057E319 /* OutputCoreAudio.m */; }; + 835DD2682ACAF1D90057E319 /* OutputCoreAudio.h in Headers */ = {isa = PBXBuildFile; fileRef = 835DD2662ACAF1D90057E319 /* OutputCoreAudio.h */; }; + 835DD2702ACAF5AD0057E319 /* LICENSE.LGPL in Resources */ = {isa = PBXBuildFile; fileRef = 835DD26B2ACAF5AD0057E319 /* LICENSE.LGPL */; }; + 835DD2712ACAF5AD0057E319 /* License.txt in Resources */ = {isa = PBXBuildFile; fileRef = 835DD26C2ACAF5AD0057E319 /* License.txt */; }; + 835DD2722ACAF5AD0057E319 /* lpc.h in Headers */ = {isa = PBXBuildFile; fileRef = 835DD26D2ACAF5AD0057E319 /* lpc.h */; }; + 835DD2732ACAF5AD0057E319 /* util.h in Headers */ = {isa = PBXBuildFile; fileRef = 835DD26E2ACAF5AD0057E319 /* util.h */; }; + 835DD2742ACAF5AD0057E319 /* lpc.c in Sources */ = {isa = PBXBuildFile; fileRef = 835DD26F2ACAF5AD0057E319 /* lpc.c */; }; 835FAC5E27BCA14D00BA8562 /* BadSampleCleaner.h in Headers */ = {isa = PBXBuildFile; fileRef = 835FAC5C27BCA14D00BA8562 /* BadSampleCleaner.h */; }; 835FAC5F27BCA14D00BA8562 /* BadSampleCleaner.m in Sources */ = {isa = PBXBuildFile; fileRef = 835FAC5D27BCA14D00BA8562 /* BadSampleCleaner.m */; }; 836DF618298F6F5F00CD0580 /* libsoxr.0.dylib in Frameworks */ = {isa = PBXBuildFile; fileRef = 836DF615298F6E8900CD0580 /* libsoxr.0.dylib */; }; @@ -132,8 +137,6 @@ 17D21C7D0B8BE4BA00D1EBDE /* Node.m */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.c.objc; path = Node.m; sourceTree = ""; }; 17D21C7E0B8BE4BA00D1EBDE /* OutputNode.h */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.c.h; path = OutputNode.h; sourceTree = ""; }; 17D21C7F0B8BE4BA00D1EBDE /* OutputNode.m */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.c.objc; path = OutputNode.m; sourceTree = ""; }; - 17D21C9C0B8BE4BA00D1EBDE /* OutputAVFoundation.h */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.c.h; path = OutputAVFoundation.h; sourceTree = ""; }; - 17D21C9D0B8BE4BA00D1EBDE /* OutputAVFoundation.m */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.c.objc; path = OutputAVFoundation.m; sourceTree = ""; }; 17D21C9E0B8BE4BA00D1EBDE /* Status.h */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.c.h; path = Status.h; sourceTree = ""; }; 17D21CF10B8BE5EF00D1EBDE /* CogSemaphore.h */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.c.h; path = CogSemaphore.h; sourceTree = ""; }; 17D21CF20B8BE5EF00D1EBDE /* CogSemaphore.m */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.c.objc; path = CogSemaphore.m; sourceTree = ""; }; @@ -174,6 +177,13 @@ 8350416C28646149006B32CC /* CoreMedia.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = CoreMedia.framework; path = System/Library/Frameworks/CoreMedia.framework; sourceTree = SDKROOT; }; 835C88AF279811A500E28EAE /* hdcd_decode2.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = hdcd_decode2.h; sourceTree = ""; }; 835C88B0279811A500E28EAE /* hdcd_decode2.c */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.c; path = hdcd_decode2.c; sourceTree = ""; }; + 835DD2652ACAF1D90057E319 /* OutputCoreAudio.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = OutputCoreAudio.m; sourceTree = ""; }; + 835DD2662ACAF1D90057E319 /* OutputCoreAudio.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = OutputCoreAudio.h; sourceTree = ""; }; + 835DD26B2ACAF5AD0057E319 /* LICENSE.LGPL */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text; path = LICENSE.LGPL; sourceTree = ""; }; + 835DD26C2ACAF5AD0057E319 /* License.txt */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text; path = License.txt; sourceTree = ""; }; + 835DD26D2ACAF5AD0057E319 /* lpc.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = lpc.h; sourceTree = ""; }; + 835DD26E2ACAF5AD0057E319 /* util.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = util.h; sourceTree = ""; }; + 835DD26F2ACAF5AD0057E319 /* lpc.c */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.c; path = lpc.c; sourceTree = ""; }; 835FAC5C27BCA14D00BA8562 /* BadSampleCleaner.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; name = BadSampleCleaner.h; path = Utils/BadSampleCleaner.h; sourceTree = SOURCE_ROOT; }; 835FAC5D27BCA14D00BA8562 /* BadSampleCleaner.m */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.objc; name = BadSampleCleaner.m; path = Utils/BadSampleCleaner.m; sourceTree = SOURCE_ROOT; }; 836DF615298F6E8900CD0580 /* libsoxr.0.dylib */ = {isa = PBXFileReference; lastKnownFileType = "compiled.mach-o.dylib"; name = libsoxr.0.dylib; path = ../ThirdParty/soxr/lib/libsoxr.0.dylib; sourceTree = ""; }; @@ -354,12 +364,12 @@ 17D21C9B0B8BE4BA00D1EBDE /* Output */ = { isa = PBXGroup; children = ( + 835DD2662ACAF1D90057E319 /* OutputCoreAudio.h */, + 835DD2652ACAF1D90057E319 /* OutputCoreAudio.m */, 834A41AD287ABD6F00EB9D9B /* FSurroundFilter.h */, 834A41AE287ABD6F00EB9D9B /* FSurroundFilter.mm */, 839E56EB2879515D00DFB5F4 /* HeadphoneFilter.h */, 839E56EC2879515D00DFB5F4 /* HeadphoneFilter.mm */, - 17D21C9C0B8BE4BA00D1EBDE /* OutputAVFoundation.h */, - 17D21C9D0B8BE4BA00D1EBDE /* OutputAVFoundation.m */, ); path = Output; sourceTree = ""; @@ -367,6 +377,7 @@ 17D21CD80B8BE5B400D1EBDE /* ThirdParty */ = { isa = PBXGroup; children = ( + 835DD2692ACAF5AD0057E319 /* lvqcl */, 834A41A4287A90AB00EB9D9B /* fsurround */, 839E56E02879450300DFB5F4 /* hrtf */, 831A50152865A8800049CFE4 /* rsstate.cpp */, @@ -437,6 +448,26 @@ path = hdcd; sourceTree = ""; }; + 835DD2692ACAF5AD0057E319 /* lvqcl */ = { + isa = PBXGroup; + children = ( + 835DD26A2ACAF5AD0057E319 /* License */, + 835DD26D2ACAF5AD0057E319 /* lpc.h */, + 835DD26E2ACAF5AD0057E319 /* util.h */, + 835DD26F2ACAF5AD0057E319 /* lpc.c */, + ); + path = lvqcl; + sourceTree = ""; + }; + 835DD26A2ACAF5AD0057E319 /* License */ = { + isa = PBXGroup; + children = ( + 835DD26B2ACAF5AD0057E319 /* LICENSE.LGPL */, + 835DD26C2ACAF5AD0057E319 /* License.txt */, + ); + path = License; + sourceTree = ""; + }; 83725A8F27AA16C90003F694 /* Frameworks */ = { isa = PBXGroup; children = ( @@ -488,18 +519,20 @@ 834A41AC287A90AB00EB9D9B /* channelmaps.h in Headers */, 17D21CA50B8BE4BA00D1EBDE /* InputNode.h in Headers */, 834A41A9287A90AB00EB9D9B /* freesurround_decoder.h in Headers */, + 835DD2732ACAF5AD0057E319 /* util.h in Headers */, 17D21CA70B8BE4BA00D1EBDE /* Node.h in Headers */, 8399CF2C27B5D1D5008751F1 /* NSDictionary+Merge.h in Headers */, 17D21CA90B8BE4BA00D1EBDE /* OutputNode.h in Headers */, 8328995427CB511000D7F028 /* RedundantPlaylistDataStore.h in Headers */, - 17D21CC50B8BE4BA00D1EBDE /* OutputAVFoundation.h in Headers */, 83504165286447DA006B32CC /* Downmix.h in Headers */, 839E56E52879450300DFB5F4 /* HrtfData.h in Headers */, 83B74281289E027F005AAC28 /* CogAudio-Bridging-Header.h in Headers */, 17D21CC70B8BE4BA00D1EBDE /* Status.h in Headers */, 17D21CF30B8BE5EF00D1EBDE /* CogSemaphore.h in Headers */, + 835DD2682ACAF1D90057E319 /* OutputCoreAudio.h in Headers */, 839E56E62879450300DFB5F4 /* Endianness.h in Headers */, 17D21DC70B8BE79700D1EBDE /* CoreAudioUtils.h in Headers */, + 835DD2722ACAF5AD0057E319 /* lpc.h in Headers */, 839E56ED2879515D00DFB5F4 /* HeadphoneFilter.h in Headers */, 17D21EBD0B8BF44000D1EBDE /* AudioPlayer.h in Headers */, 831A50182865A8B30049CFE4 /* rsstate.h in Headers */, @@ -589,6 +622,8 @@ isa = PBXResourcesBuildPhase; buildActionMask = 2147483647; files = ( + 835DD2712ACAF5AD0057E319 /* License.txt in Resources */, + 835DD2702ACAF5AD0057E319 /* LICENSE.LGPL in Resources */, ); runOnlyForDeploymentPostprocessing = 0; }; @@ -608,7 +643,6 @@ 831A50162865A8800049CFE4 /* rsstate.cpp in Sources */, 17D21CA80B8BE4BA00D1EBDE /* Node.m in Sources */, 17D21CAA0B8BE4BA00D1EBDE /* OutputNode.m in Sources */, - 17D21CC60B8BE4BA00D1EBDE /* OutputAVFoundation.m in Sources */, 835C88B2279811A500E28EAE /* hdcd_decode2.c in Sources */, 835FAC5F27BCA14D00BA8562 /* BadSampleCleaner.m in Sources */, 834FD4ED27AF91220063BC83 /* AudioChunk.m in Sources */, @@ -630,8 +664,10 @@ 834FD4F127AF93680063BC83 /* ChunkList.m in Sources */, 834A41B0287ABD6F00EB9D9B /* FSurroundFilter.mm in Sources */, 8EC122600B993BD500C5B3AD /* ConverterNode.m in Sources */, + 835DD2672ACAF1D90057E319 /* OutputCoreAudio.m in Sources */, 8E8D3D300CBAEE6E00135C1B /* AudioContainer.m in Sources */, B0575F300D687A4000411D77 /* Helper.m in Sources */, + 835DD2742ACAF5AD0057E319 /* lpc.c in Sources */, 834A41AA287A90AB00EB9D9B /* freesurround_decoder.cpp in Sources */, 07DB5F3F0ED353A900C2E3EF /* AudioMetadataWriter.m in Sources */, ); diff --git a/Audio/Output/OutputCoreAudio.h b/Audio/Output/OutputCoreAudio.h index 35d64a8dd..c2333a47b 100644 --- a/Audio/Output/OutputCoreAudio.h +++ b/Audio/Output/OutputCoreAudio.h @@ -47,8 +47,6 @@ using std::atomic_long; NSLock *outputLock; - BOOL rsDone; - void *rsstate, *rsold; double secondsLatency; double visPushed; @@ -126,7 +124,7 @@ using std::atomic_long; AudioChunk *chunkRemain; - int resamplerRemain, visResamplerRemain; + int visResamplerRemain; BOOL resetStreamFormat; diff --git a/Audio/Output/OutputCoreAudio.m b/Audio/Output/OutputCoreAudio.m index 88f3f4955..75d22e2ac 100644 --- a/Audio/Output/OutputCoreAudio.m +++ b/Audio/Output/OutputCoreAudio.m @@ -72,27 +72,12 @@ static OSStatus eqRenderCallback(void *inRefCon, AudioUnitRenderActionFlags *ioA AudioStreamBasicDescription format; uint32_t config; if([outputController peekFormat:&format channelConfig:&config]) { - // XXX ERROR with AirPods - Can't go higher than CD*8 surround - 192k stereo - // Emits to console: [AUScotty] Initialize: invalid FFT size 16384 - // DSD256 stereo emits: [AUScotty] Initialize: invalid FFT size 65536 AudioStreamBasicDescription origFormat; uint32_t origConfig = config; memcpy(&origFormat, &format, sizeof(origFormat)); - BOOL formatClipped = NO; - const double targetSampleRate = deviceFormat.mSampleRate; - double srcRate = format.mSampleRate; - double dstRate = targetSampleRate; UInt32 srcChannels = format.mChannelsPerFrame; UInt32 dstChannels = deviceFormat.mChannelsPerFrame; - if(fabs(format.mSampleRate - targetSampleRate) > 1e-5) { - format.mSampleRate = targetSampleRate; - formatClipped = YES; - if(fabs(srcRate - lastClippedSampleRate) > 1e-5) { - lastClippedSampleRate = srcRate; - streamFormatStarted = NO; - } - } if(srcChannels != dstChannels) { format.mChannelsPerFrame = dstChannels; format.mBytesPerFrame = ((format.mBitsPerChannel + 7) / 8) * dstChannels; @@ -103,19 +88,6 @@ static OSStatus eqRenderCallback(void *inRefCon, AudioUnitRenderActionFlags *ioA downmixer = nil; } if(!streamFormatStarted || config != realStreamChannelConfig || memcmp(&newFormat, &format, sizeof(format)) != 0) { - [outputLock lock]; - if(formatClipped) { - ALog(@"Format clipped to %f Hz", targetSampleRate); - if(rsstate) { - rsold = rsstate; - rsstate = NULL; - } - rsstate = rsstate_new(srcChannels, srcRate, dstRate); - } else if(rsstate) { - rsold = rsstate; - rsstate = NULL; - } - [outputLock unlock]; newFormat = format; newChannelConfig = config; streamFormatStarted = YES; @@ -126,13 +98,6 @@ static OSStatus eqRenderCallback(void *inRefCon, AudioUnitRenderActionFlags *ioA visFormat.mBytesPerPacket = visFormat.mBytesPerFrame * visFormat.mFramesPerPacket; downmixerForVis = [[DownmixProcessor alloc] initWithInputFormat:origFormat inputConfig:origConfig andOutputFormat:visFormat outputConfig:AudioConfigMono]; - [outputLock lock]; - if(!rsold) { - realStreamFormat = format; - realStreamChannelConfig = config; - streamFormatChanged = YES; - } - [outputLock unlock]; } } @@ -164,35 +129,6 @@ static OSStatus eqRenderCallback(void *inRefCon, AudioUnitRenderActionFlags *ioA location:@"pre downmix"]; #endif const float *outputPtr = (const float *)[samples bytes]; - [outputLock lock]; - if(rsstate) { - if(frameCount + resamplerRemain > 8192) { - int leftoverFrameCount = frameCount + resamplerRemain - 8192; - int frameOffset = frameCount - leftoverFrameCount; - chunkRemain = chunk; - [chunk assignSamples:&outputPtr[frameOffset * format.mChannelsPerFrame] frameCount:leftoverFrameCount]; - frameCount = frameOffset; - } - cblas_scopy(frameCount * format.mChannelsPerFrame, outputPtr, 1, &rsInBuffer[resamplerRemain * format.mChannelsPerFrame], 1); - outputPtr = &rsInBuffer[0]; - frameCount += resamplerRemain; - resamplerRemain = 0; - size_t inDone = 0; - size_t framesDone = rsstate_resample(rsstate, outputPtr, frameCount, &inDone, &rsTempBuffer[0], amountToRead); - resamplerRemain = (int)(frameCount - inDone); - if(resamplerRemain && inDone) { - memmove(&rsInBuffer[0], &rsInBuffer[inDone * format.mChannelsPerFrame], resamplerRemain * format.mBytesPerPacket); - } - if(!framesDone) { - [outputLock unlock]; - return 0; - } - frameCount = (int)framesDone; - outputPtr = &rsTempBuffer[0]; - chunkDuration = frameCount / newFormat.mSampleRate; - } - [outputLock unlock]; - [downmixerForVis process:outputPtr frameCount:frameCount output:&visAudio[0]]; @@ -403,14 +339,6 @@ current_device_listener(AudioObjectID inObjectID, UInt32 inNumberAddresses, cons visPushed = 0.0; started = NO; restarted = NO; - if(rsstate) { - rsstate_delete(rsstate); - rsstate = NULL; - } - if(rsold) { - rsstate_delete(rsold); - rsold = NULL; - } if(rsvis) { rsstate_delete(rsvis); rsvis = NULL; @@ -665,6 +593,9 @@ current_device_listener(AudioObjectID inObjectID, UInt32 inNumberAddresses, cons _deviceFormat = format; deviceFormat = *(format.streamDescription); + // Force format for HRTF + deviceFormat.mSampleRate = 96000.0; + /// Seems some 3rd party devices return incorrect stuff...or I just don't like noninterleaved data. deviceFormat.mFormatFlags &= ~kLinearPCMFormatFlagIsNonInterleaved; // deviceFormat.mFormatFlags &= ~kLinearPCMFormatFlagIsFloat; @@ -892,127 +823,89 @@ current_device_listener(AudioObjectID inObjectID, UInt32 inNumberAddresses, cons int samplesRenderedTotal = 0; - for(size_t i = 0; i < 2;) { - int samplesRendered; + int samplesRendered = inputRendered; - if(i == 0) { - [outputLock lock]; - if(!rsold) { - [outputLock unlock]; - ++i; - continue; + samplePtr = &inputBuffer[0]; + + if(samplesRendered || fsurround) { + [outputLock lock]; + if(fsurround) { + int countToProcess = samplesRendered; + if(countToProcess < 4096) { + bzero(samplePtr + countToProcess * 2, (4096 - countToProcess) * 2 * sizeof(float)); + countToProcess = 4096; } - samplesRendered = rsstate_flush(rsold, &rsTempBuffer[0], 4096); - if(samplesRendered < 4096) { - rsstate_delete(rsold); - rsold = NULL; - [outputLock unlock]; - rsDone = YES; - ++i; - continue; + [fsurround process:samplePtr output:&fsurroundBuffer[0] count:countToProcess]; + samplePtr = &fsurroundBuffer[0]; + if(resetStreamFormat || samplesRendered < 4096) { + bzero(&fsurroundBuffer[4096 * 6], 4096 * 2 * sizeof(float)); + [fsurround process:&fsurroundBuffer[4096 * 6] output:&fsurroundBuffer[4096 * 6] count:4096]; + samplesRendered += 2048; } - [outputLock unlock]; - samplePtr = &rsTempBuffer[0]; - } else { - samplesRendered = inputRendered; - samplePtr = &inputBuffer[0]; - if(rsDone) { - rsDone = NO; - realStreamFormat = newFormat; - realStreamChannelConfig = newChannelConfig; - [self updateStreamFormat]; + if(!FSurroundDelayRemoved) { + FSurroundDelayRemoved = YES; + if(samplesRendered > 2048) { + samplePtr += 2048 * 6; + samplesRendered -= 2048; + } } } + [outputLock unlock]; - if(samplesRendered || fsurround) { - [outputLock lock]; - if(fsurround) { - int countToProcess = samplesRendered; - if(countToProcess < 4096) { - bzero(samplePtr + countToProcess * 2, (4096 - countToProcess) * 2 * sizeof(float)); - countToProcess = 4096; + if(!samplesRendered) { + return 0; + } + + [outputLock lock]; + if(hrtf) { + [hrtf process:samplePtr sampleCount:samplesRendered toBuffer:&hrtfBuffer[0]]; + samplePtr = &hrtfBuffer[0]; + } + [outputLock unlock]; + + if(eqEnabled && eqInitialized) { + const int channels = streamFormat.mChannelsPerFrame; + if(channels > 0) { + const size_t channelsminusone = channels - 1; + uint8_t tempBuffer[sizeof(AudioBufferList) + sizeof(AudioBuffer) * channelsminusone]; + AudioBufferList *ioData = (AudioBufferList *)&tempBuffer[0]; + + ioData->mNumberBuffers = channels; + for(size_t i = 0; i < channels; ++i) { + ioData->mBuffers[i].mData = &eqBuffer[4096 * i]; + ioData->mBuffers[i].mDataByteSize = samplesRendered * sizeof(float); + ioData->mBuffers[i].mNumberChannels = 1; } - [fsurround process:samplePtr output:&fsurroundBuffer[0] count:countToProcess]; - samplePtr = &fsurroundBuffer[0]; - if(resetStreamFormat || samplesRendered < 4096) { - bzero(&fsurroundBuffer[4096 * 6], 4096 * 2 * sizeof(float)); - [fsurround process:&fsurroundBuffer[4096 * 6] output:&fsurroundBuffer[4096 * 6] count:4096]; - samplesRendered += 2048; + + status = AudioUnitRender(_eq, NULL, &timeStamp, 0, samplesRendered, ioData); + + if(status != noErr) { + return 0; } - if(!FSurroundDelayRemoved) { - FSurroundDelayRemoved = YES; - if(samplesRendered > 2048) { - samplePtr += 2048 * 6; - samplesRendered -= 2048; - } - } - } - [outputLock unlock]; - - if(!samplesRendered) { - break; - } - - [outputLock lock]; - if(hrtf) { - [hrtf process:samplePtr sampleCount:samplesRendered toBuffer:&hrtfBuffer[0]]; - samplePtr = &hrtfBuffer[0]; - } - [outputLock unlock]; - - if(eqEnabled && eqInitialized) { - const int channels = streamFormat.mChannelsPerFrame; - if(channels > 0) { - const size_t channelsminusone = channels - 1; - uint8_t tempBuffer[sizeof(AudioBufferList) + sizeof(AudioBuffer) * channelsminusone]; - AudioBufferList *ioData = (AudioBufferList *)&tempBuffer[0]; - - ioData->mNumberBuffers = channels; - for(size_t i = 0; i < channels; ++i) { - ioData->mBuffers[i].mData = &eqBuffer[4096 * i]; - ioData->mBuffers[i].mDataByteSize = samplesRendered * sizeof(float); - ioData->mBuffers[i].mNumberChannels = 1; - } - - status = AudioUnitRender(_eq, NULL, &timeStamp, 0, samplesRendered, ioData); - - if(status != noErr) { - return 0; - } - - timeStamp.mSampleTime += ((double)samplesRendered) / streamFormat.mSampleRate; - - for(int i = 0; i < channels; ++i) { - cblas_scopy(samplesRendered, &eqBuffer[4096 * i], 1, samplePtr + i, channels); - } + + timeStamp.mSampleTime += ((double)samplesRendered) / streamFormat.mSampleRate; + + for(int i = 0; i < channels; ++i) { + cblas_scopy(samplesRendered, &eqBuffer[4096 * i], 1, samplePtr + i, channels); } } + } - if(downmixer) { - [downmixer process:samplePtr frameCount:samplesRendered output:&downmixBuffer[0]]; - samplePtr = &downmixBuffer[0]; - } + if(downmixer) { + [downmixer process:samplePtr frameCount:samplesRendered output:&downmixBuffer[0]]; + samplePtr = &downmixBuffer[0]; + } #ifdef OUTPUT_LOG - size_t dataByteSize = samplesRendered * sizeof(float) * deviceFormat.mChannelsPerFrame; + size_t dataByteSize = samplesRendered * sizeof(float) * deviceFormat.mChannelsPerFrame; - fwrite(samplePtr, 1, dataByteSize, _logFile); + fwrite(samplePtr, 1, dataByteSize, _logFile); #endif - } - - if(i == 0) { - samplesRenderedTotal += samplesRendered; - if(samplesRendered) { - break; - } - ++i; - } else { - inputBufferLastTime = 0; - samplesRenderedTotal += samplesRendered; - ++i; - } } + inputBufferLastTime = 0; + samplesRenderedTotal += samplesRendered; + return samplesRenderedTotal; } @@ -1093,10 +986,6 @@ current_device_listener(AudioObjectID inObjectID, UInt32 inNumberAddresses, cons downmixer = nil; downmixerForVis = nil; - rsDone = NO; - rsstate = NULL; - rsold = NULL; - lastClippedSampleRate = 0.0; rsvis = NULL; @@ -1106,7 +995,6 @@ current_device_listener(AudioObjectID inObjectID, UInt32 inNumberAddresses, cons chunkRemain = nil; - resamplerRemain = 0; visResamplerRemain = 0; secondsLatency = 0; @@ -1187,7 +1075,9 @@ current_device_listener(AudioObjectID inObjectID, UInt32 inNumberAddresses, cons [self audioOutputBlock]; [_au allocateRenderResourcesAndReturnError:&err]; - + + [self updateDeviceFormat]; + visController = [VisualizationController sharedController]; [[NSUserDefaultsController sharedUserDefaultsController] addObserver:self forKeyPath:@"values.outputDevice" options:0 context:kOutputCoreAudioContext]; @@ -1326,14 +1216,6 @@ current_device_listener(AudioObjectID inObjectID, UInt32 inNumberAddresses, cons #endif outputController = nil; visController = nil; - if(rsstate) { - rsstate_delete(rsstate); - rsstate = NULL; - } - if(rsold) { - rsstate_delete(rsold); - rsold = NULL; - } if(rsvis) { rsstate_delete(rsvis); rsvis = NULL; diff --git a/Audio/ThirdParty/lvqcl/License/LICENSE.LGPL b/Audio/ThirdParty/lvqcl/License/LICENSE.LGPL new file mode 100644 index 000000000..5faba9d48 --- /dev/null +++ b/Audio/ThirdParty/lvqcl/License/LICENSE.LGPL @@ -0,0 +1,504 @@ + GNU LESSER GENERAL PUBLIC LICENSE + Version 2.1, February 1999 + + Copyright (C) 1991, 1999 Free Software Foundation, Inc. + 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + +[This is the first released version of the Lesser GPL. It also counts + as the successor of the GNU Library Public License, version 2, hence + the version number 2.1.] + + Preamble + + The licenses for most software are designed to take away your +freedom to share and change it. By contrast, the GNU General Public +Licenses are intended to guarantee your freedom to share and change +free software--to make sure the software is free for all its users. + + This license, the Lesser General Public License, applies to some +specially designated software packages--typically libraries--of the +Free Software Foundation and other authors who decide to use it. You +can use it too, but we suggest you first think carefully about whether +this license or the ordinary General Public License is the better +strategy to use in any particular case, based on the explanations below. + + When we speak of free software, we are referring to freedom of use, +not price. Our General Public Licenses are designed to make sure that +you have the freedom to distribute copies of free software (and charge +for this service if you wish); that you receive source code or can get +it if you want it; that you can change the software and use pieces of +it in new free programs; and that you are informed that you can do +these things. + + To protect your rights, we need to make restrictions that forbid +distributors to deny you these rights or to ask you to surrender these +rights. These restrictions translate to certain responsibilities for +you if you distribute copies of the library or if you modify it. + + For example, if you distribute copies of the library, whether gratis +or for a fee, you must give the recipients all the rights that we gave +you. You must make sure that they, too, receive or can get the source +code. If you link other code with the library, you must provide +complete object files to the recipients, so that they can relink them +with the library after making changes to the library and recompiling +it. And you must show them these terms so they know their rights. + + We protect your rights with a two-step method: (1) we copyright the +library, and (2) we offer you this license, which gives you legal +permission to copy, distribute and/or modify the library. + + To protect each distributor, we want to make it very clear that +there is no warranty for the free library. Also, if the library is +modified by someone else and passed on, the recipients should know +that what they have is not the original version, so that the original +author's reputation will not be affected by problems that might be +introduced by others. + + Finally, software patents pose a constant threat to the existence of +any free program. We wish to make sure that a company cannot +effectively restrict the users of a free program by obtaining a +restrictive license from a patent holder. Therefore, we insist that +any patent license obtained for a version of the library must be +consistent with the full freedom of use specified in this license. + + Most GNU software, including some libraries, is covered by the +ordinary GNU General Public License. This license, the GNU Lesser +General Public License, applies to certain designated libraries, and +is quite different from the ordinary General Public License. We use +this license for certain libraries in order to permit linking those +libraries into non-free programs. + + When a program is linked with a library, whether statically or using +a shared library, the combination of the two is legally speaking a +combined work, a derivative of the original library. The ordinary +General Public License therefore permits such linking only if the +entire combination fits its criteria of freedom. The Lesser General +Public License permits more lax criteria for linking other code with +the library. + + We call this license the "Lesser" General Public License because it +does Less to protect the user's freedom than the ordinary General +Public License. It also provides other free software developers Less +of an advantage over competing non-free programs. These disadvantages +are the reason we use the ordinary General Public License for many +libraries. However, the Lesser license provides advantages in certain +special circumstances. + + For example, on rare occasions, there may be a special need to +encourage the widest possible use of a certain library, so that it becomes +a de-facto standard. To achieve this, non-free programs must be +allowed to use the library. A more frequent case is that a free +library does the same job as widely used non-free libraries. In this +case, there is little to gain by limiting the free library to free +software only, so we use the Lesser General Public License. + + In other cases, permission to use a particular library in non-free +programs enables a greater number of people to use a large body of +free software. For example, permission to use the GNU C Library in +non-free programs enables many more people to use the whole GNU +operating system, as well as its variant, the GNU/Linux operating +system. + + Although the Lesser General Public License is Less protective of the +users' freedom, it does ensure that the user of a program that is +linked with the Library has the freedom and the wherewithal to run +that program using a modified version of the Library. + + The precise terms and conditions for copying, distribution and +modification follow. Pay close attention to the difference between a +"work based on the library" and a "work that uses the library". The +former contains code derived from the library, whereas the latter must +be combined with the library in order to run. + + GNU LESSER GENERAL PUBLIC LICENSE + TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION + + 0. This License Agreement applies to any software library or other +program which contains a notice placed by the copyright holder or +other authorized party saying it may be distributed under the terms of +this Lesser General Public License (also called "this License"). +Each licensee is addressed as "you". + + A "library" means a collection of software functions and/or data +prepared so as to be conveniently linked with application programs +(which use some of those functions and data) to form executables. + + The "Library", below, refers to any such software library or work +which has been distributed under these terms. A "work based on the +Library" means either the Library or any derivative work under +copyright law: that is to say, a work containing the Library or a +portion of it, either verbatim or with modifications and/or translated +straightforwardly into another language. (Hereinafter, translation is +included without limitation in the term "modification".) + + "Source code" for a work means the preferred form of the work for +making modifications to it. For a library, complete source code means +all the source code for all modules it contains, plus any associated +interface definition files, plus the scripts used to control compilation +and installation of the library. + + Activities other than copying, distribution and modification are not +covered by this License; they are outside its scope. The act of +running a program using the Library is not restricted, and output from +such a program is covered only if its contents constitute a work based +on the Library (independent of the use of the Library in a tool for +writing it). Whether that is true depends on what the Library does +and what the program that uses the Library does. + + 1. You may copy and distribute verbatim copies of the Library's +complete source code as you receive it, in any medium, provided that +you conspicuously and appropriately publish on each copy an +appropriate copyright notice and disclaimer of warranty; keep intact +all the notices that refer to this License and to the absence of any +warranty; and distribute a copy of this License along with the +Library. + + You may charge a fee for the physical act of transferring a copy, +and you may at your option offer warranty protection in exchange for a +fee. + + 2. You may modify your copy or copies of the Library or any portion +of it, thus forming a work based on the Library, and copy and +distribute such modifications or work under the terms of Section 1 +above, provided that you also meet all of these conditions: + + a) The modified work must itself be a software library. + + b) You must cause the files modified to carry prominent notices + stating that you changed the files and the date of any change. + + c) You must cause the whole of the work to be licensed at no + charge to all third parties under the terms of this License. + + d) If a facility in the modified Library refers to a function or a + table of data to be supplied by an application program that uses + the facility, other than as an argument passed when the facility + is invoked, then you must make a good faith effort to ensure that, + in the event an application does not supply such function or + table, the facility still operates, and performs whatever part of + its purpose remains meaningful. + + (For example, a function in a library to compute square roots has + a purpose that is entirely well-defined independent of the + application. Therefore, Subsection 2d requires that any + application-supplied function or table used by this function must + be optional: if the application does not supply it, the square + root function must still compute square roots.) + +These requirements apply to the modified work as a whole. If +identifiable sections of that work are not derived from the Library, +and can be reasonably considered independent and separate works in +themselves, then this License, and its terms, do not apply to those +sections when you distribute them as separate works. But when you +distribute the same sections as part of a whole which is a work based +on the Library, the distribution of the whole must be on the terms of +this License, whose permissions for other licensees extend to the +entire whole, and thus to each and every part regardless of who wrote +it. + +Thus, it is not the intent of this section to claim rights or contest +your rights to work written entirely by you; rather, the intent is to +exercise the right to control the distribution of derivative or +collective works based on the Library. + +In addition, mere aggregation of another work not based on the Library +with the Library (or with a work based on the Library) on a volume of +a storage or distribution medium does not bring the other work under +the scope of this License. + + 3. You may opt to apply the terms of the ordinary GNU General Public +License instead of this License to a given copy of the Library. To do +this, you must alter all the notices that refer to this License, so +that they refer to the ordinary GNU General Public License, version 2, +instead of to this License. (If a newer version than version 2 of the +ordinary GNU General Public License has appeared, then you can specify +that version instead if you wish.) Do not make any other change in +these notices. + + Once this change is made in a given copy, it is irreversible for +that copy, so the ordinary GNU General Public License applies to all +subsequent copies and derivative works made from that copy. + + This option is useful when you wish to copy part of the code of +the Library into a program that is not a library. + + 4. You may copy and distribute the Library (or a portion or +derivative of it, under Section 2) in object code or executable form +under the terms of Sections 1 and 2 above provided that you accompany +it with the complete corresponding machine-readable source code, which +must be distributed under the terms of Sections 1 and 2 above on a +medium customarily used for software interchange. + + If distribution of object code is made by offering access to copy +from a designated place, then offering equivalent access to copy the +source code from the same place satisfies the requirement to +distribute the source code, even though third parties are not +compelled to copy the source along with the object code. + + 5. A program that contains no derivative of any portion of the +Library, but is designed to work with the Library by being compiled or +linked with it, is called a "work that uses the Library". Such a +work, in isolation, is not a derivative work of the Library, and +therefore falls outside the scope of this License. + + However, linking a "work that uses the Library" with the Library +creates an executable that is a derivative of the Library (because it +contains portions of the Library), rather than a "work that uses the +library". The executable is therefore covered by this License. +Section 6 states terms for distribution of such executables. + + When a "work that uses the Library" uses material from a header file +that is part of the Library, the object code for the work may be a +derivative work of the Library even though the source code is not. +Whether this is true is especially significant if the work can be +linked without the Library, or if the work is itself a library. The +threshold for this to be true is not precisely defined by law. + + If such an object file uses only numerical parameters, data +structure layouts and accessors, and small macros and small inline +functions (ten lines or less in length), then the use of the object +file is unrestricted, regardless of whether it is legally a derivative +work. (Executables containing this object code plus portions of the +Library will still fall under Section 6.) + + Otherwise, if the work is a derivative of the Library, you may +distribute the object code for the work under the terms of Section 6. +Any executables containing that work also fall under Section 6, +whether or not they are linked directly with the Library itself. + + 6. As an exception to the Sections above, you may also combine or +link a "work that uses the Library" with the Library to produce a +work containing portions of the Library, and distribute that work +under terms of your choice, provided that the terms permit +modification of the work for the customer's own use and reverse +engineering for debugging such modifications. + + You must give prominent notice with each copy of the work that the +Library is used in it and that the Library and its use are covered by +this License. You must supply a copy of this License. If the work +during execution displays copyright notices, you must include the +copyright notice for the Library among them, as well as a reference +directing the user to the copy of this License. Also, you must do one +of these things: + + a) Accompany the work with the complete corresponding + machine-readable source code for the Library including whatever + changes were used in the work (which must be distributed under + Sections 1 and 2 above); and, if the work is an executable linked + with the Library, with the complete machine-readable "work that + uses the Library", as object code and/or source code, so that the + user can modify the Library and then relink to produce a modified + executable containing the modified Library. (It is understood + that the user who changes the contents of definitions files in the + Library will not necessarily be able to recompile the application + to use the modified definitions.) + + b) Use a suitable shared library mechanism for linking with the + Library. A suitable mechanism is one that (1) uses at run time a + copy of the library already present on the user's computer system, + rather than copying library functions into the executable, and (2) + will operate properly with a modified version of the library, if + the user installs one, as long as the modified version is + interface-compatible with the version that the work was made with. + + c) Accompany the work with a written offer, valid for at + least three years, to give the same user the materials + specified in Subsection 6a, above, for a charge no more + than the cost of performing this distribution. + + d) If distribution of the work is made by offering access to copy + from a designated place, offer equivalent access to copy the above + specified materials from the same place. + + e) Verify that the user has already received a copy of these + materials or that you have already sent this user a copy. + + For an executable, the required form of the "work that uses the +Library" must include any data and utility programs needed for +reproducing the executable from it. However, as a special exception, +the materials to be distributed need not include anything that is +normally distributed (in either source or binary form) with the major +components (compiler, kernel, and so on) of the operating system on +which the executable runs, unless that component itself accompanies +the executable. + + It may happen that this requirement contradicts the license +restrictions of other proprietary libraries that do not normally +accompany the operating system. Such a contradiction means you cannot +use both them and the Library together in an executable that you +distribute. + + 7. You may place library facilities that are a work based on the +Library side-by-side in a single library together with other library +facilities not covered by this License, and distribute such a combined +library, provided that the separate distribution of the work based on +the Library and of the other library facilities is otherwise +permitted, and provided that you do these two things: + + a) Accompany the combined library with a copy of the same work + based on the Library, uncombined with any other library + facilities. This must be distributed under the terms of the + Sections above. + + b) Give prominent notice with the combined library of the fact + that part of it is a work based on the Library, and explaining + where to find the accompanying uncombined form of the same work. + + 8. You may not copy, modify, sublicense, link with, or distribute +the Library except as expressly provided under this License. Any +attempt otherwise to copy, modify, sublicense, link with, or +distribute the Library is void, and will automatically terminate your +rights under this License. However, parties who have received copies, +or rights, from you under this License will not have their licenses +terminated so long as such parties remain in full compliance. + + 9. You are not required to accept this License, since you have not +signed it. However, nothing else grants you permission to modify or +distribute the Library or its derivative works. These actions are +prohibited by law if you do not accept this License. Therefore, by +modifying or distributing the Library (or any work based on the +Library), you indicate your acceptance of this License to do so, and +all its terms and conditions for copying, distributing or modifying +the Library or works based on it. + + 10. Each time you redistribute the Library (or any work based on the +Library), the recipient automatically receives a license from the +original licensor to copy, distribute, link with or modify the Library +subject to these terms and conditions. You may not impose any further +restrictions on the recipients' exercise of the rights granted herein. +You are not responsible for enforcing compliance by third parties with +this License. + + 11. If, as a consequence of a court judgment or allegation of patent +infringement or for any other reason (not limited to patent issues), +conditions are imposed on you (whether by court order, agreement or +otherwise) that contradict the conditions of this License, they do not +excuse you from the conditions of this License. If you cannot +distribute so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you +may not distribute the Library at all. For example, if a patent +license would not permit royalty-free redistribution of the Library by +all those who receive copies directly or indirectly through you, then +the only way you could satisfy both it and this License would be to +refrain entirely from distribution of the Library. + +If any portion of this section is held invalid or unenforceable under any +particular circumstance, the balance of the section is intended to apply, +and the section as a whole is intended to apply in other circumstances. + +It is not the purpose of this section to induce you to infringe any +patents or other property right claims or to contest validity of any +such claims; this section has the sole purpose of protecting the +integrity of the free software distribution system which is +implemented by public license practices. Many people have made +generous contributions to the wide range of software distributed +through that system in reliance on consistent application of that +system; it is up to the author/donor to decide if he or she is willing +to distribute software through any other system and a licensee cannot +impose that choice. + +This section is intended to make thoroughly clear what is believed to +be a consequence of the rest of this License. + + 12. If the distribution and/or use of the Library is restricted in +certain countries either by patents or by copyrighted interfaces, the +original copyright holder who places the Library under this License may add +an explicit geographical distribution limitation excluding those countries, +so that distribution is permitted only in or among countries not thus +excluded. In such case, this License incorporates the limitation as if +written in the body of this License. + + 13. The Free Software Foundation may publish revised and/or new +versions of the Lesser General Public License from time to time. +Such new versions will be similar in spirit to the present version, +but may differ in detail to address new problems or concerns. + +Each version is given a distinguishing version number. If the Library +specifies a version number of this License which applies to it and +"any later version", you have the option of following the terms and +conditions either of that version or of any later version published by +the Free Software Foundation. If the Library does not specify a +license version number, you may choose any version ever published by +the Free Software Foundation. + + 14. If you wish to incorporate parts of the Library into other free +programs whose distribution conditions are incompatible with these, +write to the author to ask for permission. For software which is +copyrighted by the Free Software Foundation, write to the Free +Software Foundation; we sometimes make exceptions for this. Our +decision will be guided by the two goals of preserving the free status +of all derivatives of our free software and of promoting the sharing +and reuse of software generally. + + NO WARRANTY + + 15. BECAUSE THE LIBRARY IS LICENSED FREE OF CHARGE, THERE IS NO +WARRANTY FOR THE LIBRARY, TO THE EXTENT PERMITTED BY APPLICABLE LAW. +EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR +OTHER PARTIES PROVIDE THE LIBRARY "AS IS" WITHOUT WARRANTY OF ANY +KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE +IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE +LIBRARY IS WITH YOU. SHOULD THE LIBRARY PROVE DEFECTIVE, YOU ASSUME +THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. + + 16. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN +WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY +AND/OR REDISTRIBUTE THE LIBRARY AS PERMITTED ABOVE, BE LIABLE TO YOU +FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR +CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE +LIBRARY (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING +RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A +FAILURE OF THE LIBRARY TO OPERATE WITH ANY OTHER SOFTWARE), EVEN IF +SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH +DAMAGES. + + END OF TERMS AND CONDITIONS + + How to Apply These Terms to Your New Libraries + + If you develop a new library, and you want it to be of the greatest +possible use to the public, we recommend making it free software that +everyone can redistribute and change. You can do so by permitting +redistribution under these terms (or, alternatively, under the terms of the +ordinary General Public License). + + To apply these terms, attach the following notices to the library. It is +safest to attach them to the start of each source file to most effectively +convey the exclusion of warranty; and each file should have at least the +"copyright" line and a pointer to where the full notice is found. + + + Copyright (C) + + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2.1 of the License, or (at your option) any later version. + + This library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + +Also add information on how to contact you by electronic and paper mail. + +You should also get your employer (if you work as a programmer) or your +school, if any, to sign a "copyright disclaimer" for the library, if +necessary. Here is a sample; alter the names: + + Yoyodyne, Inc., hereby disclaims all copyright interest in the + library `Frob' (a library for tweaking knobs) written by James Random Hacker. + + , 1 April 1990 + Ty Coon, President of Vice + +That's all there is to it! + + diff --git a/Audio/ThirdParty/lvqcl/License/License.txt b/Audio/ThirdParty/lvqcl/License/License.txt new file mode 100644 index 000000000..d7eebdcc6 --- /dev/null +++ b/Audio/ThirdParty/lvqcl/License/License.txt @@ -0,0 +1,39 @@ +SoX resampler plugin for foobar2000 audio player +Copyright (C) lvqcl + +This library is free software; you can redistribute it and/or +modify it under the terms of the GNU Lesser General Public +License as published by the Free Software Foundation; either +version 2.1 of the License, or (at your option) any later version. + +This library is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +Lesser General Public License for more details. + +You should have received a copy of the GNU Lesser General Public +License along with this library; if not, write to the Free Software +Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + + +This software uses code of SoX licensed under the terms of LGPLv2.1 +Copyright (C) robs@users.sourceforge.net +Copyright (C) Chris Bagwell and SoX contributors +Copyright (C) Reuben Thomas + + +This software uses code of FFmpeg licensed under the terms of LGPLv2.1 +Copyright (C) Fabrice Bellard +Copyright (C) Michael Niedermayer +Copyright (C) Alex Converse +Copyright (C) Loren Merritt +Copyright (C) Vitor Sessak +Copyright (C) x264 project + + +This software uses code of General Purpose FFT Package +Copyright (C) Takuya OOURA + + +This software uses code of foobar2000 1.4 SDK +Copyright (C) 2001-2018, Peter Pawlowski diff --git a/Audio/ThirdParty/lvqcl/lpc.c b/Audio/ThirdParty/lvqcl/lpc.c new file mode 100644 index 000000000..29f634578 --- /dev/null +++ b/Audio/ThirdParty/lvqcl/lpc.c @@ -0,0 +1,193 @@ +/* + * Copyright (c) 2013, 2018 lvqcl + * + * Permission to use, copy, modify, and distribute this software for any + * purpose with or without fee is hereby granted, provided that the above + * copyright notice and this permission notice appear in all copies. + * + * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES + * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF + * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR + * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES + * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN + * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF + * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. + */ + +#include +#include +#include +#include "lpc.h" + +static void apply_window(float *const data, const size_t data_len) { +#if 0 + if (0) // subtract the mean + { + double mean = 0; + for(int i = 0; i < (int)data_len; i++) + mean += data[i]; + mean /= data_len; + + for(int i = 0; i < (int)data_len; i++) + data[i] -= (float)mean; + } +#endif + + if(1) // Welch window + { + const float n2 = (data_len + 1) / 2.0f; + for(int i = 0; i < (int)data_len; i++) { + float k = (i + 1 - n2) / n2; + data[data_len - 1 - i] *= 1.0f - k * k; + } + } +} + +static float vorbis_lpc_from_data(float *data, float *lpci, int n, int m, double *aut, double *lpc) { + double error; + double epsilon; + int i, j; + + /* autocorrelation, p+1 lag coefficients */ + j = m + 1; + while(j--) { + double d = 0; /* double needed for accumulator depth */ + for(i = j; i < n; i++) d += (double)data[i] * data[i - j]; + aut[j] = d; + } + + /* Generate lpc coefficients from autocorr values */ + + /* set our noise floor to about -100dB */ + error = aut[0] * (1. + 1e-10); + epsilon = 1e-9 * aut[0] + 1e-10; + + for(i = 0; i < m; i++) { + double r = -aut[i + 1]; + + if(error < epsilon) { + memset(lpc + i, 0, (m - i) * sizeof(*lpc)); + goto done; + } + + /* Sum up this iteration's reflection coefficient; note that in + Vorbis we don't save it. If anyone wants to recycle this code + and needs reflection coefficients, save the results of 'r' from + each iteration. */ + + for(j = 0; j < i; j++) r -= lpc[j] * aut[i - j]; + r /= error; + + /* Update LPC coefficients and total error */ + + lpc[i] = r; + for(j = 0; j < i / 2; j++) { + double tmp = lpc[j]; + + lpc[j] += r * lpc[i - 1 - j]; + lpc[i - 1 - j] += r * tmp; + } + if(i & 1) lpc[j] += lpc[j] * r; + + error *= 1. - r * r; + } + +done: + + /* slightly damp the filter */ + { + double g = .99; + double damp = g; + for(j = 0; j < m; j++) { + lpc[j] *= damp; + damp *= g; + } + } + + for(j = 0; j < m; j++) lpci[j] = (float)lpc[j]; + + /* we need the error value to know how big an impulse to hit the + filter with later */ + + return error; +} + +static void vorbis_lpc_predict(float *coeff, float *prime, int m, float *data, long n, float *work) { + /* in: coeff[0...m-1] LPC coefficients + prime[0...m-1] initial values (allocated size of n+m-1) + out: data[0...n-1] data samples */ + + long i, j, o, p; + float y; + + if(!prime) + for(i = 0; i < m; i++) + work[i] = 0.f; + else + for(i = 0; i < m; i++) + work[i] = prime[i]; + + for(i = 0; i < n; i++) { + y = 0; + o = i; + p = m; + for(j = 0; j < m; j++) + y -= work[o++] * coeff[--p]; + + data[i] = work[o] = y; + } +} + +void lpc_extrapolate2(float *const data, const size_t data_len, const int nch, const int lpc_order, const size_t extra_bkwd, const size_t extra_fwd, void **extrapolate_buffer, size_t *extrapolate_buffer_size) { + const size_t tdata_size = sizeof(float) * (extra_bkwd + data_len + extra_fwd); + const size_t aut_size = sizeof(double) * (lpc_order + 1); + const size_t lpc_size = sizeof(double) * lpc_order; + const size_t lpci_size = sizeof(float) * lpc_order; + const size_t work_size = sizeof(float) * (extra_bkwd + lpc_order + extra_fwd); + + const size_t new_size = tdata_size + aut_size + lpc_size + lpci_size + work_size; + + if(new_size > *extrapolate_buffer_size) { + *extrapolate_buffer = realloc(*extrapolate_buffer, new_size); + *extrapolate_buffer_size = new_size; + } + + float *tdata = (float *)(*extrapolate_buffer); // for 1 channel only + + double *aut = (double *)(*extrapolate_buffer + tdata_size); + double *lpc = (double *)(*extrapolate_buffer + tdata_size + aut_size); + float *lpci = (float *)(*extrapolate_buffer + tdata_size + aut_size + lpc_size); + float *work = (float *)(*extrapolate_buffer + tdata_size + aut_size + lpc_size + lpci_size); + + for(int c = 0; c < nch; c++) { + if(extra_bkwd) { + for(int i = 0; i < (int)data_len; i++) + tdata[data_len - 1 - i] = data[i * nch + c]; + } else { + for(int i = 0; i < (int)data_len; i++) + tdata[i] = data[i * nch + c]; + } + + apply_window(tdata, data_len); + vorbis_lpc_from_data(tdata, lpci, (int)data_len, lpc_order, aut, lpc); + + // restore after apply_window + if(extra_bkwd) { + for(int i = 0; i < (int)data_len; i++) + tdata[data_len - 1 - i] = data[i * nch + c]; + } else { + for(int i = 0; i < (int)data_len; i++) + tdata[i] = data[i * nch + c]; + } + + vorbis_lpc_predict(lpci, tdata + data_len - lpc_order, lpc_order, tdata + data_len, extra_fwd + extra_bkwd, work); + + if(extra_bkwd) { + for(int i = 0; i < extra_bkwd; i++) + data[(-i - 1) * nch + c] = tdata[data_len + i]; + } else { + for(int i = 0; i < extra_fwd; i++) + data[(i + data_len) * nch + c] = tdata[data_len + i]; + } + } +} diff --git a/Audio/ThirdParty/lvqcl/lpc.h b/Audio/ThirdParty/lvqcl/lpc.h new file mode 100644 index 000000000..9a0bd90f3 --- /dev/null +++ b/Audio/ThirdParty/lvqcl/lpc.h @@ -0,0 +1,40 @@ +#ifndef MY_LPC_H +#define MY_LPC_H + +/* data - beginning of the data + * data_len - length of data (in samples) that are base for extrapolation + * nch - number of (interleaved) channels + * lpc_order - LPC order + * extra_bkwd - number of samples to pre-extrapolate + * extra_fwd - number of samples to post-extrapolate + * + * D = data; N = num_channels; LEN = data_len*N; EX = extra*N + * + * memory layout when invdir == false: + * + * [||||||||||||||||||||||||||||||||][||||||||||||||||||||][ + * ^ D[0] ^ D[LEN] ^ D[LEN+EX] + * + * memory layout when invdir == true: + * ][||||||||||||||||||||][||||||||||||||||||||||||||||||||][ + * ^ D[0] ^ D[LEN] + * ^ D[-1*N-EX] ^ D[-1*N] + * + */ + +static const size_t LPC_ORDER = 32; + +void lpc_extrapolate2(float * const data, const size_t data_len, const int nch, const int lpc_order, const size_t extra_bkwd, const size_t extra_fwd, void ** extrapolate_buffer, size_t * extrapolate_buffer_size); + +static inline void lpc_extrapolate_bkwd(float * const data, const size_t data_len, const size_t prime_len, const int nch, const int lpc_order, const size_t extra_bkwd, void ** extrapolate_buffer, size_t * extrapolate_buffer_size) +{ + (void)data_len; + lpc_extrapolate2(data, prime_len, nch, lpc_order, extra_bkwd, 0, extrapolate_buffer, extrapolate_buffer_size); +} + +static inline void lpc_extrapolate_fwd(float * const data, const size_t data_len, const size_t prime_len, const int nch, const int lpc_order, const size_t extra_fwd, void ** extrapolate_buffer, size_t * extrapolate_buffer_size) +{ + lpc_extrapolate2(data + (data_len - prime_len)*nch, prime_len, nch, lpc_order, 0, extra_fwd, extrapolate_buffer, extrapolate_buffer_size); +} + +#endif diff --git a/Audio/ThirdParty/lvqcl/util.h b/Audio/ThirdParty/lvqcl/util.h new file mode 100644 index 000000000..ec26088db --- /dev/null +++ b/Audio/ThirdParty/lvqcl/util.h @@ -0,0 +1,55 @@ +/* Copyright (c) 2018 lvqcl. All rights reserved. + * + * This library is free software; you can redistribute it and/or modify it + * under the terms of the GNU Lesser General Public License as published by + * the Free Software Foundation; either version 2.1 of the License, or (at + * your option) any later version. + * + * This library is distributed in the hope that it will be useful, but + * WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser + * General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public License + * along with this library; if not, write to the Free Software Foundation, + * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + */ + +#ifndef UTIL_H_ +#define UTIL_H_ + +#ifndef min +#define min(a,b) (((a)<(b))?(a):(b)) +#endif +#ifndef max +#define max(a,b) (((a)>(b))?(a):(b)) +#endif + +static inline unsigned local_gcd(unsigned a, unsigned b) +{ + if (a == 0 || b == 0) return 0; + unsigned c = a % b; + while (c != 0) { a = b; b = c; c = a % b; } + return b; +} + +/* + In: *r1 and *r2: samplerates; + Out: *r1 and *r2: numbers of samples; + + multiply r1 and r2 by n so that durations is 1/N th of second; + limit n so that r1 and r2 aren't bigger than M +*/ +static void samples_len(unsigned* r1, unsigned* r2, unsigned N, unsigned M) // example: r1 = 44100, r2 = 48000, N = 20, M = 8192 +{ + if (r1 == 0 || r2 == 0) return; + unsigned v = local_gcd(*r1, *r2); // v = 300 + *r1 /= v; *r2 /= v; // r1 = 147; r2 = 160 == 1/300th of second + unsigned n = (v + N-1) / N; // n = 300/20 = 15 times + unsigned z = max(*r1, *r2); // z = 160 + if (z*n > M) n = M / z; // 160*15 = 2400 < 8192;; if M == 1024: n = 1024/160 = 6; 160*6 = 960 + if (n < 1) n = 1; + *r1 *= n; *r2 *= n; // r1 = 147*15 = 2205 samples, r2 = 160*15 = 2400 samples +} + +#endif