diff --git a/.gitignore b/.gitignore index ff52565fc..a372da51a 100644 --- a/.gitignore +++ b/.gitignore @@ -47,6 +47,7 @@ Xcode-config/DEVELOPMENT_TEAM.xcconfig /ThirdParty/ogg/lib/libogg.0.dylib /ThirdParty/opus/lib/libopus.0.dylib /ThirdParty/opusfile/lib/libopusfile.0.dylib +/ThirdParty/rubberband/lib/librubberband.3.dylib /ThirdParty/speex/libspeex.a /ThirdParty/vorbis/lib/libvorbisfile.3.dylib /ThirdParty/vorbis/lib/libvorbis.0.dylib diff --git a/Application/PlaybackController.h b/Application/PlaybackController.h index ed1f4fcf5..6aeea5669 100644 --- a/Application/PlaybackController.h +++ b/Application/PlaybackController.h @@ -19,8 +19,11 @@ #define DEFAULT_VOLUME_DOWN 5 #define DEFAULT_VOLUME_UP DEFAULT_VOLUME_DOWN -#define DEFAULT_SPEED_DOWN 0.2 -#define DEFAULT_SPEED_UP DEFAULT_SPEED_DOWN +#define DEFAULT_PITCH_DOWN 0.2 +#define DEFAULT_PITCH_UP DEFAULT_PITCH_DOWN + +#define DEFAULT_TEMPO_DOWN 0.2 +#define DEFAULT_TEMPO_UP DEFAULT_TEMPO_DOWN extern NSString *CogPlaybackDidBeginNotificiation; extern NSString *CogPlaybackDidPauseNotificiation; @@ -43,7 +46,9 @@ extern NSDictionary *makeRGInfo(PlaylistEntry *pe); IBOutlet EqualizerWindowController *equalizerWindowController; IBOutlet NSSlider *volumeSlider; - IBOutlet NSSlider *speedSlider; + IBOutlet NSSlider *pitchSlider; + IBOutlet NSSlider *tempoSlider; + IBOutlet NSButton *lockButton; IBOutlet NSArrayController *outputDevices; @@ -73,9 +78,13 @@ extern NSDictionary *makeRGInfo(PlaylistEntry *pe); - (IBAction)volumeDown:(id)sender; - (IBAction)volumeUp:(id)sender; -- (IBAction)changeSpeed:(id)sender; -- (IBAction)speedDown:(id)sender; -- (IBAction)speedUp:(id)sender; +- (IBAction)changePitch:(id)sender; +- (IBAction)pitchDown:(id)sender; +- (IBAction)pitchUp:(id)sender; + +- (IBAction)changeTempo:(id)sender; +- (IBAction)tempoDown:(id)sender; +- (IBAction)tempoUp:(id)sender; - (IBAction)playPauseResume:(id)sender; - (IBAction)pauseResume:(id)sender; diff --git a/Application/PlaybackController.m b/Application/PlaybackController.m index 27fda07a9..3254b0ed0 100644 --- a/Application/PlaybackController.m +++ b/Application/PlaybackController.m @@ -91,7 +91,9 @@ NSString *CogPlaybackDidStopNotificiation = @"CogPlaybackDidStopNotificiation"; - (void)initDefaults { NSDictionary *defaultsDictionary = @{ @"volume": @(75.0), - @"speed": @(1.0), + @"pitch": @(1.0), + @"tempo": @(1.0), + @"speedLock": @(YES), @"GraphicEQenable": @(NO), @"GraphicEQpreset": @(-1), @"GraphicEQtrackgenre": @(NO), @@ -101,6 +103,16 @@ NSString *CogPlaybackDidStopNotificiation = @"CogPlaybackDidStopNotificiation"; [[NSUserDefaults standardUserDefaults] registerDefaults:defaultsDictionary]; } +static double speedScale(double input, double min, double max) { + input = (input - min) * 100.0 / (max - min); + return ((input * input) * (5.0 - 0.2) / 10000.0) + 0.2; +} + +static double reverseSpeedScale(double input, double min, double max) { + input = sqrtf((input - 0.2) * 10000.0 / (5.0 - 0.2)); + return (input * (max - min) / 100.0) + min; +} + - (void)awakeFromNib { BOOL volumeLimit = [[[NSUserDefaultsController sharedUserDefaultsController] defaults] boolForKey:@"volumeLimit"]; const double MAX_VOLUME = (volumeLimit) ? 100.0 : 800.0; @@ -110,8 +122,15 @@ NSString *CogPlaybackDidStopNotificiation = @"CogPlaybackDidStopNotificiation"; [volumeSlider setDoubleValue:logarithmicToLinear(volume, MAX_VOLUME)]; [audioPlayer setVolume:volume]; - double speed = [[NSUserDefaults standardUserDefaults] doubleForKey:@"speed"]; - [audioPlayer setSpeed:speed]; + double pitch = [[NSUserDefaults standardUserDefaults] doubleForKey:@"pitch"]; + [audioPlayer setPitch:pitch]; + [pitchSlider setDoubleValue:reverseSpeedScale(pitch, [pitchSlider minValue], [pitchSlider maxValue])]; + double tempo = [[NSUserDefaults standardUserDefaults] doubleForKey:@"tempo"]; + [audioPlayer setTempo:tempo]; + [tempoSlider setDoubleValue:reverseSpeedScale(tempo, [tempoSlider minValue], [tempoSlider maxValue])]; + + BOOL speedLock = [[NSUserDefaults standardUserDefaults] boolForKey:@"speedLock"]; + [lockButton setTitle:speedLock ? @"🔒" : @"🔓"]; [self setSeekable:NO]; } @@ -253,7 +272,7 @@ NSDictionary *makeRGInfo(PlaylistEntry *pe) { #if 0 // Race here, but the worst that could happen is we re-read the data - if ([pe metadataLoaded] != YES) { + if([pe metadataLoaded] != YES) { [pe performSelectorOnMainThread:@selector(setMetadata:) withObject:[playlistLoader readEntryInfo:pe] waitUntilDone:YES]; } #elif 0 @@ -381,7 +400,7 @@ NSDictionary *makeRGInfo(PlaylistEntry *pe) { NSImage *img = [NSImage imageNamed:name]; // [img retain]; - if (img == nil) + if(img == nil) { DLog(@"Error loading image!"); } @@ -482,12 +501,34 @@ NSDictionary *makeRGInfo(PlaylistEntry *pe) { } } -- (IBAction)changeSpeed:(id)sender { - DLog(@"SPEED: %lf", [sender doubleValue]); +- (IBAction)changePitch:(id)sender { + const double pitch = speedScale([sender doubleValue], [pitchSlider minValue], [pitchSlider maxValue]); + DLog(@"PITCH: %lf", pitch); - [audioPlayer setSpeed:[sender doubleValue]]; + [audioPlayer setPitch:pitch]; - [[NSUserDefaults standardUserDefaults] setDouble:[audioPlayer speed] forKey:@"speed"]; + [[NSUserDefaults standardUserDefaults] setDouble:[audioPlayer pitch] forKey:@"pitch"]; + + if([[NSUserDefaults standardUserDefaults] boolForKey:@"speedLock"]) { + [audioPlayer setTempo:pitch]; + + [[NSUserDefaults standardUserDefaults] setDouble:[audioPlayer tempo] forKey:@"tempo"]; + } +} + +- (IBAction)changeTempo:(id)sender { + const double tempo = speedScale([sender doubleValue], [tempoSlider minValue], [tempoSlider maxValue]); + DLog(@"TEMPO: %lf", tempo); + + [audioPlayer setTempo:tempo]; + + [[NSUserDefaults standardUserDefaults] setDouble:[audioPlayer tempo] forKey:@"tempo"]; + + if([[NSUserDefaults standardUserDefaults] boolForKey:@"speedLock"]) { + [audioPlayer setPitch:tempo]; + + [[NSUserDefaults standardUserDefaults] setDouble:[audioPlayer pitch] forKey:@"pitch"]; + } } - (IBAction)skipToNextAlbum:(id)sender { @@ -591,18 +632,64 @@ NSDictionary *makeRGInfo(PlaylistEntry *pe) { [[NSUserDefaults standardUserDefaults] setDouble:[audioPlayer volume] forKey:@"volume"]; } -- (IBAction)speedDown:(id)sender { - double newSpeed = [audioPlayer speedDown:DEFAULT_SPEED_DOWN]; - [speedSlider setDoubleValue:[audioPlayer speed]]; +- (IBAction)pitchDown:(id)sender { + /*double newPitch = */[audioPlayer pitchDown:DEFAULT_PITCH_DOWN]; + [pitchSlider setDoubleValue:reverseSpeedScale([audioPlayer pitch], [pitchSlider minValue], [pitchSlider maxValue])]; - [[NSUserDefaults standardUserDefaults] setDouble:[audioPlayer speed] forKey:@"speed"]; + [[NSUserDefaults standardUserDefaults] setDouble:[audioPlayer pitch] forKey:@"pitch"]; + + if([[NSUserDefaults standardUserDefaults] boolForKey:@"speedLock"]) { + [audioPlayer setTempo:[audioPlayer pitch]]; + + [tempoSlider setDoubleValue:reverseSpeedScale([audioPlayer tempo], [tempoSlider minValue], [tempoSlider maxValue])]; + + [[NSUserDefaults standardUserDefaults] setDouble:[audioPlayer tempo] forKey:@"tempo"]; + } } -- (IBAction)speedUp:(id)sender { - double newSpeed = [audioPlayer speedUp:DEFAULT_SPEED_UP]; - [speedSlider setDoubleValue:[audioPlayer speed]]; +- (IBAction)pitchUp:(id)sender { + /*double newPitch = */[audioPlayer tempoUp:DEFAULT_PITCH_UP]; + [pitchSlider setDoubleValue:reverseSpeedScale([audioPlayer pitch], [pitchSlider minValue], [pitchSlider maxValue])]; - [[NSUserDefaults standardUserDefaults] setDouble:[audioPlayer speed] forKey:@"speed"]; + [[NSUserDefaults standardUserDefaults] setDouble:[audioPlayer pitch] forKey:@"pitch"]; + + if([[NSUserDefaults standardUserDefaults] boolForKey:@"speedLock"]) { + [audioPlayer setTempo:[audioPlayer pitch]]; + + [tempoSlider setDoubleValue:reverseSpeedScale([audioPlayer tempo], [tempoSlider minValue], [tempoSlider maxValue])]; + + [[NSUserDefaults standardUserDefaults] setDouble:[audioPlayer tempo] forKey:@"tempo"]; + } +} + +- (IBAction)tempoDown:(id)sender { + /*double newTempo = */[audioPlayer tempoDown:DEFAULT_TEMPO_DOWN]; + [tempoSlider setDoubleValue:reverseSpeedScale([audioPlayer tempo], [tempoSlider minValue], [tempoSlider maxValue])]; + + [[NSUserDefaults standardUserDefaults] setDouble:[audioPlayer tempo] forKey:@"tempo"]; + + if([[NSUserDefaults standardUserDefaults] boolForKey:@"speedLock"]) { + [audioPlayer setPitch:[audioPlayer tempo]]; + + [pitchSlider setDoubleValue:reverseSpeedScale([audioPlayer pitch], [pitchSlider minValue], [pitchSlider maxValue])]; + + [[NSUserDefaults standardUserDefaults] setDouble:[audioPlayer pitch] forKey:@"pitch"]; + } +} + +- (IBAction)tempoUp:(id)sender { + /*double newTempo = */[audioPlayer tempoUp:DEFAULT_PITCH_UP]; + [tempoSlider setDoubleValue:reverseSpeedScale([audioPlayer tempo], [tempoSlider minValue], [tempoSlider maxValue])]; + + [[NSUserDefaults standardUserDefaults] setDouble:[audioPlayer tempo] forKey:@"tempo"]; + + if([[NSUserDefaults standardUserDefaults] boolForKey:@"speedLock"]) { + [audioPlayer setPitch:[audioPlayer tempo]]; + + [pitchSlider setDoubleValue:reverseSpeedScale([audioPlayer pitch], [pitchSlider minValue], [pitchSlider maxValue])]; + + [[NSUserDefaults standardUserDefaults] setDouble:[audioPlayer pitch] forKey:@"pitch"]; + } } - (void)audioPlayer:(AudioPlayer *)player displayEqualizer:(AudioUnit)eq { @@ -764,7 +851,7 @@ NSDictionary *makeRGInfo(PlaylistEntry *pe) { - (void)audioPlayer:(AudioPlayer *)player pushInfo:(NSDictionary *)info toTrack:(id)userInfo { PlaylistEntry *pe = (PlaylistEntry *)userInfo; - if (!pe) pe = [playlistController currentEntry]; + if(!pe) pe = [playlistController currentEntry]; [pe setMetadata:info]; [playlistView refreshTrack:pe]; // Delay the action until this function has returned to the audio thread diff --git a/Audio/AudioPlayer.h b/Audio/AudioPlayer.h index 01acaeee4..a6ea2d6bc 100644 --- a/Audio/AudioPlayer.h +++ b/Audio/AudioPlayer.h @@ -26,7 +26,8 @@ OutputNode *output; double volume; - double speed; + double pitch; + double tempo; NSMutableArray *chainQueue; @@ -75,10 +76,15 @@ - (double)volumeUp:(double)amount; - (double)volumeDown:(double)amount; -- (void)setSpeed:(double)s; -- (double)speed; -- (double)speedUp:(double)amount; -- (double)speedDown:(double)amount; +- (void)setPitch:(double)s; +- (double)pitch; +- (double)pitchUp:(double)amount; +- (double)pitchDown:(double)amount; + +- (void)setTempo:(double)s; +- (double)tempo; +- (double)tempoUp:(double)amount; +- (double)tempoDown:(double)amount; - (double)amountPlayed; - (double)amountPlayedInterval; diff --git a/Audio/AudioPlayer.m b/Audio/AudioPlayer.m index 70a858597..aaeb9cf11 100644 --- a/Audio/AudioPlayer.m +++ b/Audio/AudioPlayer.m @@ -24,6 +24,10 @@ bufferChain = nil; outputLaunched = NO; endOfInputReached = NO; + + // Safety + pitch = 1.0; + tempo = 1.0; chainQueue = [[NSMutableArray alloc] init]; @@ -75,7 +79,8 @@ } [output setup]; [output setVolume:volume]; - [output setSpeed:speed]; + [output setPitch:pitch]; + [output setTempo:tempo]; @synchronized(chainQueue) { for(id anObject in chainQueue) { [anObject setShouldContinue:NO]; @@ -211,14 +216,24 @@ return volume; } -- (void)setSpeed:(double)s { - speed = s; +- (void)setPitch:(double)p { + pitch = p; - [output setSpeed:s]; + [output setPitch:p]; } -- (double)speed { - return speed; +- (double)pitch { + return pitch; +} + +- (void)setTempo:(double)t { + tempo = t; + + [output setTempo:t]; +} + +- (double)tempo { + return tempo; } // This is called by the delegate DURING a requestNextStream request. @@ -659,30 +674,56 @@ return newVolume; } -- (double)speedUp:(double)amount { - const double MAX_SPEED = 5.0; +- (double)pitchUp:(double)amount { + const double MAX_PITCH = 5.0; - double newSpeed; - if((speed + amount) > MAX_SPEED) - newSpeed = MAX_SPEED; + double newPitch; + if((pitch + amount) > MAX_PITCH) + newPitch = MAX_PITCH; else - newSpeed = speed + amount; + newPitch = pitch + amount; - [self setSpeed:newSpeed]; - return newSpeed; + [self setPitch:newPitch]; + return newPitch; } -- (double)speedDown:(double)amount { - const double MIN_SPEED = 0.2; +- (double)pitchDown:(double)amount { + const double MIN_PITCH = 0.2; - double newSpeed; - if((speed - amount) < MIN_SPEED) - newSpeed = MIN_SPEED; + double newPitch; + if((pitch - amount) < MIN_PITCH) + newPitch = MIN_PITCH; else - newSpeed = speed - amount; + newPitch = pitch - amount; - [self setSpeed:newSpeed]; - return newSpeed; + [self setPitch:newPitch]; + return newPitch; +} + +- (double)tempoUp:(double)amount { + const double MAX_TEMPO = 5.0; + + double newTempo; + if((tempo + amount) > MAX_TEMPO) + newTempo = MAX_TEMPO; + else + newTempo = tempo + amount; + + [self setTempo:newTempo]; + return newTempo; +} + +- (double)tempoDown:(double)amount { + const double MIN_TEMPO = 0.2; + + double newTempo; + if((tempo - amount) < MIN_TEMPO) + newTempo = MIN_TEMPO; + else + newTempo = tempo - amount; + + [self setTempo:newTempo]; + return newTempo; } - (void)waitUntilCallbacksExit { diff --git a/Audio/Chain/OutputNode.h b/Audio/Chain/OutputNode.h index fdae901f0..ef9f9651d 100644 --- a/Audio/Chain/OutputNode.h +++ b/Audio/Chain/OutputNode.h @@ -61,7 +61,8 @@ - (void)setVolume:(double)v; -- (void)setSpeed:(double)s; +- (void)setPitch:(double)p; +- (void)setTempo:(double)t; - (void)setShouldContinue:(BOOL)s; diff --git a/Audio/Chain/OutputNode.m b/Audio/Chain/OutputNode.m index 6a67445e1..593cd8fd2 100644 --- a/Audio/Chain/OutputNode.m +++ b/Audio/Chain/OutputNode.m @@ -164,8 +164,12 @@ [output setVolume:v]; } -- (void)setSpeed:(double)s { - [output setSpeed:s]; +- (void)setPitch:(double)p { + [output setPitch:p]; +} + +- (void)setTempo:(double)t { + [output setTempo:t]; } - (void)setShouldContinue:(BOOL)s { diff --git a/Audio/CogAudio.xcodeproj/project.pbxproj b/Audio/CogAudio.xcodeproj/project.pbxproj index 1ed1f7ee4..f49021c89 100644 --- a/Audio/CogAudio.xcodeproj/project.pbxproj +++ b/Audio/CogAudio.xcodeproj/project.pbxproj @@ -79,6 +79,7 @@ 8377C64C27B8C51500E8BC0F /* fft_accelerate.c in Sources */ = {isa = PBXBuildFile; fileRef = 8377C64B27B8C51500E8BC0F /* fft_accelerate.c */; }; 8377C64E27B8C54400E8BC0F /* fft.h in Headers */ = {isa = PBXBuildFile; fileRef = 8377C64D27B8C54400E8BC0F /* fft.h */; }; 8384912718080FF100E7332D /* Logging.h in Headers */ = {isa = PBXBuildFile; fileRef = 8384912618080FF100E7332D /* Logging.h */; }; + 838A33722D06A97D00D0D770 /* librubberband.3.dylib in Frameworks */ = {isa = PBXBuildFile; fileRef = 838A33712D06A97D00D0D770 /* librubberband.3.dylib */; }; 839065F32853338700636FBB /* dsd2float.h in Headers */ = {isa = PBXBuildFile; fileRef = 839065F22853338700636FBB /* dsd2float.h */; }; 839366671815923C006DD712 /* CogPluginMulti.h in Headers */ = {isa = PBXBuildFile; fileRef = 839366651815923C006DD712 /* CogPluginMulti.h */; }; 839366681815923C006DD712 /* CogPluginMulti.m in Sources */ = {isa = PBXBuildFile; fileRef = 839366661815923C006DD712 /* CogPluginMulti.m */; }; @@ -192,6 +193,7 @@ 8377C64B27B8C51500E8BC0F /* fft_accelerate.c */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.c; path = fft_accelerate.c; sourceTree = ""; }; 8377C64D27B8C54400E8BC0F /* fft.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = fft.h; sourceTree = ""; }; 8384912618080FF100E7332D /* Logging.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = Logging.h; path = ../../Utils/Logging.h; sourceTree = ""; }; + 838A33712D06A97D00D0D770 /* librubberband.3.dylib */ = {isa = PBXFileReference; lastKnownFileType = "compiled.mach-o.dylib"; name = librubberband.3.dylib; path = ../ThirdParty/rubberband/lib/librubberband.3.dylib; sourceTree = SOURCE_ROOT; }; 839065F22853338700636FBB /* dsd2float.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = dsd2float.h; sourceTree = ""; }; 839366651815923C006DD712 /* CogPluginMulti.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = CogPluginMulti.h; sourceTree = ""; }; 839366661815923C006DD712 /* CogPluginMulti.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = CogPluginMulti.m; sourceTree = ""; }; @@ -233,6 +235,7 @@ 17D21DAE0B8BE76800D1EBDE /* AudioUnit.framework in Frameworks */, 17D21DAF0B8BE76800D1EBDE /* CoreAudio.framework in Frameworks */, 17D21DB00B8BE76800D1EBDE /* CoreAudioKit.framework in Frameworks */, + 838A33722D06A97D00D0D770 /* librubberband.3.dylib in Frameworks */, ); runOnlyForDeploymentPostprocessing = 0; }; @@ -324,6 +327,7 @@ 1058C7B2FEA5585E11CA2CBB /* Other Frameworks */ = { isa = PBXGroup; children = ( + 838A33712D06A97D00D0D770 /* librubberband.3.dylib */, 836DF615298F6E8900CD0580 /* libsoxr.0.dylib */, 83725A7B27AA0D8A0003F694 /* Accelerate.framework */, 17D21DAA0B8BE76800D1EBDE /* AudioUnit.framework */, @@ -693,11 +697,18 @@ GCC_PRECOMPILE_PREFIX_HEADER = YES; GCC_PREFIX_HEADER = CogAudio_Prefix.pch; GCC_PREPROCESSOR_DEFINITIONS = "DEBUG=1"; - HEADER_SEARCH_PATHS = ../ThirdParty/soxr/include; + HEADER_SEARCH_PATHS = ( + ../ThirdParty/soxr/include, + ../ThirdParty/rubberband/include, + ); INFOPLIST_FILE = Info.plist; INSTALL_PATH = "@executable_path/../Frameworks"; LD_RUNPATH_SEARCH_PATHS = "@loader_path/Frameworks"; - LIBRARY_SEARCH_PATHS = ../ThirdParty/soxr/lib; + LIBRARY_SEARCH_PATHS = ( + ../ThirdParty/rubberband/lib, + ../ThirdParty/soxr/lib, + "$(PROJECT_DIR)", + ); OTHER_LDFLAGS = ""; PRODUCT_BUNDLE_IDENTIFIER = org.cogx.cogaudio; PRODUCT_NAME = CogAudio; @@ -724,11 +735,18 @@ GCC_PRECOMPILE_PREFIX_HEADER = YES; GCC_PREFIX_HEADER = CogAudio_Prefix.pch; GCC_PREPROCESSOR_DEFINITIONS = ""; - HEADER_SEARCH_PATHS = ../ThirdParty/soxr/include; + HEADER_SEARCH_PATHS = ( + ../ThirdParty/soxr/include, + ../ThirdParty/rubberband/include, + ); INFOPLIST_FILE = Info.plist; INSTALL_PATH = "@executable_path/../Frameworks"; LD_RUNPATH_SEARCH_PATHS = "@loader_path/Frameworks"; - LIBRARY_SEARCH_PATHS = ../ThirdParty/soxr/lib; + LIBRARY_SEARCH_PATHS = ( + ../ThirdParty/rubberband/lib, + ../ThirdParty/soxr/lib, + "$(PROJECT_DIR)", + ); OTHER_LDFLAGS = ""; PRODUCT_BUNDLE_IDENTIFIER = org.cogx.cogaudio; PRODUCT_NAME = CogAudio; diff --git a/Audio/Output/OutputCoreAudio.h b/Audio/Output/OutputCoreAudio.h index 2a44bd0a7..d5a89a72e 100644 --- a/Audio/Output/OutputCoreAudio.h +++ b/Audio/Output/OutputCoreAudio.h @@ -35,8 +35,6 @@ using std::atomic_long; #import #endif -#import - @class OutputNode; @class FSurroundFilter; @@ -56,7 +54,8 @@ using std::atomic_long; double lastClippedSampleRate; - soxr_t rssimplespeed; + void *ts; + size_t blockSize, toDrop, samplesBuffered; double ssRenderedIn, ssLastRenderedIn; double ssRenderedOut; @@ -90,8 +89,8 @@ using std::atomic_long; float volume; float eqPreamp; - double speed; - double lastSpeed; + double pitch, tempo; + double lastPitch, lastTempo; AVAudioFormat *_deviceFormat; @@ -139,7 +138,9 @@ using std::atomic_long; float *samplePtr; float tempBuffer[512 * 32]; - float rsInBuffer[8192 * 32]; + float *rsPtrs[32]; + float rsInBuffer[1024 * 32]; + float rsOutBuffer[65536 * 32]; float inputBuffer[4096 * 32]; // 4096 samples times maximum supported channel count float fsurroundBuffer[8192 * 6]; float hrtfBuffer[4096 * 2]; @@ -182,6 +183,7 @@ using std::atomic_long; - (void)reportMotion:(simd_float4x4)matrix; -- (void)setSpeed:(double)s; +- (void)setPitch:(double)p; +- (void)setTempo:(double)t; @end diff --git a/Audio/Output/OutputCoreAudio.m b/Audio/Output/OutputCoreAudio.m index 93f6fa409..a0ff78179 100644 --- a/Audio/Output/OutputCoreAudio.m +++ b/Audio/Output/OutputCoreAudio.m @@ -23,12 +23,16 @@ #import "FSurroundFilter.h" +#import + #define OCTAVES 5 extern void scale_by_volume(float *buffer, size_t count, float volume); static NSString *CogPlaybackDidBeginNotificiation = @"CogPlaybackDidBeginNotificiation"; +#define tts ((RubberBandState)ts) + simd_float4x4 convertMatrix(CMRotationMatrix r) { simd_float4x4 matrix = { simd_make_float4(r.m33, -r.m31, r.m32, 0.0f), @@ -110,7 +114,7 @@ static void fillBuffers(AudioBufferList *ioData, const float *inbuffer, size_t c static void clearBuffers(AudioBufferList *ioData, size_t count, size_t offset) { for(int i = 0; i < ioData->mNumberBuffers; ++i) { - memset(ioData->mBuffers[i].mData + offset * sizeof(float), 0, count * sizeof(float)); + memset((uint8_t *)ioData->mBuffers[i].mData + offset * sizeof(float), 0, count * sizeof(float)); ioData->mBuffers[i].mNumberChannels = 1; } } @@ -338,8 +342,8 @@ static OSStatus eqRenderCallback(void *inRefCon, AudioUnitRenderActionFlags *ioA outputLock = [[NSLock alloc] init]; - speed = 1.0; - lastSpeed = 1.0; + pitch = 1.0; tempo = 1.0; + lastPitch = 1.0; lastTempo = 1.0; #ifdef OUTPUT_LOG NSString *logName = [NSTemporaryDirectory() stringByAppendingPathComponent:@"CogAudioLog.raw"]; @@ -352,21 +356,21 @@ static OSStatus eqRenderCallback(void *inRefCon, AudioUnitRenderActionFlags *ioA static OSStatus default_device_changed(AudioObjectID inObjectID, UInt32 inNumberAddresses, const AudioObjectPropertyAddress *inAddresses, void *inUserData) { - OutputCoreAudio *this = (__bridge OutputCoreAudio *)inUserData; - return [this setOutputDeviceByID:-1]; + OutputCoreAudio *_self = (__bridge OutputCoreAudio *)inUserData; + return [_self setOutputDeviceByID:-1]; } static OSStatus current_device_listener(AudioObjectID inObjectID, UInt32 inNumberAddresses, const AudioObjectPropertyAddress *inAddresses, void *inUserData) { - OutputCoreAudio *this = (__bridge OutputCoreAudio *)inUserData; + OutputCoreAudio *_self = (__bridge OutputCoreAudio *)inUserData; for(UInt32 i = 0; i < inNumberAddresses; ++i) { switch(inAddresses[i].mSelector) { case kAudioDevicePropertyDeviceIsAlive: - return [this setOutputDeviceByID:-1]; + return [_self setOutputDeviceByID:-1]; case kAudioDevicePropertyNominalSampleRate: case kAudioDevicePropertyStreamFormat: - this->outputdevicechanged = YES; + _self->outputdevicechanged = YES; return noErr; } } @@ -611,7 +615,7 @@ current_device_listener(AudioObjectID inObjectID, UInt32 inNumberAddresses, cons __Verify_noErr(AudioObjectGetPropertyDataSize(kAudioObjectSystemObject, &theAddress, 0, NULL, &propsize)); UInt32 nDevices = propsize / (UInt32)sizeof(AudioDeviceID); - AudioDeviceID *devids = malloc(propsize); + AudioDeviceID *devids = (AudioDeviceID *)malloc(propsize); __Verify_noErr(AudioObjectGetPropertyData(kAudioObjectSystemObject, &theAddress, 0, NULL, &propsize, devids)); theAddress.mSelector = kAudioHardwarePropertyDefaultOutputDevice; @@ -812,14 +816,35 @@ current_device_listener(AudioObjectID inObjectID, UInt32 inNumberAddresses, cons [outputLock unlock]; } - if(rssimplespeed) { - soxr_delete(rssimplespeed); + if(ts) { + rubberband_delete(tts); + ts = NULL; } - soxr_error_t error; - soxr_quality_spec_t q_spec = soxr_quality_spec(SOXR_HQ, SOXR_VR); - rssimplespeed = soxr_create(1 << OCTAVES, 1, realStreamFormat.mChannelsPerFrame, &error, NULL, &q_spec, NULL); - soxr_set_io_ratio(rssimplespeed, speed, 0); + RubberBandOptions options = RubberBandOptionProcessRealTime; + ts = rubberband_new(realStreamFormat.mSampleRate, realStreamFormat.mChannelsPerFrame, options, 1.0 / tempo, pitch); + + blockSize = 1024; + toDrop = rubberband_get_start_delay(tts); + samplesBuffered = 0; + rubberband_set_max_process_size(tts, (int)blockSize); + + for(size_t i = 0; i < 32; ++i) { + rsPtrs[i] = &rsInBuffer[1024 * i]; + } + + size_t toPad = rubberband_get_preferred_start_pad(tts); + if(toPad > 0) { + for(size_t i = 0; i < realStreamFormat.mChannelsPerFrame; ++i) { + memset(rsPtrs[i], 0, 1024 * sizeof(float)); + } + while(toPad > 0) { + size_t p = toPad; + if(p > blockSize) p = blockSize; + rubberband_process(tts, (const float * const *)rsPtrs, (int)p, false); + toPad -= p; + } + } ssRenderedIn = 0.0; ssLastRenderedIn = 0.0; @@ -951,37 +976,65 @@ current_device_listener(AudioObjectID inObjectID, UInt32 inNumberAddresses, cons int simpleSpeedInput = samplesRendered; int simpleSpeedRendered = 0; int channels = realStreamFormat.mChannelsPerFrame; - int max_block_len = 8192; + size_t max_block_len = blockSize; - if (fabs(speed - lastSpeed) > 1e-5) { - lastSpeed = speed; - soxr_set_io_ratio(rssimplespeed, speed, max_block_len); + if (fabs(pitch - lastPitch) > 1e-5 || + fabs(tempo - lastTempo) > 1e-5) { + lastPitch = pitch; + lastTempo = tempo; + rubberband_set_pitch_scale(tts, pitch); + rubberband_set_time_ratio(tts, 1.0 / tempo); } const double inputRatio = 1.0 / realStreamFormat.mSampleRate; - const double outputRatio = inputRatio * speed; + const double outputRatio = inputRatio * tempo; while (simpleSpeedInput > 0) { - int block_len = max_block_len - simpleSpeedRendered; - - if (!block_len) - break; - float *ibuf = samplePtr; - int len = simpleSpeedInput; - float *obuf = &rsInBuffer[simpleSpeedRendered * channels]; - size_t idone = 0; - size_t odone = 0; - int error = soxr_process(rssimplespeed, ibuf, len, &idone, obuf, block_len, &odone); - simpleSpeedInput -= idone; - ibuf += channels * idone; - simpleSpeedRendered += odone; - ssRenderedIn += idone * inputRatio; - ssRenderedOut += odone * outputRatio; + size_t len = simpleSpeedInput; + if(len > blockSize) len = blockSize; + + for(size_t i = 0; i < channels; ++i) { + cblas_scopy((int)len, ibuf + i, channels, rsPtrs[i], 1); + } + + rubberband_process(tts, (const float * const *)rsPtrs, (int)len, false); + + simpleSpeedInput -= len; + ibuf += len * channels; + ssRenderedIn += len * inputRatio; + + size_t samplesAvailable; + while ((samplesAvailable = rubberband_available(tts)) > 0) { + if(toDrop > 0) { + size_t blockDrop = toDrop; + if(blockDrop > blockSize) blockDrop = blockSize; + rubberband_retrieve(tts, (float * const *)rsPtrs, (int)blockDrop); + toDrop -= blockDrop; + continue; + } + size_t maxAvailable = 65536 - samplesBuffered; + if(samplesAvailable > maxAvailable) { + samplesAvailable = maxAvailable; + if(!samplesAvailable) { + break; + } + } + size_t samplesOut = samplesAvailable; + if(samplesOut > blockSize) samplesOut = blockSize; + rubberband_retrieve(tts, (float * const *)rsPtrs, (int)samplesOut); + for(size_t i = 0; i < channels; ++i) { + cblas_scopy((int)samplesOut, rsPtrs[i], 1, &rsOutBuffer[samplesBuffered * channels + i], channels); + } + samplesBuffered += samplesOut; + ssRenderedOut += samplesOut * outputRatio; + simpleSpeedRendered += samplesOut; + } samplePtr = ibuf; } - samplePtr = &rsInBuffer[0]; + samplePtr = &rsOutBuffer[0]; samplesRendered = simpleSpeedRendered; + samplesBuffered = 0; } [outputLock lock]; if(fsurround) { @@ -1288,8 +1341,12 @@ current_device_listener(AudioObjectID inObjectID, UInt32 inNumberAddresses, cons volume = v * 0.01f; } -- (void)setSpeed:(double)s { - speed = s; +- (void)setPitch:(double)p { + pitch = p; +} + +- (void)setTempo:(double)t { + tempo = t; } - (void)setEqualizerEnabled:(BOOL)enabled { @@ -1406,9 +1463,9 @@ current_device_listener(AudioObjectID inObjectID, UInt32 inNumberAddresses, cons rsstate_delete(rsvis); rsvis = NULL; } - if(rssimplespeed) { - soxr_delete(rssimplespeed); - rssimplespeed = NULL; + if(ts) { + rubberband_delete(tts); + ts = NULL; } stopCompleted = YES; } diff --git a/Base.lproj/MainMenu.xib b/Base.lproj/MainMenu.xib index d9b40e988..46c9b95b4 100644 --- a/Base.lproj/MainMenu.xib +++ b/Base.lproj/MainMenu.xib @@ -1,8 +1,8 @@ - + - + @@ -25,17 +25,17 @@ - + - + - + - + @@ -57,7 +57,7 @@ - + @@ -102,7 +102,7 @@ - + @@ -127,7 +127,7 @@ - + @@ -141,11 +141,11 @@ - + - - + + @@ -171,7 +171,7 @@ - + @@ -185,11 +185,11 @@ - + - - + + @@ -231,7 +231,7 @@ - + @@ -259,7 +259,7 @@ - + @@ -273,11 +273,11 @@ - + - - + + @@ -320,7 +320,7 @@ - + @@ -347,7 +347,7 @@ - + @@ -361,11 +361,11 @@ - + - - + + @@ -404,10 +404,10 @@ - + - + @@ -448,10 +448,10 @@ - + - + @@ -475,7 +475,7 @@ - + @@ -489,11 +489,11 @@ - + - - + + @@ -529,10 +529,10 @@ - + - + @@ -572,7 +572,7 @@ - + @@ -616,7 +616,7 @@ - + @@ -660,7 +660,7 @@ - + @@ -704,7 +704,7 @@ - + @@ -748,7 +748,7 @@ - + @@ -792,7 +792,7 @@ - + @@ -844,11 +844,11 @@ - + @@ -860,8 +860,8 @@ - - + + @@ -923,7 +923,7 @@ - + @@ -988,7 +988,7 @@ - + @@ -1022,7 +1022,11 @@ - + + + + + @@ -1273,7 +1277,7 @@ - + @@ -2355,10 +2359,12 @@ Gw + + - + @@ -2539,19 +2545,69 @@ Gw - + - - + + + + + + + + + + + + + + + + + + + + - + - + + + + + + + + + + + + + - + diff --git a/Cog.xcodeproj/project.pbxproj b/Cog.xcodeproj/project.pbxproj index 19f968ae9..c689b1055 100644 --- a/Cog.xcodeproj/project.pbxproj +++ b/Cog.xcodeproj/project.pbxproj @@ -98,13 +98,11 @@ 830C37A527B95EB300E02BB0 /* EqualizerWindowController.m in Sources */ = {isa = PBXBuildFile; fileRef = 830C37A427B95EB300E02BB0 /* EqualizerWindowController.m */; }; 830C37FC27B9956C00E02BB0 /* analyzer.c in Sources */ = {isa = PBXBuildFile; fileRef = 830C37F227B9956C00E02BB0 /* analyzer.c */; }; 831B99BF27C23E88005A969B /* Cog.sdef in Resources */ = {isa = PBXBuildFile; fileRef = 831B99BE27C23E88005A969B /* Cog.sdef */; }; - 83229C9F283B0095004626A8 /* SpectrumWindowController.m in Sources */ = {isa = PBXBuildFile; fileRef = 83229C9D283B0095004626A8 /* SpectrumWindowController.m */; }; 83256B68286661FC0036D9C0 /* libmpg123.0.dylib in Frameworks */ = {isa = PBXBuildFile; fileRef = 83256B672866617F0036D9C0 /* libmpg123.0.dylib */; }; 83256B69286661FC0036D9C0 /* libmpg123.0.dylib in CopyFiles */ = {isa = PBXBuildFile; fileRef = 83256B672866617F0036D9C0 /* libmpg123.0.dylib */; settings = {ATTRIBUTES = (CodeSignOnCopy, ); }; }; 8327DBA9293CAD2400CD0580 /* Organya.bundle in CopyFiles */ = {isa = PBXBuildFile; fileRef = 8327DB94293C923500CD0580 /* Organya.bundle */; settings = {ATTRIBUTES = (CodeSignOnCopy, RemoveHeadersOnCopy, ); }; }; 832923AF279FAC400048201E /* Cog.q1.json in Resources */ = {isa = PBXBuildFile; fileRef = 832923AE279FAC400048201E /* Cog.q1.json */; }; 832CFC4F2851AA1A002AC26F /* NSView+Visibility.m in Sources */ = {isa = PBXBuildFile; fileRef = 832CFC4E2851AA1A002AC26F /* NSView+Visibility.m */; }; - 832CFC562851AA8B002AC26F /* SpectrumViewCG.m in Sources */ = {isa = PBXBuildFile; fileRef = 832CFC552851AA8B002AC26F /* SpectrumViewCG.m */; }; 833D0C2527C4ABB80060E16A /* ScriptAdditions.m in Sources */ = {isa = PBXBuildFile; fileRef = 833D0C2427C4ABB80060E16A /* ScriptAdditions.m */; }; 83489C6B2782F78700BDCEA2 /* libvgmPlayer.bundle in CopyFiles */ = {isa = PBXBuildFile; fileRef = 83489C542782F2DF00BDCEA2 /* libvgmPlayer.bundle */; settings = {ATTRIBUTES = (CodeSignOnCopy, RemoveHeadersOnCopy, ); }; }; 834B05EA2859C006000B7DC0 /* TotalTimeTransformer.m in Sources */ = {isa = PBXBuildFile; fileRef = 834B05E92859C006000B7DC0 /* TotalTimeTransformer.m */; }; @@ -145,6 +143,13 @@ 837DC931285B3F790005C58A /* DataModel.xcdatamodeld in Sources */ = {isa = PBXBuildFile; fileRef = 837DC92F285B3F790005C58A /* DataModel.xcdatamodeld */; }; 8381A09227C5F72F00A1C530 /* SHA256Digest.m in Sources */ = {isa = PBXBuildFile; fileRef = 8381A09127C5F72F00A1C530 /* SHA256Digest.m */; }; 8384914018083E4E00E7332D /* filetype.icns in Resources */ = {isa = PBXBuildFile; fileRef = 8384913D18083E4E00E7332D /* filetype.icns */; }; + 838A33742D06A9B100D0D770 /* librubberband.3.dylib in Frameworks */ = {isa = PBXBuildFile; fileRef = 838A33732D06A9B100D0D770 /* librubberband.3.dylib */; }; + 838A33752D06A9CE00D0D770 /* librubberband.3.dylib in CopyFiles */ = {isa = PBXBuildFile; fileRef = 838A33732D06A9B100D0D770 /* librubberband.3.dylib */; settings = {ATTRIBUTES = (CodeSignOnCopy, ); }; }; + 838A337D2D06C14200D0D770 /* TempoSlider.m in Sources */ = {isa = PBXBuildFile; fileRef = 838A337C2D06C14200D0D770 /* TempoSlider.m */; }; + 838A337E2D06C14200D0D770 /* PitchSlider.m in Sources */ = {isa = PBXBuildFile; fileRef = 838A337A2D06C14200D0D770 /* PitchSlider.m */; }; + 838A33832D06CF4100D0D770 /* SpectrumViewCG.m in Sources */ = {isa = PBXBuildFile; fileRef = 838A33802D06CF4100D0D770 /* SpectrumViewCG.m */; }; + 838A33842D06CF4100D0D770 /* SpectrumWindowController.m in Sources */ = {isa = PBXBuildFile; fileRef = 838A33822D06CF4100D0D770 /* SpectrumWindowController.m */; }; + 838A33872D06CFCA00D0D770 /* SpeedButton.m in Sources */ = {isa = PBXBuildFile; fileRef = 838A33862D06CFCA00D0D770 /* SpeedButton.m */; }; 83922FBA286B1AA900A0B039 /* WebKit.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 83922FB6286B1AA900A0B039 /* WebKit.framework */; }; 839614A2286ED97200D3EEDB /* AboutWindowController.xib in Resources */ = {isa = PBXBuildFile; fileRef = 839614A0286ED97200D3EEDB /* AboutWindowController.xib */; }; 839614AD286EDA5C00D3EEDB /* SpectrumWindow.xib in Resources */ = {isa = PBXBuildFile; fileRef = 839614AB286EDA5C00D3EEDB /* SpectrumWindow.xib */; }; @@ -154,8 +159,6 @@ 83988F0E27BE0A5900A0E89A /* RedundantPlaylistDataStore.m in Sources */ = {isa = PBXBuildFile; fileRef = 83988F0D27BE0A5900A0E89A /* RedundantPlaylistDataStore.m */; }; 8399D4E21805A55000B503B1 /* XmlContainer.m in Sources */ = {isa = PBXBuildFile; fileRef = 8399D4E01805A55000B503B1 /* XmlContainer.m */; }; 839B837F286D7F8D00F529EE /* NumberHertzToStringTransformer.swift in Sources */ = {isa = PBXBuildFile; fileRef = 839B837E286D7F8D00F529EE /* NumberHertzToStringTransformer.swift */; }; - 839D48AA2C9E73AA00D03298 /* SpeedButton.m in Sources */ = {isa = PBXBuildFile; fileRef = 839D48A72C9E73AA00D03298 /* SpeedButton.m */; }; - 839D48AB2C9E73AA00D03298 /* SpeedSlider.m in Sources */ = {isa = PBXBuildFile; fileRef = 839D48A92C9E73AA00D03298 /* SpeedSlider.m */; }; 839DA7CF274A2D4C001B18E5 /* NSDictionary+Merge.m in Sources */ = {isa = PBXBuildFile; fileRef = 839DA7CE274A2D4C001B18E5 /* NSDictionary+Merge.m */; }; 839E56F52879625100DFB5F4 /* SADIE_D02-96000.mhr in Resources */ = {isa = PBXBuildFile; fileRef = 839E56F12879625100DFB5F4 /* SADIE_D02-96000.mhr */; }; 83A360B220E4E81D00192DAB /* Flac.bundle in CopyFiles */ = {isa = PBXBuildFile; fileRef = 8303A30C20E4E3D000951EF8 /* Flac.bundle */; settings = {ATTRIBUTES = (CodeSignOnCopy, RemoveHeadersOnCopy, ); }; }; @@ -721,6 +724,7 @@ 836EF0C827BB91E600BF35B2 /* libogg.0.dylib in CopyFiles */, 83AA7D07279EBCAF00087AA4 /* libswresample.5.dylib in CopyFiles */, 83AA7D06279EBCAD00087AA4 /* libavutil.59.dylib in CopyFiles */, + 838A33752D06A9CE00D0D770 /* librubberband.3.dylib in CopyFiles */, 83AA7D05279EBCAB00087AA4 /* libavformat.61.dylib in CopyFiles */, 83AA7D04279EBCA900087AA4 /* libavcodec.61.dylib in CopyFiles */, 83B72E3B279045B7006007A3 /* libfdk-aac.2.dylib in CopyFiles */, @@ -770,7 +774,7 @@ 177042970B8BC53600B86321 /* AppController.h */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.c.h; path = AppController.h; sourceTree = ""; }; 177042980B8BC53600B86321 /* AppController.m */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.c.objc; path = AppController.m; sourceTree = ""; }; 177042990B8BC53600B86321 /* PlaybackController.h */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.c.h; path = PlaybackController.h; sourceTree = ""; }; - 1770429A0B8BC53600B86321 /* PlaybackController.m */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.c.objc; path = PlaybackController.m; sourceTree = ""; }; + 1770429A0B8BC53600B86321 /* PlaybackController.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = PlaybackController.m; sourceTree = ""; }; 1778D3C80F645BF00037E7A0 /* MissingAlbumArtTransformer.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = MissingAlbumArtTransformer.h; path = InfoInspector/MissingAlbumArtTransformer.h; sourceTree = ""; }; 1778D3C90F645BF00037E7A0 /* MissingAlbumArtTransformer.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; name = MissingAlbumArtTransformer.m; path = InfoInspector/MissingAlbumArtTransformer.m; sourceTree = ""; }; 177EBF860B8BC2A70000BC8C /* ImageTextCell.h */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.c.h; path = ImageTextCell.h; sourceTree = ""; }; @@ -907,15 +911,11 @@ 830C37F227B9956C00E02BB0 /* analyzer.c */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.c; path = analyzer.c; sourceTree = ""; }; 8314D63B1A354DFE00EEE8E6 /* sidplay.xcodeproj */ = {isa = PBXFileReference; lastKnownFileType = "wrapper.pb-project"; name = sidplay.xcodeproj; path = Plugins/sidplay/sidplay.xcodeproj; sourceTree = ""; }; 831B99BE27C23E88005A969B /* Cog.sdef */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.xml; path = Cog.sdef; sourceTree = ""; }; - 83229C9C283B0095004626A8 /* SpectrumWindowController.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = SpectrumWindowController.h; sourceTree = ""; }; - 83229C9D283B0095004626A8 /* SpectrumWindowController.m */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.objc; path = SpectrumWindowController.m; sourceTree = ""; }; 83256B672866617F0036D9C0 /* libmpg123.0.dylib */ = {isa = PBXFileReference; lastKnownFileType = "compiled.mach-o.dylib"; name = libmpg123.0.dylib; path = ThirdParty/mpg123/lib/libmpg123.0.dylib; sourceTree = ""; }; 8327DB8F293C923500CD0580 /* Organya.xcodeproj */ = {isa = PBXFileReference; lastKnownFileType = "wrapper.pb-project"; name = Organya.xcodeproj; path = Plugins/Organya/Organya.xcodeproj; sourceTree = ""; }; 832923AE279FAC400048201E /* Cog.q1.json */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.json; path = Cog.q1.json; sourceTree = ""; }; 832CFC4E2851AA1A002AC26F /* NSView+Visibility.m */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.objc; path = "NSView+Visibility.m"; sourceTree = ""; }; 832CFC532851AA37002AC26F /* NSView+Visibility.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = "NSView+Visibility.h"; sourceTree = ""; }; - 832CFC542851AA8B002AC26F /* SpectrumViewCG.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = SpectrumViewCG.h; sourceTree = SOURCE_ROOT; }; - 832CFC552851AA8B002AC26F /* SpectrumViewCG.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = SpectrumViewCG.m; sourceTree = SOURCE_ROOT; }; 833D0C2027C4ABA00060E16A /* ScriptAdditions.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = ScriptAdditions.h; sourceTree = ""; }; 833D0C2427C4ABB80060E16A /* ScriptAdditions.m */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.objc; path = ScriptAdditions.m; sourceTree = ""; }; 833F681E1CDBCAA700AFB9F0 /* es */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.plist.strings; name = es; path = es.lproj/InfoPlist.strings; sourceTree = ""; }; @@ -981,6 +981,17 @@ 8384912518080F2D00E7332D /* Logging.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = Logging.h; sourceTree = ""; }; 8384913D18083E4E00E7332D /* filetype.icns */ = {isa = PBXFileReference; lastKnownFileType = image.icns; path = filetype.icns; sourceTree = ""; }; 83859520234FEB35004E9946 /* Cog.entitlements */ = {isa = PBXFileReference; lastKnownFileType = text.plist.entitlements; path = Cog.entitlements; sourceTree = ""; }; + 838A33732D06A9B100D0D770 /* librubberband.3.dylib */ = {isa = PBXFileReference; lastKnownFileType = "compiled.mach-o.dylib"; name = librubberband.3.dylib; path = ThirdParty/rubberband/lib/librubberband.3.dylib; sourceTree = ""; }; + 838A33792D06C14200D0D770 /* PitchSlider.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; name = PitchSlider.h; path = Window/PitchSlider.h; sourceTree = ""; }; + 838A337A2D06C14200D0D770 /* PitchSlider.m */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.objc; name = PitchSlider.m; path = Window/PitchSlider.m; sourceTree = ""; }; + 838A337B2D06C14200D0D770 /* TempoSlider.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; name = TempoSlider.h; path = Window/TempoSlider.h; sourceTree = ""; }; + 838A337C2D06C14200D0D770 /* TempoSlider.m */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.objc; name = TempoSlider.m; path = Window/TempoSlider.m; sourceTree = ""; }; + 838A337F2D06CF4100D0D770 /* SpectrumViewCG.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; name = SpectrumViewCG.h; path = Visualization/SpectrumViewCG.h; sourceTree = ""; }; + 838A33802D06CF4100D0D770 /* SpectrumViewCG.m */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.objc; name = SpectrumViewCG.m; path = Visualization/SpectrumViewCG.m; sourceTree = ""; }; + 838A33812D06CF4100D0D770 /* SpectrumWindowController.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; name = SpectrumWindowController.h; path = Visualization/SpectrumWindowController.h; sourceTree = ""; }; + 838A33822D06CF4100D0D770 /* SpectrumWindowController.m */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.objc; name = SpectrumWindowController.m; path = Visualization/SpectrumWindowController.m; sourceTree = ""; }; + 838A33852D06CFCA00D0D770 /* SpeedButton.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; name = SpeedButton.h; path = Window/SpeedButton.h; sourceTree = ""; }; + 838A33862D06CFCA00D0D770 /* SpeedButton.m */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.objc; name = SpeedButton.m; path = Window/SpeedButton.m; sourceTree = ""; }; 838EE79E29A8556000CD0580 /* en */ = {isa = PBXFileReference; lastKnownFileType = text.plist.strings; name = en; path = en.lproj/LyricsWindow.strings; sourceTree = ""; }; 838EE7A029A8556500CD0580 /* es */ = {isa = PBXFileReference; lastKnownFileType = text.plist.strings; name = es; path = es.lproj/LyricsWindow.strings; sourceTree = ""; }; 838EE7A229A8557000CD0580 /* ru */ = {isa = PBXFileReference; lastKnownFileType = text.plist.strings; name = ru; path = ru.lproj/LyricsWindow.strings; sourceTree = ""; }; @@ -1015,10 +1026,6 @@ 8399D4E01805A55000B503B1 /* XmlContainer.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = XmlContainer.m; sourceTree = ""; }; 8399D4E11805A55000B503B1 /* XmlContainer.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = XmlContainer.h; sourceTree = ""; }; 839B837E286D7F8D00F529EE /* NumberHertzToStringTransformer.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; name = NumberHertzToStringTransformer.swift; path = Transformers/NumberHertzToStringTransformer.swift; sourceTree = ""; }; - 839D48A62C9E73AA00D03298 /* SpeedButton.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = SpeedButton.h; sourceTree = ""; }; - 839D48A72C9E73AA00D03298 /* SpeedButton.m */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.objc; path = SpeedButton.m; sourceTree = ""; }; - 839D48A82C9E73AA00D03298 /* SpeedSlider.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = SpeedSlider.h; sourceTree = ""; }; - 839D48A92C9E73AA00D03298 /* SpeedSlider.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = SpeedSlider.m; sourceTree = ""; }; 839DA7CB274A2D4C001B18E5 /* NSDictionary+Merge.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = "NSDictionary+Merge.h"; sourceTree = ""; }; 839DA7CE274A2D4C001B18E5 /* NSDictionary+Merge.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = "NSDictionary+Merge.m"; sourceTree = ""; }; 839E3B53286595D700880EA2 /* GeneralPane.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = GeneralPane.h; path = Preferences/Preferences/GeneralPane.h; sourceTree = ""; }; @@ -1112,6 +1119,7 @@ 83922FBA286B1AA900A0B039 /* WebKit.framework in Frameworks */, 835FAC7E27BCDF5B00BA8562 /* libaom.a in Frameworks */, 837DC92B285B05710005C58A /* CoreData.framework in Frameworks */, + 838A33742D06A9B100D0D770 /* librubberband.3.dylib in Frameworks */, 83978E26285C596F0076ED21 /* FirebaseAnalytics in Frameworks */, 17BB5CF90B8A86350009ACB1 /* AudioUnit.framework in Frameworks */, 17BB5CFA0B8A86350009ACB1 /* CoreAudio.framework in Frameworks */, @@ -1168,6 +1176,7 @@ 1058C7A2FEA54F0111CA2CBB /* Other Frameworks */ = { isa = PBXGroup; children = ( + 838A33732D06A9B100D0D770 /* librubberband.3.dylib */, 836DF616298F6EC400CD0580 /* libsoxr.0.dylib */, 83256B672866617F0036D9C0 /* libmpg123.0.dylib */, 835FAC7C27BCDF5B00BA8562 /* libaom.a */, @@ -1412,6 +1421,8 @@ 836D28A718086386005B7299 /* MiniModeMenuTitleTransformer.m */, 17E0D5E30F520F02005B6FED /* MiniWindow.h */, 17E0D5E40F520F02005B6FED /* MiniWindow.m */, + 838A33792D06C14200D0D770 /* PitchSlider.h */, + 838A337A2D06C14200D0D770 /* PitchSlider.m */, 1752C36A0F59E00100F85F28 /* PlaybackButtons.h */, 1752C36B0F59E00100F85F28 /* PlaybackButtons.m */, 17E0D5E50F520F02005B6FED /* PositionSlider.h */, @@ -1421,10 +1432,10 @@ 172A12320F5911D20078EF0C /* RepeatTransformers.m */, 172A123A0F5912AE0078EF0C /* ShuffleTransformers.h */, 172A123B0F5912AE0078EF0C /* ShuffleTransformers.m */, - 839D48A62C9E73AA00D03298 /* SpeedButton.h */, - 839D48A72C9E73AA00D03298 /* SpeedButton.m */, - 839D48A82C9E73AA00D03298 /* SpeedSlider.h */, - 839D48A92C9E73AA00D03298 /* SpeedSlider.m */, + 838A33852D06CFCA00D0D770 /* SpeedButton.h */, + 838A33862D06CFCA00D0D770 /* SpeedButton.m */, + 838A337B2D06C14200D0D770 /* TempoSlider.h */, + 838A337C2D06C14200D0D770 /* TempoSlider.m */, 17E0D5E70F520F02005B6FED /* TimeField.h */, 17E0D5E80F520F02005B6FED /* TimeField.m */, 17E0D6180F520F9F005B6FED /* VolumeButton.h */, @@ -1811,15 +1822,15 @@ isa = PBXGroup; children = ( 830C37EF27B9956C00E02BB0 /* ThirdParty */, - 8377C66427B8CF7A00E8BC0F /* VisualizationController.h */, - 8377C66227B8CF6300E8BC0F /* SpectrumViewSK.h */, - 8377C66127B8CF6300E8BC0F /* SpectrumViewSK.m */, - 832CFC542851AA8B002AC26F /* SpectrumViewCG.h */, - 832CFC552851AA8B002AC26F /* SpectrumViewCG.m */, 8377C6B727B900F000E8BC0F /* SpectrumItem.h */, 8377C6B827B900F000E8BC0F /* SpectrumItem.m */, - 83229C9C283B0095004626A8 /* SpectrumWindowController.h */, - 83229C9D283B0095004626A8 /* SpectrumWindowController.m */, + 838A337F2D06CF4100D0D770 /* SpectrumViewCG.h */, + 838A33802D06CF4100D0D770 /* SpectrumViewCG.m */, + 8377C66227B8CF6300E8BC0F /* SpectrumViewSK.h */, + 8377C66127B8CF6300E8BC0F /* SpectrumViewSK.m */, + 838A33812D06CF4100D0D770 /* SpectrumWindowController.h */, + 838A33822D06CF4100D0D770 /* SpectrumWindowController.m */, + 8377C66427B8CF7A00E8BC0F /* VisualizationController.h */, ); name = Visualization; sourceTree = ""; @@ -2561,8 +2572,6 @@ 83A3B734283AE89000CC6593 /* ColorToValueTransformer.m in Sources */, 8D11072D0486CEB800E47090 /* main.m in Sources */, 8E75757109F31D5A0080F1EE /* DNDArrayController.m in Sources */, - 839D48AA2C9E73AA00D03298 /* SpeedButton.m in Sources */, - 839D48AB2C9E73AA00D03298 /* SpeedSlider.m in Sources */, 8E75757209F31D5A0080F1EE /* PlaylistController.m in Sources */, 8E75757309F31D5A0080F1EE /* PlaylistEntry.m in Sources */, 8E75757409F31D5A0080F1EE /* PlaylistView.m in Sources */, @@ -2572,6 +2581,7 @@ 177EBFA70B8BC2A70000BC8C /* ImageTextCell.m in Sources */, 177EC0270B8BC2CF0000BC8C /* TrackingCell.m in Sources */, 177EC0290B8BC2CF0000BC8C /* TrackingSlider.m in Sources */, + 838A33872D06CFCA00D0D770 /* SpeedButton.m in Sources */, 1770429C0B8BC53600B86321 /* AppController.m in Sources */, 1770429E0B8BC53600B86321 /* PlaybackController.m in Sources */, 8355D6B6180612F300D05687 /* NSData+MD5.m in Sources */, @@ -2588,7 +2598,10 @@ 5604D4F60D60726E004F5C5D /* SpotlightPlaylistEntry.m in Sources */, 56462EAF0D6341F6000AB68C /* SpotlightTransformers.m in Sources */, 830C37A527B95EB300E02BB0 /* EqualizerWindowController.m in Sources */, - 832CFC562851AA8B002AC26F /* SpectrumViewCG.m in Sources */, + 838A337D2D06C14200D0D770 /* TempoSlider.m in Sources */, + 838A337E2D06C14200D0D770 /* PitchSlider.m in Sources */, + 838A33832D06CF4100D0D770 /* SpectrumViewCG.m in Sources */, + 838A33842D06CF4100D0D770 /* SpectrumWindowController.m in Sources */, 83B61E2829A82A0200CD0580 /* LyricsWindowController.m in Sources */, 56462EB20D634206000AB68C /* SpotlightPlaylistController.m in Sources */, 07E18DF30D62B38400BB0E11 /* NSArray+ShuffleUtils.m in Sources */, @@ -2635,7 +2648,6 @@ 17F6C8070F603701000D9DA9 /* PlaybackEventController.m in Sources */, 83BC5AB220E4C87100631CD4 /* DualWindow.m in Sources */, 8307D30E28606148000FF8EB /* SandboxBroker.m in Sources */, - 83229C9F283B0095004626A8 /* SpectrumWindowController.m in Sources */, 835F00BB279BD1CD00055FCF /* SecondsFormatter.m in Sources */, 1784560F0F631E24007E8021 /* FileTreeViewController.m in Sources */, 178456120F631E31007E8021 /* SideViewController.m in Sources */, @@ -3025,6 +3037,8 @@ "$(PROJECT_DIR)/ThirdParty/avif/lib", "$(PROJECT_DIR)/ThirdParty/mpg123/lib", "$(PROJECT_DIR)/ThirdParty/soxr/lib", + "$(PROJECT_DIR)", + "$(PROJECT_DIR)/ThirdParty/rubberband/lib", ); OTHER_CFLAGS = ( "-D__MACOSX__", @@ -3082,6 +3096,8 @@ "$(PROJECT_DIR)/ThirdParty/avif/lib", "$(PROJECT_DIR)/ThirdParty/mpg123/lib", "$(PROJECT_DIR)/ThirdParty/soxr/lib", + "$(PROJECT_DIR)", + "$(PROJECT_DIR)/ThirdParty/rubberband/lib", ); OTHER_CFLAGS = ( "-D__MACOSX__", diff --git a/SpeedButton.h b/SpeedButton.h deleted file mode 100644 index 1f204c704..000000000 --- a/SpeedButton.h +++ /dev/null @@ -1,16 +0,0 @@ -// -// SpeedButton.h -// Cog -// -// Created by Christopher Snowhill on 9/20/24. -// Copyright 2024 __LoSnoCo__. All rights reserved. -// - -#import "SpeedSlider.h" -#import - -@interface SpeedButton : NSButton { - IBOutlet SpeedSlider *_popView; -} - -@end diff --git a/SpeedButton.m b/SpeedButton.m deleted file mode 100644 index 2b9882856..000000000 --- a/SpeedButton.m +++ /dev/null @@ -1,51 +0,0 @@ -// -// SpeedButton.m -// Cog -// -// Created by Christopher Snowhill on 9/20/24. -// Copyright 2024 __LoSnoCo__. All rights reserved. -// - -#import "SpeedButton.h" -#import "PlaybackController.h" - -@implementation SpeedButton { - NSPopover *popover; - NSViewController *viewController; -} - -- (void)awakeFromNib { - popover = [[NSPopover alloc] init]; - popover.behavior = NSPopoverBehaviorTransient; - [popover setContentSize:_popView.bounds.size]; -} - -- (void)scrollWheel:(NSEvent *)theEvent { - if([popover isShown]) { - [_popView scrollWheel:theEvent]; - return; - } - - double change = [theEvent deltaY]; - - [_popView setDoubleValue:[_popView doubleValue] + change]; - - [[_popView target] changeSpeed:_popView]; - - [_popView showToolTipForView:self closeAfter:1.0]; -} - -- (void)mouseDown:(NSEvent *)theEvent { - [popover close]; - - popover.contentViewController = nil; - viewController = [[NSViewController alloc] init]; - viewController.view = _popView; - popover.contentViewController = viewController; - - [popover showRelativeToRect:self.bounds ofView:self preferredEdge:NSRectEdgeMaxY]; - - [super mouseDown:theEvent]; -} - -@end diff --git a/ThirdParty/libraries.tar.xz b/ThirdParty/libraries.tar.xz index 24afe16eb..1a4b7c13c 100644 Binary files a/ThirdParty/libraries.tar.xz and b/ThirdParty/libraries.tar.xz differ diff --git a/ThirdParty/rubberband/README.md b/ThirdParty/rubberband/README.md new file mode 100644 index 000000000..2c7d4f20d --- /dev/null +++ b/ThirdParty/rubberband/README.md @@ -0,0 +1,7 @@ +Build the stock release of librubberband with meson and ninja, using the stock +cross build option files to build each architecture, then combine them with lipo. + +No changes were made to the upstream library, these binaries are only packaged to +simplify building and packaging the project. + +Version 4.0 was used. diff --git a/ThirdParty/rubberband/include/rubberband/RubberBandLiveShifter.h b/ThirdParty/rubberband/include/rubberband/RubberBandLiveShifter.h new file mode 100644 index 000000000..e809666e0 --- /dev/null +++ b/ThirdParty/rubberband/include/rubberband/RubberBandLiveShifter.h @@ -0,0 +1,353 @@ +/* -*- c-basic-offset: 4 indent-tabs-mode: nil -*- vi:set ts=8 sts=4 sw=4: */ + +/* + Rubber Band Library + An audio time-stretching and pitch-shifting library. + Copyright 2007-2024 Particular Programs Ltd. + + This program is free software; you can redistribute it and/or + modify it under the terms of the GNU General Public License as + published by the Free Software Foundation; either version 2 of the + License, or (at your option) any later version. See the file + COPYING included with this distribution for more information. + + Alternatively, if you have a valid commercial licence for the + Rubber Band Live Pitch Shifter obtained by agreement with the + copyright holders, you may redistribute and/or modify it under the + terms described in that licence. + + If you wish to distribute code using Rubber Band Live under terms + other than those of the GNU General Public License, you must + obtain a valid commercial licence before doing so. +*/ + +#ifndef RUBBERBAND_LIVE_SHIFTER_H +#define RUBBERBAND_LIVE_SHIFTER_H + +#define RUBBERBAND_VERSION "4.0.0" +#define RUBBERBAND_API_MAJOR_VERSION 3 +#define RUBBERBAND_API_MINOR_VERSION 0 + +#undef RUBBERBAND_LIVE_DLLEXPORT +#ifdef _MSC_VER +#define RUBBERBAND_LIVE_DLLEXPORT __declspec(dllexport) +#else +#define RUBBERBAND_LIVE_DLLEXPORT +#endif + +#include +#include +#include +#include +#include + +namespace RubberBand +{ + +/** + * ### Summary + * + * RubberBand::RubberBandLiveShifter is an interface to the Rubber + * Band Library designed for applications that need to perform + * pitch-shifting only, without time-stretching, and to do so in a + * straightforward block-by-block process with the shortest available + * processing delay. For the more general interface, see + * RubberBand::RubberBandStretcher. + * + * RubberBandLiveShifter has a much simpler API than + * RubberBandStretcher. Its process function, called + * RubberBandLiveShifter::shift(), accepts a fixed number of sample + * frames on each call and always returns exactly the same number of + * sample frames. This is in contrast to the + * process/available/retrieve call sequence that RubberBandStretcher + * requires as a result of its variable output rate. + * + * The number of frames accepted by and returned from + * RubberBandLiveShifter::shift() are not under the caller's control: + * they must always be exactly the number given by + * RubberBandLiveShifter::getBlockSize(). But this number is fixed for + * the lifetime of the shifter, so it only needs to be queried once + * after construction and then fixed-size buffers may be used. + * + * Using RubberBandLiveShifter also gives a shorter processing delay + * than a typical buffering setup using RubberBandStretcher, making it + * a useful choice for some streamed or live situations. However, it + * is still not a low-latency effect, with a delay of 50ms or more + * between input and output signals depending on configuration. (The + * actual value may be queried via + * RubberBandLiveShifter::getStartDelay().) The shifter is real-time + * safe in the sense of avoiding allocation, locking, or blocking + * operations in the processing path. + * + * ### Thread safety + * + * Multiple instances of RubberBandLiveShifter may be created and used + * in separate threads concurrently. However, for any single instance + * of RubberBandLiveShifter, you may not call + * RubberBandLiveShifter::shift() more than once concurrently, and you + * may not change the pitch scaling ratio using + * RubberBandLiveShifter::setPitchScale() while a + * RubberBandLiveShifter::shift() call is being executed. Changing the + * ratio is real-time safe, so when the pitch ratio is time-varying, + * it is normal to update the ratio before each shift call. + */ +class RUBBERBAND_LIVE_DLLEXPORT +RubberBandLiveShifter +{ +public: + enum Option { + OptionWindowShort = 0x00000000, + OptionWindowMedium = 0x00100000, + + OptionFormantShifted = 0x00000000, + OptionFormantPreserved = 0x01000000, + + OptionChannelsApart = 0x00000000, + OptionChannelsTogether = 0x10000000 + + // n.b. Options is int, so we must stop before 0x80000000 + }; + + /** + * A bitwise OR of values from the RubberBandLiveShifter::Option + * enum. + */ + typedef int Options; + + enum PresetOption { + DefaultOptions = 0x00000000 + }; + + /** + * Interface for log callbacks that may optionally be provided to + * the shifter on construction. + * + * If a Logger is provided, the shifter will call one of these + * functions instead of sending output to \c cerr when there is + * something to report. This allows debug output to be diverted to + * an application's logging facilities, and/or handled in an + * RT-safe way. See setDebugLevel() for details about how and when + * RubberBandLiveShifter reports something in this way. + * + * The message text passed to each of these log functions is a + * C-style string with no particular guaranteed lifespan. If you + * need to retain it, copy it before returning. Do not free it. + * + * @see setDebugLevel + * @see setDefaultDebugLevel + */ + struct Logger { + /// Receive a log message with no numeric values. + virtual void log(const char *) = 0; + + /// Receive a log message and one accompanying numeric value. + virtual void log(const char *, double) = 0; + + /// Receive a log message and two accompanying numeric values. + virtual void log(const char *, double, double) = 0; + + virtual ~Logger() { } + }; + + /** + * Construct a pitch shifter object to run at the given sample + * rate, with the given number of channels. + */ + RubberBandLiveShifter(size_t sampleRate, size_t channels, + Options options); + + /** + * Construct a pitch shifter object with a custom debug + * logger. This may be useful for debugging if the default logger + * output (which simply goes to \c cerr) is not visible in the + * runtime environment, or if the application has a standard or + * more realtime-appropriate logging mechanism. + * + * See the documentation for the other constructor above for + * details of the arguments other than the logger. + * + * Note that although the supplied logger gets to decide what to + * do with log messages, the separately-set debug level (see + * setDebugLevel() and setDefaultDebugLevel()) still determines + * whether any given debug message is sent to the logger in the + * first place. + */ + RubberBandLiveShifter(size_t sampleRate, size_t channels, + std::shared_ptr logger, + Options options); + + ~RubberBandLiveShifter(); + + /** + * Reset the shifter's internal buffers. The shifter should + * subsequently behave as if it had just been constructed + * (although retaining the current pitch ratio). + */ + void reset(); + + /** + * Set the pitch scaling ratio for the shifter. This is the ratio + * of target frequency to source frequency. For example, a ratio + * of 2.0 would shift up by one octave; 0.5 down by one octave; or + * 1.0 leave the pitch unaffected. + * + * To put this in musical terms, a pitch scaling ratio + * corresponding to a shift of S equal-tempered semitones (where S + * is positive for an upwards shift and negative for downwards) is + * pow(2.0, S / 12.0). + * + * This function may be called at any time, so long as it is not + * called concurrently with shift(). You should either call this + * function from the same thread as shift(), or provide your own + * mutex or similar mechanism to ensure that setPitchScale and + * shift() cannot be run at once (there is no internal mutex for + * this purpose). + */ + void setPitchScale(double scale); + + /** + * Set a pitch scale for the vocal formant envelope separately + * from the overall pitch scale. This is a ratio of target + * frequency to source frequency. For example, a ratio of 2.0 + * would shift the formant envelope up by one octave; 0.5 down by + * one octave; or 1.0 leave the formant unaffected. + * + * By default this is set to the special value of 0.0, which + * causes the scale to be calculated automatically. It will be + * treated as 1.0 / the pitch scale if OptionFormantPreserved is + * specified, or 1.0 for OptionFormantShifted. + * + * Conversely, if this is set to a value other than the default + * 0.0, formant shifting will happen regardless of the state of + * the OptionFormantPreserved/OptionFormantShifted option. + * + * This function is provided for special effects only. You do not + * need to call it for ordinary pitch shifting, with or without + * formant preservation - just specify or omit the + * OptionFormantPreserved option as appropriate. Use this function + * only if you want to shift formants by a distance other than + * that of the overall pitch shift. + */ + void setFormantScale(double scale); + + /** + * Return the last pitch scaling ratio value that was set (either + * on construction or with setPitchScale()). + */ + double getPitchScale() const; + + /** + * Return the last formant scaling ratio that was set with + * setFormantScale, or 0.0 if the default automatic scaling is in + * effect. + */ + double getFormantScale() const; + + /** + * Return the output delay of the shifter. This is the number of + * audio samples that one should discard at the start of the + * output, in order to ensure that the resulting audio has the + * expected time alignment with the input. + * + * Ensure you have set the pitch scale to its proper starting + * value before calling getStartDelay(). + */ + size_t getStartDelay() const; + + /** + * Return the number of channels this shifter was constructed + * with. + */ + size_t getChannelCount() const; + + /** + * Change an OptionFormant configuration setting. This may be + * called at any time in any mode. + * + * Note that if running multi-threaded in Offline mode, the change + * may not take effect immediately if processing is already under + * way when this function is called. + */ + void setFormantOption(Options options); + + /** + * Query the number of sample frames that must be passed to, and + * will be returned by, each shift() call. This value is fixed for + * the lifetime of the shifter. + * + * Note that the blocksize refers to the number of audio sample + * frames, which may be multi-channel, not the number of + * individual samples. + */ + size_t getBlockSize() const; + + /** + * Pitch-shift a single block of sample frames. The number of + * sample frames (samples per channel) processed per call is + * constant. + * + * "input" should point to de-interleaved audio data with one + * float array per channel, with each array containing n samples + * where n is the value returned by getBlockSize(). + * + * "output" should point to a float array per channel, with each + * array having enough room to store n samples where n is the value + * returned by getBlockSize(). + * + * The input and output must be separate arrays; they cannot alias + * one another or overlap. + * + * Sample values are conventionally expected to be in the range + * -1.0f to +1.0f. + */ + void shift(const float *const *input, float *const *output); + + /** + * Set the level of debug output. The supported values are: + * + * 0. Report errors only. + * + * 1. Report some information on construction and ratio + * change. Nothing is reported during normal processing unless + * something changes. + * + * 2. Report a significant amount of information about ongoing + * calculations during normal processing. + * + * The default is whatever has been set using + * setDefaultDebugLevel(), or 0 if that function has not been + * called. + * + * All output goes to \c cerr unless a custom + * RubberBandLiveShifter::Logger has been provided on + * construction. Because writing to \c cerr is not RT-safe, only + * debug level 0 is RT-safe in normal use by default. Debug levels + * 0 and 1 use only C-string constants as debug messages, so they + * are RT-safe if your custom logger is RT-safe. Levels 2 and 3 + * are not guaranteed to be RT-safe in any conditions as they may + * construct messages by allocation. + * + * @see Logger + * @see setDefaultDebugLevel + */ + void setDebugLevel(int level); + + /** + * Set the default level of debug output for subsequently + * constructed shifters. + * + * @see setDebugLevel + */ + static void setDefaultDebugLevel(int level); + +protected: + class Impl; + Impl *m_d; + + RubberBandLiveShifter(const RubberBandLiveShifter &) =delete; + RubberBandLiveShifter &operator=(const RubberBandLiveShifter &) =delete; +}; + +} + +#endif diff --git a/ThirdParty/rubberband/include/rubberband/RubberBandStretcher.h b/ThirdParty/rubberband/include/rubberband/RubberBandStretcher.h new file mode 100644 index 000000000..b938ea906 --- /dev/null +++ b/ThirdParty/rubberband/include/rubberband/RubberBandStretcher.h @@ -0,0 +1,1099 @@ +/* -*- c-basic-offset: 4 indent-tabs-mode: nil -*- vi:set ts=8 sts=4 sw=4: */ + +/* + Rubber Band Library + An audio time-stretching and pitch-shifting library. + Copyright 2007-2024 Particular Programs Ltd. + + This program is free software; you can redistribute it and/or + modify it under the terms of the GNU General Public License as + published by the Free Software Foundation; either version 2 of the + License, or (at your option) any later version. See the file + COPYING included with this distribution for more information. + + Alternatively, if you have a valid commercial licence for the + Rubber Band Library obtained by agreement with the copyright + holders, you may redistribute and/or modify it under the terms + described in that licence. + + If you wish to distribute code using the Rubber Band Library + under terms other than those of the GNU General Public License, + you must obtain a valid commercial licence before doing so. +*/ + +#ifndef RUBBERBAND_STRETCHER_H +#define RUBBERBAND_STRETCHER_H + +#define RUBBERBAND_VERSION "4.0.0" +#define RUBBERBAND_API_MAJOR_VERSION 3 +#define RUBBERBAND_API_MINOR_VERSION 0 + +#undef RUBBERBAND_DLLEXPORT +#ifdef _MSC_VER +#ifndef RUBBERBAND_STATIC +#define RUBBERBAND_DLLEXPORT __declspec(dllexport) +#else +#define RUBBERBAND_DLLEXPORT +#endif +#else +#define RUBBERBAND_DLLEXPORT +#endif + +#include +#include +#include +#include +#include + +namespace RubberBand +{ + +/** + * @mainpage RubberBand + * + * ### Summary + * + * The primary Rubber Band Library API is contained in the class + * RubberBand::RubberBandStretcher. This class can perform both pitch + * shifting and time stretching and supports every feature of the + * library. A simpler, more limited API that supports only + * pitch-shifting can be found in RubberBand::RubberBandLiveShifter. + * + * RubberBandStretcher supports two processing modes, offline and + * real-time, and two processing "engines", known as the R2 or Faster + * engine and the R3 or Finer engine. The choices of processing mode + * and engine are fixed on construction: see the constructor + * RubberBandStretcher::RubberBandStretcher. The two engines work + * identically in API terms, and both of them support both offline and + * real-time modes as described below. + * + * ### Offline mode + * + * In offline mode, you must provide the audio block-by-block in + * two passes. In the first pass, call RubberBandStretcher::study() on + * each block; in the second pass, call RubberBandStretcher::process() + * on each block and receive the output via + * RubberBandStretcher::retrieve(). + * + * In offline mode, the time and pitch ratios are fixed as soon as the + * study pass has begun and cannot be changed afterwards. (But see + * RubberBandStretcher::setKeyFrameMap() for a way to do pre-planned + * variable time stretching in offline mode.) Offline mode also + * performs padding and delay compensation so that the stretched + * result has an exact start and duration. + * + * ### Real-time mode + * + * In \b real-time mode, there is no study pass, just a single + * streaming pass in which the audio is passed to + * RubberBandStretcher::process() and output received via + * RubberBandStretcher::retrieve(). + * + * In real-time mode you can change the time and pitch ratios at any + * time. + * + * You may need to perform signal padding and delay compensation in + * real-time mode; see RubberBandStretcher::getPreferredStartPad() and + * RubberBandStretcher::getStartDelay() for details. + * + * Rubber Band Library is RT-safe when used in real-time mode with + * "normal" processing parameters. That is, it performs no allocation, + * locking, or blocking operations after initialisation during normal + * use, even when the time and pitch ratios change. There are certain + * exceptions that include error states and extremely rapid changes + * between extreme ratios, as well as the case in which more frames + * are passed to RubberBandStretcher::process() than the values + * returned by RubberBandStretcher::getSamplesRequired() or set using + * RubberBandStretcher::setMaxProcessSize(), when buffer reallocation + * may occur. See the latter function's documentation for + * details. Note that offline mode is never RT-safe. + * + * ### Thread safety + * + * Multiple instances of RubberBandStretcher may be created and used + * in separate threads concurrently. However, for any single instance + * of RubberBandStretcher, you may not call + * RubberBandStretcher::process() more than once concurrently, and you + * may not change the time or pitch ratio while a + * RubberBandStretcher::process() call is being executed (if the + * stretcher was created in "real-time mode"; in "offline mode" you + * can't change the ratios during use anyway). + * + * So you can run RubberBandStretcher::process() in its own thread if + * you like, but if you want to change ratios dynamically from a + * different thread, you will need some form of mutex in your code. + * Changing the time or pitch ratio is real-time safe except in + * extreme circumstances, so for most applications that may change + * these dynamically it probably makes most sense to do so from the + * same thread as calls RubberBandStretcher::process(), even if that + * is a real-time thread. + */ +class RUBBERBAND_DLLEXPORT +RubberBandStretcher +{ +public: + /** + * Processing options for the timestretcher. The preferred + * options should normally be set in the constructor, as a bitwise + * OR of the option flags. The default value (DefaultOptions) is + * intended to give good results in most situations. + * + * 1. Flags prefixed \c OptionProcess determine how the timestretcher + * will be invoked. These options may not be changed after + * construction. + * + * \li \c OptionProcessOffline - Run the stretcher in offline + * mode. In this mode the input data needs to be provided + * twice, once to study(), which calculates a stretch profile + * for the audio, and once to process(), which stretches it. + * + * \li \c OptionProcessRealTime - Run the stretcher in real-time + * mode. In this mode only process() should be called, and the + * stretcher adjusts dynamically in response to the input audio. + * + * The Process setting is likely to depend on your architecture: + * non-real-time operation on seekable files: Offline; real-time + * or streaming operation: RealTime. + * + * 2. Flags prefixed \c OptionEngine select the core Rubber Band + * processing engine to be used. These options may not be changed + * after construction. + * + * \li \c OptionEngineFaster - Use the Rubber Band Library R2 + * (Faster) engine. This is the engine implemented in Rubber + * Band Library v1.x and v2.x, and it remains the default in + * newer versions. It uses substantially less CPU than the R3 + * engine and there are still many situations in which it is + * likely to be the more appropriate choice. + * + * \li \c OptionEngineFiner - Use the Rubber Band Library R3 + * (Finer) engine. This engine was introduced in Rubber Band + * Library v3.0. It produces higher-quality results than the R2 + * engine for most material, especially complex mixes, vocals + * and other sounds that have soft onsets and smooth pitch + * changes, and music with substantial bass content. However, it + * uses much more CPU power than the R2 engine. + * + * Important note: Consider calling getEngineVersion() after + * construction to make sure the engine you requested is + * active. That's not because engine selection can fail, but + * because Rubber Band Library ignores any unknown options + * supplied on construction - so a program that requests the R3 + * engine but ends up linked against an older version of the + * library (prior to v3.0) will silently use the R2 engine + * instead. Calling the v3.0 function getEngineVersion() will + * ensure a link failure in this situation instead, and supply a + * reassuring run-time check. + * + * 3. Flags prefixed \c OptionTransients control the component + * frequency phase-reset mechanism in the R2 engine, that may be + * used at transient points to provide clarity and realism to + * percussion and other significant transient sounds. These + * options have no effect when using the R3 engine. These options + * may be changed after construction when running in real-time + * mode, but not when running in offline mode. + * + * \li \c OptionTransientsCrisp - Reset component phases at the + * peak of each transient (the start of a significant note or + * percussive event). This, the default setting, usually + * results in a clear-sounding output; but it is not always + * consistent, and may cause interruptions in stable sounds + * present at the same time as transient events. The + * OptionDetector flags (below) can be used to tune this to some + * extent. + * + * \li \c OptionTransientsMixed - Reset component phases at the + * peak of each transient, outside a frequency range typical of + * musical fundamental frequencies. The results may be more + * regular for mixed stable and percussive notes than + * \c OptionTransientsCrisp, but with a "phasier" sound. The + * balance may sound very good for certain types of music and + * fairly bad for others. + * + * \li \c OptionTransientsSmooth - Do not reset component phases + * at any point. The results will be smoother and more regular + * but may be less clear than with either of the other + * transients flags. + * + * 4. Flags prefixed \c OptionDetector control the type of + * transient detector used in the R2 engine. These options have + * no effect when using the R3 engine. These options may be + * changed after construction when running in real-time mode, but + * not when running in offline mode. + * + * \li \c OptionDetectorCompound - Use a general-purpose + * transient detector which is likely to be good for most + * situations. This is the default. + * + * \li \c OptionDetectorPercussive - Detect percussive + * transients. Note that this was the default and only option + * in Rubber Band versions prior to 1.5. + * + * \li \c OptionDetectorSoft - Use an onset detector with less + * of a bias toward percussive transients. This may give better + * results with certain material (e.g. relatively monophonic + * piano music). + * + * 5. Flags prefixed \c OptionPhase control the adjustment of + * component frequency phases in the R2 engine from one analysis + * window to the next during non-transient segments. These + * options have no effect when using the R3 engine. These options + * may be changed at any time. + * + * \li \c OptionPhaseLaminar - Adjust phases when stretching in + * such a way as to try to retain the continuity of phase + * relationships between adjacent frequency bins whose phases + * are behaving in similar ways. This, the default setting, + * should give good results in most situations. + * + * \li \c OptionPhaseIndependent - Adjust the phase in each + * frequency bin independently from its neighbours. This + * usually results in a slightly softer, phasier sound. + * + * 6. Flags prefixed \c OptionThreading control the threading + * model of the stretcher. These options may not be changed after + * construction. + * + * \li \c OptionThreadingAuto - Permit the stretcher to + * determine its own threading model. In the R2 engine this + * means using one processing thread per audio channel in + * offline mode if the stretcher is able to determine that more + * than one CPU is available, and one thread only in realtime + * mode. The R3 engine does not currently have a multi-threaded + * mode, but if one is introduced in future, this option may use + * it. This is the default. + * + * \li \c OptionThreadingNever - Never use more than one thread. + * + * \li \c OptionThreadingAlways - Use multiple threads in any + * situation where \c OptionThreadingAuto would do so, except omit + * the check for multiple CPUs and instead assume it to be true. + * + * 7. Flags prefixed \c OptionWindow influence the window size for + * FFT processing. In the R2 engine these affect the resulting + * sound quality but have relatively little effect on processing + * speed. With the R3 engine they can dramatically affect + * processing speed as well as output quality. These options may + * not be changed after construction. + * + * \li \c OptionWindowStandard - Use the default window size. + * The actual size will vary depending on other parameters. + * This option is expected to produce better results than the + * other window options in most situations. In the R3 engine + * this causes the engine's full multi-resolution processing + * scheme to be used. + * + * \li \c OptionWindowShort - Use a shorter window. This has + * different effects with R2 and R3 engines. + * + * With the R2 engine it may result in crisper sound for audio + * that depends strongly on its timing qualities, but is likely + * to sound worse in other ways and will have similar + * efficiency. + * + * With the R3 engine, it causes the engine to be restricted to + * a single window size, resulting in both dramatically faster + * processing and lower delay than OptionWindowStandard, but at + * the expense of some sound quality. It may still sound better + * for non-percussive material than the R2 engine. + * + * With both engines it reduces the start delay somewhat (see + * RubberBandStretcher::getStartDelay) which may be useful for + * real-time handling. + * + * \li \c OptionWindowLong - Use a longer window. With the R2 + * engine this is likely to result in a smoother sound at the + * expense of clarity and timing. The R3 engine currently + * ignores this option, treating it like OptionWindowStandard. + * + * 8. Flags prefixed \c OptionSmoothing control the use of + * window-presum FFT and time-domain smoothing in the R2 + * engine. These options have no effect when using the R3 engine. + * These options may not be changed after construction. + * + * \li \c OptionSmoothingOff - Do not use time-domain smoothing. + * This is the default. + * + * \li \c OptionSmoothingOn - Use time-domain smoothing. This + * will result in a softer sound with some audible artifacts + * around sharp transients, but it may be appropriate for longer + * stretches of some instruments and can mix well with + * OptionWindowShort. + * + * 9. Flags prefixed \c OptionFormant control the handling of + * formant shape (spectral envelope) when pitch-shifting. These + * options affect both the R2 and R3 engines. These options may + * be changed at any time. + * + * \li \c OptionFormantShifted - Apply no special formant + * processing. The spectral envelope will be pitch shifted as + * normal. This is the default. + * + * \li \c OptionFormantPreserved - Preserve the spectral + * envelope of the unshifted signal. This permits shifting the + * note frequency without so substantially affecting the + * perceived pitch profile of the voice or instrument. + * + * 10. Flags prefixed \c OptionPitch control the method used for + * pitch shifting. These options affect only realtime mode. In + * offline mode the method is not adjustable. In the R2 engine + * these options may be changed at any time; in the R3 engine they + * may be set only on construction. + * + * \li \c OptionPitchHighSpeed - Favour CPU cost over sound + * quality. This is the default. Use this when time-stretching + * only, or for fixed pitch shifts where CPU usage is of + * concern. Do not use this for arbitrarily time-varying pitch + * shifts (see OptionPitchHighConsistency below). + * + * \li \c OptionPitchHighQuality - Favour sound quality over CPU + * cost. Use this for fixed pitch shifts where sound quality is + * of most concern. Do not use this for arbitrarily time-varying + * pitch shifts (see OptionPitchHighConsistency below). + + * \li \c OptionPitchHighConsistency - Use a method that + * supports dynamic pitch changes without discontinuities, + * including when crossing the 1.0 pitch scale. This may cost + * more in CPU than the default, especially when the pitch scale + * is exactly 1.0. You should use this option whenever you wish + * to support dynamically changing pitch shift during + * processing. + * + * 11. Flags prefixed \c OptionChannels control the method used + * for processing two-channel stereo audio. These options may not + * be changed after construction. + * + * \li \c OptionChannelsApart - Channels are handled for maximum + * individual fidelity, at the expense of synchronisation. In + * the R3 engine, this means frequency-bin synchronisation is + * maintained more closely for lower-frequency content than + * higher. In R2, it means the stereo channels are processed + * individually and only synchronised at transients. In both + * engines this gives the highest quality for the individual + * channels but a more diffuse stereo image, an unnatural + * increase in "width", and generally a loss of mono + * compatibility (i.e. mono mixes from stereo can sound phasy). + * This option is the default. + * + * \li \c OptionChannelsTogether - Channels are handled for + * higher synchronisation at some expense of individual + * fidelity. In particular, a stretcher processing two channels + * will treat its input as a stereo pair and aim to maximise + * clarity at the centre and preserve mono compatibility. This + * gives relatively less stereo space and width than the + * default, as well as slightly lower fidelity for individual + * channel content, but the results may be more appropriate for + * many situations making use of stereo mixes. + * + * Finally, flags prefixed \c OptionStretch are obsolete flags + * provided for backward compatibility only. They are ignored by + * the stretcher. + */ + enum Option { + + OptionProcessOffline = 0x00000000, + OptionProcessRealTime = 0x00000001, + + OptionStretchElastic = 0x00000000, // obsolete + OptionStretchPrecise = 0x00000010, // obsolete + + OptionTransientsCrisp = 0x00000000, + OptionTransientsMixed = 0x00000100, + OptionTransientsSmooth = 0x00000200, + + OptionDetectorCompound = 0x00000000, + OptionDetectorPercussive = 0x00000400, + OptionDetectorSoft = 0x00000800, + + OptionPhaseLaminar = 0x00000000, + OptionPhaseIndependent = 0x00002000, + + OptionThreadingAuto = 0x00000000, + OptionThreadingNever = 0x00010000, + OptionThreadingAlways = 0x00020000, + + OptionWindowStandard = 0x00000000, + OptionWindowShort = 0x00100000, + OptionWindowLong = 0x00200000, + + OptionSmoothingOff = 0x00000000, + OptionSmoothingOn = 0x00800000, + + OptionFormantShifted = 0x00000000, + OptionFormantPreserved = 0x01000000, + + OptionPitchHighSpeed = 0x00000000, + OptionPitchHighQuality = 0x02000000, + OptionPitchHighConsistency = 0x04000000, + + OptionChannelsApart = 0x00000000, + OptionChannelsTogether = 0x10000000, + + OptionEngineFaster = 0x00000000, + OptionEngineFiner = 0x20000000 + + // n.b. Options is int, so we must stop before 0x80000000 + }; + + /** + * A bitwise OR of values from the RubberBandStretcher::Option + * enum. + */ + typedef int Options; + + enum PresetOption { + DefaultOptions = 0x00000000, + PercussiveOptions = 0x00102000 + }; + + /** + * Interface for log callbacks that may optionally be provided to + * the stretcher on construction. + * + * If a Logger is provided, the stretcher will call one of these + * functions instead of sending output to \c cerr when there is + * something to report. This allows debug output to be diverted to + * an application's logging facilities, and/or handled in an + * RT-safe way. See setDebugLevel() for details about how and when + * RubberBandStretcher reports something in this way. + * + * The message text passed to each of these log functions is a + * C-style string with no particular guaranteed lifespan. If you + * need to retain it, copy it before returning. Do not free it. + * + * @see setDebugLevel + * @see setDefaultDebugLevel + */ + struct Logger { + /// Receive a log message with no numeric values. + virtual void log(const char *) = 0; + + /// Receive a log message and one accompanying numeric value. + virtual void log(const char *, double) = 0; + + /// Receive a log message and two accompanying numeric values. + virtual void log(const char *, double, double) = 0; + + virtual ~Logger() { } + }; + + /** + * Construct a time and pitch stretcher object to run at the given + * sample rate, with the given number of channels. + * + * Both of the stretcher engines provide their best balance of + * quality with efficiency at sample rates of 44100 or 48000 Hz. + * Other rates may be used, and the stretcher should produce + * sensible output with any rate from 8000 to 192000 Hz, but you + * are advised to use 44100 or 48000 where practical. Do not use + * rates below 8000 or above 192000 Hz. + * + * Initial time and pitch scaling ratios and other processing + * options may be provided. In particular, the behaviour of the + * stretcher depends strongly on whether offline or real-time mode + * is selected on construction (via OptionProcessOffline or + * OptionProcessRealTime option - offline is the default). + * + * In offline mode, you must provide the audio block-by-block in + * two passes: in the first pass calling study(), in the second + * pass calling process() and receiving the output via + * retrieve(). In real-time mode, there is no study pass, just a + * single streaming pass in which the audio is passed to process() + * and output received via retrieve(). + * + * In real-time mode you can change the time and pitch ratios at + * any time, but in offline mode they are fixed and cannot be + * changed after the study pass has begun. (However, see + * setKeyFrameMap() for a way to do pre-planned variable time + * stretching in offline mode.) + * + * See the option documentation above for more details. + */ + RubberBandStretcher(size_t sampleRate, + size_t channels, + Options options = DefaultOptions, + double initialTimeRatio = 1.0, + double initialPitchScale = 1.0); + + /** + * Construct a time and pitch stretcher object with a custom debug + * logger. This may be useful for debugging if the default logger + * output (which simply goes to \c cerr) is not visible in the + * runtime environment, or if the application has a standard or + * more realtime-appropriate logging mechanism. + * + * See the documentation for the other constructor above for + * details of the arguments other than the logger. + * + * Note that although the supplied logger gets to decide what to + * do with log messages, the separately-set debug level (see + * setDebugLevel() and setDefaultDebugLevel()) still determines + * whether any given debug message is sent to the logger in the + * first place. + */ + RubberBandStretcher(size_t sampleRate, + size_t channels, + std::shared_ptr logger, + Options options = DefaultOptions, + double initialTimeRatio = 1.0, + double initialPitchScale = 1.0); + + ~RubberBandStretcher(); + + /** + * Reset the stretcher's internal buffers. The stretcher should + * subsequently behave as if it had just been constructed + * (although retaining the current time and pitch ratio). + */ + void reset(); + + /** + * Return the active internal engine version, according to the \c + * OptionEngine flag supplied on construction. This will return 2 + * for the R2 (Faster) engine or 3 for the R3 (Finer) engine. + * + * This function was added in Rubber Band Library v3.0. + */ + int getEngineVersion() const; + + /** + * Set the time ratio for the stretcher. This is the ratio of + * stretched to unstretched duration -- not tempo. For example, a + * ratio of 2.0 would make the audio twice as long (i.e. halve the + * tempo); 0.5 would make it half as long (i.e. double the tempo); + * 1.0 would leave the duration unaffected. + * + * If the stretcher was constructed in Offline mode, the time + * ratio is fixed throughout operation; this function may be + * called any number of times between construction (or a call to + * reset()) and the first call to study() or process(), but may + * not be called after study() or process() has been called. + * + * If the stretcher was constructed in RealTime mode, the time + * ratio may be varied during operation; this function may be + * called at any time, so long as it is not called concurrently + * with process(). You should either call this function from the + * same thread as process(), or provide your own mutex or similar + * mechanism to ensure that setTimeRatio and process() cannot be + * run at once (there is no internal mutex for this purpose). + */ + void setTimeRatio(double ratio); + + /** + * Set the pitch scaling ratio for the stretcher. This is the + * ratio of target frequency to source frequency. For example, a + * ratio of 2.0 would shift up by one octave; 0.5 down by one + * octave; or 1.0 leave the pitch unaffected. + * + * To put this in musical terms, a pitch scaling ratio + * corresponding to a shift of S equal-tempered semitones (where S + * is positive for an upwards shift and negative for downwards) is + * pow(2.0, S / 12.0). + * + * If the stretcher was constructed in Offline mode, the pitch + * scaling ratio is fixed throughout operation; this function may + * be called any number of times between construction (or a call + * to reset()) and the first call to study() or process(), but may + * not be called after study() or process() has been called. + * + * If the stretcher was constructed in RealTime mode, the pitch + * scaling ratio may be varied during operation; this function may + * be called at any time, so long as it is not called concurrently + * with process(). You should either call this function from the + * same thread as process(), or provide your own mutex or similar + * mechanism to ensure that setPitchScale and process() cannot be + * run at once (there is no internal mutex for this purpose). + */ + void setPitchScale(double scale); + + /** + * Set a pitch scale for the vocal formant envelope separately + * from the overall pitch scale. This is a ratio of target + * frequency to source frequency. For example, a ratio of 2.0 + * would shift the formant envelope up by one octave; 0.5 down by + * one octave; or 1.0 leave the formant unaffected. + * + * By default this is set to the special value of 0.0, which + * causes the scale to be calculated automatically. It will be + * treated as 1.0 / the pitch scale if OptionFormantPreserved is + * specified, or 1.0 for OptionFormantShifted. + * + * Conversely, if this is set to a value other than the default + * 0.0, formant shifting will happen regardless of the state of + * the OptionFormantPreserved/OptionFormantShifted option. + * + * This function is provided for special effects only. You do not + * need to call it for ordinary pitch shifting, with or without + * formant preservation - just specify or omit the + * OptionFormantPreserved option as appropriate. Use this function + * only if you want to shift formants by a distance other than + * that of the overall pitch shift. + * + * This function is supported only in the R3 (OptionEngineFiner) + * engine. It has no effect in R2 (OptionEngineFaster). + * + * This function was added in Rubber Band Library v3.0. + */ + void setFormantScale(double scale); + + /** + * Return the last time ratio value that was set (either on + * construction or with setTimeRatio()). + */ + double getTimeRatio() const; + + /** + * Return the last pitch scaling ratio value that was set (either + * on construction or with setPitchScale()). + */ + double getPitchScale() const; + + /** + * Return the last formant scaling ratio that was set with + * setFormantScale, or 0.0 if the default automatic scaling is in + * effect. + * + * This function is supported only in the R3 (OptionEngineFiner) + * engine. It always returns 0.0 in R2 (OptionEngineFaster). + * + * This function was added in Rubber Band Library v3.0. + */ + double getFormantScale() const; + + /** + * In RealTime mode (unlike in Offline mode) the stretcher + * performs no automatic padding or delay/latency compensation at + * the start of the signal. This permits applications to have + * their own custom requirements, but it also means that by + * default some samples will be lost or attenuated at the start of + * the output and the correct linear relationship between input + * and output sample counts may be lost. + * + * Most applications using RealTime mode should solve this by + * calling getPreferredStartPad() and supplying the returned + * number of (silent) samples at the start of their input, before + * their first "true" process() call; and then also calling + * getStartDelay() and trimming the returned number of samples + * from the start of their stretcher's output. + * + * Ensure you have set the time and pitch scale factors to their + * proper starting values before calling getRequiredStartPad() or + * getStartDelay(). + * + * In Offline mode, padding and delay compensation are handled + * internally and both functions always return zero. + * + * This function was added in Rubber Band Library v3.0. + * + * @see getStartDelay + */ + size_t getPreferredStartPad() const; + + /** + * Return the output delay of the stretcher. This is the number + * of audio samples that one should discard at the start of the + * output, after padding the start of the input with + * getPreferredStartPad(), in order to ensure that the resulting + * audio has the expected time alignment with the input. + * + * Ensure you have set the time and pitch scale factors to their + * proper starting values before calling getPreferredStartPad() or + * getStartDelay(). + * + * In Offline mode, padding and delay compensation are handled + * internally and both functions always return zero. + * + * This function was added in Rubber Band Library v3.0. Previously + * it was called getLatency(). It was renamed to avoid confusion + * with the number of samples needed at input to cause a block of + * processing to handle (returned by getSamplesRequired()) which + * is also sometimes referred to as latency. + * + * @see getPreferredStartPad + */ + size_t getStartDelay() const; + + /** + * Return the start delay of the stretcher. This is a deprecated + * alias for getStartDelay(). + * + * @deprecated + */ + size_t getLatency() const; + + /** + * Return the number of channels this stretcher was constructed + * with. + */ + size_t getChannelCount() const; + + /** + * Change an OptionTransients configuration setting. This may be + * called at any time in RealTime mode. It may not be called in + * Offline mode (for which the transients option is fixed on + * construction). This has no effect when using the R3 engine. + */ + void setTransientsOption(Options options); + + /** + * Change an OptionDetector configuration setting. This may be + * called at any time in RealTime mode. It may not be called in + * Offline mode (for which the detector option is fixed on + * construction). This has no effect when using the R3 engine. + */ + void setDetectorOption(Options options); + + /** + * Change an OptionPhase configuration setting. This may be + * called at any time in any mode. This has no effect when using + * the R3 engine. + * + * Note that if running multi-threaded in Offline mode, the change + * may not take effect immediately if processing is already under + * way when this function is called. + */ + void setPhaseOption(Options options); + + /** + * Change an OptionFormant configuration setting. This may be + * called at any time in any mode. + * + * Note that if running multi-threaded in Offline mode, the change + * may not take effect immediately if processing is already under + * way when this function is called. + */ + void setFormantOption(Options options); + + /** + * Change an OptionPitch configuration setting. This may be + * called at any time in RealTime mode. It may not be called in + * Offline mode (for which the pitch option is fixed on + * construction). This has no effect when using the R3 engine. + */ + void setPitchOption(Options options); + + /** + * Tell the stretcher exactly how many input sample frames it will + * receive. This is only useful in Offline mode, when it allows + * the stretcher to ensure that the number of output samples is + * exactly correct. In RealTime mode no such guarantee is + * possible and this value is ignored. + * + * Note that the value of "samples" refers to the number of audio + * sample frames, which may be multi-channel, not the number of + * individual samples. (For example, one second of stereo audio + * sampled at 44100Hz yields a value of 44100 sample frames, not + * 88200.) This rule applies throughout the Rubber Band API. + */ + void setExpectedInputDuration(size_t samples); + + /** + * Tell the stretcher the maximum number of sample frames that you + * will ever be passing in to a single process() call. If you + * don't call this, the stretcher will assume that you are calling + * getSamplesRequired() at each cycle and are never passing more + * samples than are suggested by that function. + * + * If your application has some external constraint that means you + * prefer a fixed block size, then your normal mode of operation + * would be to provide that block size to this function; to loop + * calling process() with that size of block; after each call to + * process(), test whether output has been generated by calling + * available(); and, if so, call retrieve() to obtain it. See + * getSamplesRequired() for a more suitable operating mode for + * applications without such external constraints. + * + * This function may not be called after the first call to study() + * or process(). + * + * Note that this value is only relevant to process(), not to + * study() (to which you may pass any number of samples at a time, + * and from which there is no output). + * + * Despite the existence of this call and its use of a size_t + * argument, there is an internal limit to the maximum process + * buffer size that can be requested. Call getProcessSizeLimit() + * to query that limit. The Rubber Band API is essentially + * block-based and is not designed to process an entire signal + * within a single process cycle. + * + * Note that the value of "samples" refers to the number of audio + * sample frames, which may be multi-channel, not the number of + * individual samples. (For example, one second of stereo audio + * sampled at 44100Hz yields a value of 44100 sample frames, not + * 88200.) This rule applies throughout the Rubber Band API. + */ + void setMaxProcessSize(size_t samples); + + /** + * Obtain the overall maximum supported process buffer size in + * sample frames, which is also the maximum acceptable value to + * pass to setMaxProcessSize(). This value is fixed across + * instances and configurations. As of Rubber Band v3.3 it is + * always 524288 (or 2^19), but in principle it may change in + * future releases. + * + * This function was added in Rubber Band Library v3.3. + */ + size_t getProcessSizeLimit() const; + + /** + * Ask the stretcher how many audio sample frames should be + * provided as input in order to ensure that some more output + * becomes available. + * + * If your application has no particular constraint on processing + * block size and you are able to provide any block size as input + * for each cycle, then your normal mode of operation would be to + * loop querying this function; providing that number of samples + * to process(); and reading the output (repeatedly if necessary) + * using available() and retrieve(). See setMaxProcessSize() for + * a more suitable operating mode for applications that do have + * external block size constraints. + * + * Note that this value is only relevant to process(), not to + * study() (to which you may pass any number of samples at a time, + * and from which there is no output). + * + * Note that the return value refers to the number of audio sample + * frames, which may be multi-channel, not the number of + * individual samples. (For example, one second of stereo audio + * sampled at 44100Hz yields a value of 44100 sample frames, not + * 88200.) This rule applies throughout the Rubber Band API. + * + * @see getStartDelay + */ + size_t getSamplesRequired() const; + + /** + * Provide a set of mappings from "before" to "after" sample + * numbers so as to enforce a particular stretch profile. The + * argument is a map from audio sample frame number in the source + * material, to the corresponding sample frame number in the + * stretched output. The mapping should be for key frames only, + * with a "reasonable" gap between mapped samples. + * + * This function cannot be used in RealTime mode. + * + * This function may not be called after the first call to + * process(). It should be called after the time and pitch ratios + * have been set; the results of changing the time and pitch + * ratios after calling this function are undefined. Calling + * reset() will clear this mapping. + * + * The key frame map only affects points within the material; it + * does not determine the overall stretch ratio (that is, the + * ratio between the output material's duration and the source + * material's duration). You need to provide this ratio + * separately to setTimeRatio(), otherwise the results may be + * truncated or extended in unexpected ways regardless of the + * extent of the frame numbers found in the key frame map. + */ + void setKeyFrameMap(const std::map &); + + /** + * Provide a block of "samples" sample frames for the stretcher to + * study and calculate a stretch profile from. + * + * This is only meaningful in Offline mode, and is required if + * running in that mode. You should pass the entire input through + * study() before any process() calls are made, as a sequence of + * blocks in individual study() calls, or as a single large block. + * + * "input" should point to de-interleaved audio data with one + * float array per channel. Sample values are conventionally + * expected to be in the range -1.0f to +1.0f. "samples" supplies + * the number of audio sample frames available in "input". If + * "samples" is zero, "input" may be NULL. + * + * Note that the value of "samples" refers to the number of audio + * sample frames, which may be multi-channel, not the number of + * individual samples. (For example, one second of stereo audio + * sampled at 44100Hz yields a value of 44100 sample frames, not + * 88200.) This rule applies throughout the Rubber Band API. + * + * Set "final" to true if this is the last block of data that will + * be provided to study() before the first process() call. + */ + void study(const float *const *input, size_t samples, bool final); + + /** + * Provide a block of "samples" sample frames for processing. + * See also getSamplesRequired() and setMaxProcessSize(). + * + * "input" should point to de-interleaved audio data with one + * float array per channel. Sample values are conventionally + * expected to be in the range -1.0f to +1.0f. "samples" supplies + * the number of audio sample frames available in "input". + * + * Note that the value of "samples" refers to the number of audio + * sample frames, which may be multi-channel, not the number of + * individual samples. (For example, one second of stereo audio + * sampled at 44100Hz yields a value of 44100 sample frames, not + * 88200.) This rule applies throughout the Rubber Band API. + * + * Set "final" to true if this is the last block of input data. + */ + void process(const float *const *input, size_t samples, bool final); + + /** + * Ask the stretcher how many audio sample frames of output data + * are available for reading (via retrieve()). + * + * This function returns 0 if no frames are available: this + * usually means more input data needs to be provided, but if the + * stretcher is running in threaded mode it may just mean that not + * enough data has yet been processed. Call getSamplesRequired() + * to discover whether more input is needed. + * + * Note that the return value refers to the number of audio sample + * frames, which may be multi-channel, not the number of + * individual samples. (For example, one second of stereo audio + * sampled at 44100Hz yields a value of 44100 sample frames, not + * 88200.) This rule applies throughout the Rubber Band API. + * + * This function returns -1 if all data has been fully processed + * and all output read, and the stretch process is now finished. + */ + int available() const; + + /** + * Obtain some processed output data from the stretcher. Up to + * "samples" samples will be stored in each of the output arrays + * (one per channel for de-interleaved audio data) pointed to by + * "output". The number of sample frames available to be + * retrieved can be queried beforehand with a call to available(). + * The return value is the actual number of sample frames + * retrieved. + * + * Note that the value of "samples" and the return value refer to + * the number of audio sample frames, which may be multi-channel, + * not the number of individual samples. (For example, one second + * of stereo audio sampled at 44100Hz yields a value of 44100 + * sample frames, not 88200.) This rule applies throughout the + * Rubber Band API. + */ + size_t retrieve(float *const *output, size_t samples) const; + + /** + * Return the value of internal frequency cutoff value n. + * + * This function is not for general use and is supported only with + * the R2 engine. + */ + float getFrequencyCutoff(int n) const; + + /** + * Set the value of internal frequency cutoff n to f Hz. + * + * This function is not for general use and is supported only with + * the R2 engine. + */ + void setFrequencyCutoff(int n, float f); + + /** + * Retrieve the value of the internal input block increment value. + * + * This function is provided for diagnostic purposes only and is + * supported only with the R2 engine. + */ + size_t getInputIncrement() const; + + /** + * In offline mode, retrieve the sequence of internal block + * increments for output, for the entire audio data, provided the + * stretch profile has been calculated. In realtime mode, + * retrieve any output increments that have accumulated since the + * last call to getOutputIncrements, to a limit of 16. + * + * This function is provided for diagnostic purposes only and is + * supported only with the R2 engine. + */ + std::vector getOutputIncrements() const; + + /** + * In offline mode, retrieve the sequence of internal phase reset + * detection function values, for the entire audio data, provided + * the stretch profile has been calculated. In realtime mode, + * retrieve any phase reset points that have accumulated since the + * last call to getPhaseResetCurve, to a limit of 16. + * + * This function is provided for diagnostic purposes only and is + * supported only with the R2 engine. + */ + std::vector getPhaseResetCurve() const; + + /** + * In offline mode, retrieve the sequence of internal frames for + * which exact timing has been sought, for the entire audio data, + * provided the stretch profile has been calculated. In realtime + * mode, return an empty sequence. + * + * This function is provided for diagnostic purposes only and is + * supported only with the R2 engine. + */ + std::vector getExactTimePoints() const; + + /** + * Force the stretcher to calculate a stretch profile. Normally + * this happens automatically for the first process() call in + * offline mode. + * + * This function is provided for diagnostic purposes only and is + * supported only with the R2 engine. + */ + void calculateStretch(); + + /** + * Set the level of debug output. The supported values are: + * + * 0. Report errors only. + * + * 1. Report some information on construction and ratio + * change. Nothing is reported during normal processing unless + * something changes. + * + * 2. Report a significant amount of information about ongoing + * stretch calculations during normal processing. + * + * 3. Report a large amount of information and also (in the R2 + * engine) add audible ticks to the output at phase reset + * points. This is seldom useful. + * + * The default is whatever has been set using + * setDefaultDebugLevel(), or 0 if that function has not been + * called. + * + * All output goes to \c cerr unless a custom + * RubberBandStretcher::Logger has been provided on + * construction. Because writing to \c cerr is not RT-safe, only + * debug level 0 is RT-safe in normal use by default. Debug levels + * 0 and 1 use only C-string constants as debug messages, so they + * are RT-safe if your custom logger is RT-safe. Levels 2 and 3 + * are not guaranteed to be RT-safe in any conditions as they may + * construct messages by allocation. + * + * @see Logger + * @see setDefaultDebugLevel + */ + void setDebugLevel(int level); + + /** + * Set the default level of debug output for subsequently + * constructed stretchers. + * + * @see setDebugLevel + */ + static void setDefaultDebugLevel(int level); + +protected: + class Impl; + Impl *m_d; + + RubberBandStretcher(const RubberBandStretcher &) =delete; + RubberBandStretcher &operator=(const RubberBandStretcher &) =delete; +}; + +} + +#endif diff --git a/ThirdParty/rubberband/include/rubberband/rubberband-c.h b/ThirdParty/rubberband/include/rubberband/rubberband-c.h new file mode 100644 index 000000000..ec4638da9 --- /dev/null +++ b/ThirdParty/rubberband/include/rubberband/rubberband-c.h @@ -0,0 +1,216 @@ + +/* -*- c-basic-offset: 4 indent-tabs-mode: nil -*- vi:set ts=8 sts=4 sw=4: */ + +/* + Rubber Band Library + An audio time-stretching and pitch-shifting library. + Copyright 2007-2024 Particular Programs Ltd. + + This program is free software; you can redistribute it and/or + modify it under the terms of the GNU General Public License as + published by the Free Software Foundation; either version 2 of the + License, or (at your option) any later version. See the file + COPYING included with this distribution for more information. + + Alternatively, if you have a valid commercial licence for the + Rubber Band Library obtained by agreement with the copyright + holders, you may redistribute and/or modify it under the terms + described in that licence. + + If you wish to distribute code using the Rubber Band Library + under terms other than those of the GNU General Public License, + you must obtain a valid commercial licence before doing so. +*/ + +#ifndef RUBBERBAND_C_API_H +#define RUBBERBAND_C_API_H + +#ifdef __cplusplus +extern "C" { +#endif + +#define RUBBERBAND_VERSION "4.0.0" +#define RUBBERBAND_API_MAJOR_VERSION 3 +#define RUBBERBAND_API_MINOR_VERSION 0 + +#undef RB_EXTERN +#ifdef _MSC_VER +#ifndef RUBBERBAND_STATIC +#define RB_EXTERN extern __declspec(dllexport) +#else +#define RB_EXTERN extern +#endif +#else +#define RB_EXTERN extern +#endif + +/** + * This is a C-linkage interface to the Rubber Band time stretcher. + * + * This is a wrapper interface: the primary interface is in C++ and is + * defined and documented in RubberBandStretcher.h and + * RubberBandLiveShifter.h. The library itself is implemented in C++, + * and requires C++ standard library support even when using the + * C-linkage API. + * + * Please see RubberBandStretcher.h and RubberBandLiveShifter.h for + * documentation. + * + * If you are writing to the C++ API, do not include this header. + */ + +enum RubberBandOption { + + RubberBandOptionProcessOffline = 0x00000000, + RubberBandOptionProcessRealTime = 0x00000001, + + RubberBandOptionStretchElastic = 0x00000000, // obsolete + RubberBandOptionStretchPrecise = 0x00000010, // obsolete + + RubberBandOptionTransientsCrisp = 0x00000000, + RubberBandOptionTransientsMixed = 0x00000100, + RubberBandOptionTransientsSmooth = 0x00000200, + + RubberBandOptionDetectorCompound = 0x00000000, + RubberBandOptionDetectorPercussive = 0x00000400, + RubberBandOptionDetectorSoft = 0x00000800, + + RubberBandOptionPhaseLaminar = 0x00000000, + RubberBandOptionPhaseIndependent = 0x00002000, + + RubberBandOptionThreadingAuto = 0x00000000, + RubberBandOptionThreadingNever = 0x00010000, + RubberBandOptionThreadingAlways = 0x00020000, + + RubberBandOptionWindowStandard = 0x00000000, + RubberBandOptionWindowShort = 0x00100000, + RubberBandOptionWindowLong = 0x00200000, + + RubberBandOptionSmoothingOff = 0x00000000, + RubberBandOptionSmoothingOn = 0x00800000, + + RubberBandOptionFormantShifted = 0x00000000, + RubberBandOptionFormantPreserved = 0x01000000, + + RubberBandOptionPitchHighSpeed = 0x00000000, + RubberBandOptionPitchHighQuality = 0x02000000, + RubberBandOptionPitchHighConsistency = 0x04000000, + + RubberBandOptionChannelsApart = 0x00000000, + RubberBandOptionChannelsTogether = 0x10000000, + + RubberBandOptionEngineFaster = 0x00000000, + RubberBandOptionEngineFiner = 0x20000000 +}; + +typedef int RubberBandOptions; + +struct RubberBandState_; +typedef struct RubberBandState_ *RubberBandState; + +RB_EXTERN RubberBandState rubberband_new(unsigned int sampleRate, + unsigned int channels, + RubberBandOptions options, + double initialTimeRatio, + double initialPitchScale); + +RB_EXTERN void rubberband_delete(RubberBandState); + +RB_EXTERN void rubberband_reset(RubberBandState); + +RB_EXTERN int rubberband_get_engine_version(RubberBandState); + +RB_EXTERN void rubberband_set_time_ratio(RubberBandState, double ratio); +RB_EXTERN void rubberband_set_pitch_scale(RubberBandState, double scale); + +RB_EXTERN double rubberband_get_time_ratio(const RubberBandState); +RB_EXTERN double rubberband_get_pitch_scale(const RubberBandState); + +RB_EXTERN void rubberband_set_formant_scale(RubberBandState, double scale); +RB_EXTERN double rubberband_get_formant_scale(const RubberBandState); + +RB_EXTERN unsigned int rubberband_get_preferred_start_pad(const RubberBandState); +RB_EXTERN unsigned int rubberband_get_start_delay(const RubberBandState); +RB_EXTERN unsigned int rubberband_get_latency(const RubberBandState); + +RB_EXTERN void rubberband_set_transients_option(RubberBandState, RubberBandOptions options); +RB_EXTERN void rubberband_set_detector_option(RubberBandState, RubberBandOptions options); +RB_EXTERN void rubberband_set_phase_option(RubberBandState, RubberBandOptions options); +RB_EXTERN void rubberband_set_formant_option(RubberBandState, RubberBandOptions options); +RB_EXTERN void rubberband_set_pitch_option(RubberBandState, RubberBandOptions options); + +RB_EXTERN void rubberband_set_expected_input_duration(RubberBandState, unsigned int samples); + +RB_EXTERN unsigned int rubberband_get_samples_required(const RubberBandState); + +RB_EXTERN void rubberband_set_max_process_size(RubberBandState, unsigned int samples); +RB_EXTERN unsigned int rubberband_get_process_size_limit(RubberBandState); + +RB_EXTERN void rubberband_set_key_frame_map(RubberBandState, unsigned int keyframecount, unsigned int *from, unsigned int *to); + +RB_EXTERN void rubberband_study(RubberBandState, const float *const *input, unsigned int samples, int final); +RB_EXTERN void rubberband_process(RubberBandState, const float *const *input, unsigned int samples, int final); + +RB_EXTERN int rubberband_available(const RubberBandState); +RB_EXTERN unsigned int rubberband_retrieve(const RubberBandState, float *const *output, unsigned int samples); + +RB_EXTERN unsigned int rubberband_get_channel_count(const RubberBandState); + +RB_EXTERN void rubberband_calculate_stretch(RubberBandState); + +RB_EXTERN void rubberband_set_debug_level(RubberBandState, int level); +RB_EXTERN void rubberband_set_default_debug_level(int level); + + +enum RubberBandLiveOption { + + RubberBandLiveOptionWindowShort = 0x00000000, + RubberBandLiveOptionWindowMedium = 0x00100000, + + RubberBandLiveOptionFormantShifted = 0x00000000, + RubberBandLiveOptionFormantPreserved = 0x01000000, + + RubberBandLiveOptionChannelsApart = 0x00000000, + RubberBandLiveOptionChannelsTogether = 0x10000000 +}; + +typedef int RubberBandLiveOptions; + +struct RubberBandLiveState_; +typedef struct RubberBandLiveState_ *RubberBandLiveState; + +RB_EXTERN RubberBandLiveState rubberband_live_new(unsigned int sampleRate, + unsigned int channels, + RubberBandOptions options); + +RB_EXTERN void rubberband_live_delete(RubberBandLiveState); + +RB_EXTERN void rubberband_live_reset(RubberBandLiveState); + +RB_EXTERN void rubberband_live_set_pitch_scale(RubberBandLiveState, double scale); +RB_EXTERN double rubberband_live_get_pitch_scale(const RubberBandLiveState); + +RB_EXTERN void rubberband_live_set_formant_scale(RubberBandLiveState, double scale); +RB_EXTERN double rubberband_live_get_formant_scale(const RubberBandLiveState); + +RB_EXTERN unsigned int rubberband_live_get_start_delay(const RubberBandLiveState); + +RB_EXTERN void rubberband_live_set_formant_option(RubberBandLiveState, RubberBandOptions options); + +RB_EXTERN unsigned int rubberband_live_get_block_size(RubberBandLiveState); + +RB_EXTERN void rubberband_live_shift(RubberBandLiveState, const float *const *input, float *const *output); + +RB_EXTERN unsigned int rubberband_live_get_channel_count(const RubberBandLiveState); + +RB_EXTERN void rubberband_live_set_debug_level(RubberBandLiveState, int level); +RB_EXTERN void rubberband_live_set_default_debug_level(int level); + + +#ifdef __cplusplus +} +#endif + +#undef RB_EXTERN + +#endif diff --git a/SpectrumViewCG.h b/Visualization/SpectrumViewCG.h similarity index 100% rename from SpectrumViewCG.h rename to Visualization/SpectrumViewCG.h diff --git a/SpectrumViewCG.m b/Visualization/SpectrumViewCG.m similarity index 100% rename from SpectrumViewCG.m rename to Visualization/SpectrumViewCG.m diff --git a/SpectrumWindowController.h b/Visualization/SpectrumWindowController.h similarity index 100% rename from SpectrumWindowController.h rename to Visualization/SpectrumWindowController.h diff --git a/SpectrumWindowController.m b/Visualization/SpectrumWindowController.m similarity index 100% rename from SpectrumWindowController.m rename to Visualization/SpectrumWindowController.m diff --git a/SpeedSlider.h b/Window/PitchSlider.h similarity index 76% rename from SpeedSlider.h rename to Window/PitchSlider.h index 3ea26df59..a1351af67 100644 --- a/SpeedSlider.h +++ b/Window/PitchSlider.h @@ -1,16 +1,19 @@ // -// SpeedSlider.h +// PitchSlider.h // Cog // // Created by Christopher Snowhill on 9/20/24. // Copyright 2024 __LoSnoCo__. All rights reserved. // +#import "TempoSlider.h" + #import -@interface SpeedSlider : NSSlider { +@interface PitchSlider : NSSlider { NSPopover *popover; NSText *textView; + IBOutlet NSSlider *_TempoSlider; } - (void)showToolTip; diff --git a/SpeedSlider.m b/Window/PitchSlider.m similarity index 71% rename from SpeedSlider.m rename to Window/PitchSlider.m index 4dd7dc19c..86df5e21d 100644 --- a/SpeedSlider.m +++ b/Window/PitchSlider.m @@ -1,18 +1,18 @@ // -// SpeedSlider.m +// PitchSlider.m // Cog // // Created by Christopher Snowhill on 9/20/24. // Copyright 2024 __LoSnoCo__. All rights reserved. // -#import "SpeedSlider.h" +#import "PitchSlider.h" #import "CogAudio/Helper.h" #import "PlaybackController.h" -static void *kSpeedSliderContext = &kSpeedSliderContext; +static void *kPitchSliderContext = &kPitchSliderContext; -@implementation SpeedSlider { +@implementation PitchSlider { NSTimer *currentTimer; BOOL wasInsideSnapRange; /*BOOL observersadded;*/ @@ -55,22 +55,24 @@ static void *kSpeedSliderContext = &kSpeedSliderContext; }*/ - (void)updateToolTip { - const double value = [self doubleValue]; + const double value = ([self doubleValue] - [self minValue]) * 100.0 / ([self maxValue] - [self minValue]); NSString *text; - - double speed; - if(value < 0.2) { - speed = 0.2; - } else if(value > 5.0) { - speed = 5.0; + + const double adjustedValue = ((value * value) * (5.0 - 0.2) / 10000.0) + 0.2; + + double pitch; + if(adjustedValue < 0.2) { + pitch = 0.2; + } else if(adjustedValue > 5.0) { + pitch = 5.0; } else { - speed = value; + pitch = adjustedValue; } - if(speed < 1) - text = [NSString stringWithFormat:@"%0.2lf×", speed]; + if(pitch < 1) + text = [NSString stringWithFormat:@"%0.2lf×", pitch]; else - text = [NSString stringWithFormat:@"%0.1lf×", speed]; + text = [NSString stringWithFormat:@"%0.1lf×", pitch]; [textView setString:text]; } @@ -128,7 +130,7 @@ static void *kSpeedSliderContext = &kSpeedSliderContext; } /*- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context { - if(context != kSpeedSliderContext) { + if(context != kPitchSliderContext) { [super observeValueForKeyPath:keyPath ofObject:object change:change context:context]; return; } @@ -137,10 +139,21 @@ static void *kSpeedSliderContext = &kSpeedSliderContext; - (BOOL)sendAction:(SEL)theAction to:(id)theTarget { // Snap to 1.0× if value is close double snapTarget = 1.0; - double snapProgress = ([self doubleValue] - snapTarget) / (self.maxValue - self.minValue); + const double value = ([self doubleValue] - [self minValue]) * 100.0 / ([self maxValue] - [self minValue]); + const double adjustedValue = ((value * value) * (5.0 - 0.2) / 10000.0) + 0.2; + double snapProgress = (adjustedValue - snapTarget); - if(fabs(snapProgress) < 0.005) { - [self setDoubleValue:snapTarget]; + BOOL speedLock = [[NSUserDefaults standardUserDefaults] boolForKey:@"speedLock"]; + if(speedLock) { + [_TempoSlider setDoubleValue:[self doubleValue]]; + } + + if(fabs(snapProgress) < 0.01) { + const double inverseValue = sqrtf((snapTarget - 0.2) * 10000.0 / (5.0 - 0.2)); + [self setDoubleValue:inverseValue]; + if(speedLock) { + [_TempoSlider setDoubleValue:inverseValue]; + } if(!wasInsideSnapRange) { [[NSHapticFeedbackManager defaultPerformer] performFeedbackPattern:NSHapticFeedbackPatternGeneric performanceTime:NSHapticFeedbackPerformanceTimeDefault]; } @@ -149,7 +162,7 @@ static void *kSpeedSliderContext = &kSpeedSliderContext; wasInsideSnapRange = NO; } - [self showToolTip]; + [self showToolTipForDuration:1.0]; return [super sendAction:theAction to:theTarget]; } @@ -159,7 +172,14 @@ static void *kSpeedSliderContext = &kSpeedSliderContext; [self setDoubleValue:[self doubleValue] + change]; - [[self target] changeSpeed:self]; + [[self target] changePitch:self]; + + BOOL speedLock = [[NSUserDefaults standardUserDefaults] boolForKey:@"speedLock"]; + if(speedLock) { + [_TempoSlider setDoubleValue:[self doubleValue]]; + + [[self target] changeTempo:self]; + } [self showToolTipForDuration:1.0]; } diff --git a/Window/SpeedButton.h b/Window/SpeedButton.h index aa607cd54..5db371b39 100644 --- a/Window/SpeedButton.h +++ b/Window/SpeedButton.h @@ -1,16 +1,24 @@ // -// VolumeButton.h +// SpeedButton.h // Cog // -// Created by Vincent Spader on 2/8/09. -// Copyright 2009 __MyCompanyName__. All rights reserved. +// Created by Christopher Snowhill on 9/20/24. +// Copyright 2024 __LoSnoCo__. All rights reserved. // -#import "VolumeSlider.h" +#import "PitchSlider.h" +#import "TempoSlider.h" #import -@interface VolumeButton : NSButton { - IBOutlet VolumeSlider *_popView; +@interface SpeedButton : NSButton { + IBOutlet NSView *_popView; + IBOutlet PitchSlider *_PitchSlider; + IBOutlet TempoSlider *_TempoSlider; + IBOutlet NSButton *_LockButton; + IBOutlet NSButton *_ResetButton; } +- (IBAction)pressLock:(id)sender; +- (IBAction)pressReset:(id)sender; + @end diff --git a/Window/SpeedButton.m b/Window/SpeedButton.m index 8224d4386..d4beac489 100644 --- a/Window/SpeedButton.m +++ b/Window/SpeedButton.m @@ -1,15 +1,20 @@ // -// VolumeButton.m +// SpeedButton.m // Cog // -// Created by Vincent Spader on 2/8/09. -// Copyright 2009 __MyCompanyName__. All rights reserved. +// Created by Christopher Snowhill on 9/20/24. +// Copyright 2024 __LoSnoCo__. All rights reserved. // -#import "VolumeButton.h" +#import "SpeedButton.h" #import "PlaybackController.h" -@implementation VolumeButton { +static double reverseSpeedScale(double input, double min, double max) { + input = sqrtf((input - 0.2) * 10000.0 / (5.0 - 0.2)); + return (input * (max - min) / 100.0) + min; +} + +@implementation SpeedButton { NSPopover *popover; NSViewController *viewController; } @@ -20,21 +25,6 @@ [popover setContentSize:_popView.bounds.size]; } -- (void)scrollWheel:(NSEvent *)theEvent { - if([popover isShown]) { - [_popView scrollWheel:theEvent]; - return; - } - - double change = [theEvent deltaY]; - - [_popView setDoubleValue:[_popView doubleValue] + change]; - - [[_popView target] changeVolume:_popView]; - - [_popView showToolTipForView:self closeAfter:1.0]; -} - - (void)mouseDown:(NSEvent *)theEvent { [popover close]; @@ -48,4 +38,30 @@ [super mouseDown:theEvent]; } +- (IBAction)pressLock:(id)sender { + BOOL speedLock = [[NSUserDefaults standardUserDefaults] boolForKey:@"speedLock"]; + speedLock = !speedLock; + [_LockButton setTitle:speedLock ? @"🔒" : @"🔓"]; + [[NSUserDefaults standardUserDefaults] setBool:speedLock forKey:@"speedLock"]; + + if(speedLock) { + const double pitchValue = ([_PitchSlider doubleValue] - [_PitchSlider minValue]) / ([_PitchSlider maxValue] - [_PitchSlider minValue]); + const double tempoValue = ([_TempoSlider doubleValue] - [_TempoSlider minValue]) / ([_TempoSlider maxValue] - [_TempoSlider minValue]); + const double averageValue = (pitchValue + tempoValue) * 0.5; + [_PitchSlider setDoubleValue:(averageValue * ([_PitchSlider maxValue] - [_PitchSlider minValue])) + [_PitchSlider minValue]]; + [_TempoSlider setDoubleValue:(averageValue * ([_TempoSlider maxValue] - [_TempoSlider minValue])) + [_TempoSlider minValue]]; + + [[_PitchSlider target] changePitch:_PitchSlider]; + [[_TempoSlider target] changeTempo:_TempoSlider]; + } +} + +- (IBAction)pressReset:(id)sender { + [_PitchSlider setDoubleValue:reverseSpeedScale(1.0, [_PitchSlider minValue], [_PitchSlider maxValue])]; + [_TempoSlider setDoubleValue:reverseSpeedScale(1.0, [_TempoSlider minValue], [_TempoSlider maxValue])]; + + [[_PitchSlider target] changePitch:_PitchSlider]; + [[_TempoSlider target] changeTempo:_TempoSlider]; +} + @end diff --git a/Window/SpeedSlider.h b/Window/TempoSlider.h similarity index 55% rename from Window/SpeedSlider.h rename to Window/TempoSlider.h index 56b959ba0..fbf845941 100644 --- a/Window/SpeedSlider.h +++ b/Window/TempoSlider.h @@ -1,17 +1,19 @@ // -// VolumeSlider.h +// TempoSlider.h // Cog // -// Created by Vincent Spader on 2/8/09. -// Copyright 2009 __MyCompanyName__. All rights reserved. +// Created by Christopher Snowhill on 9/20/24. +// Copyright 2024 __LoSnoCo__. All rights reserved. // +#import "TempoSlider.h" + #import -@interface VolumeSlider : NSSlider { +@interface TempoSlider : NSSlider { NSPopover *popover; NSText *textView; - double MAX_VOLUME; + IBOutlet NSSlider *_PitchSlider; } - (void)showToolTip; diff --git a/Window/SpeedSlider.m b/Window/TempoSlider.m similarity index 59% rename from Window/SpeedSlider.m rename to Window/TempoSlider.m index ccaedf7f3..89360555e 100644 --- a/Window/SpeedSlider.m +++ b/Window/TempoSlider.m @@ -1,21 +1,21 @@ // -// VolumeSlider.m +// TempoSlider.m // Cog // -// Created by Vincent Spader on 2/8/09. -// Copyright 2009 __MyCompanyName__. All rights reserved. +// Created by Christopher Snowhill on 9/20/24. +// Copyright 2024 __LoSnoCo__. All rights reserved. // -#import "VolumeSlider.h" +#import "TempoSlider.h" #import "CogAudio/Helper.h" #import "PlaybackController.h" -static void *kVolumeSliderContext = &kVolumeSliderContext; +static void *kTempoSliderContext = &kTempoSliderContext; -@implementation VolumeSlider { +@implementation TempoSlider { NSTimer *currentTimer; BOOL wasInsideSnapRange; - BOOL observersadded; + /*BOOL observersadded;*/ } - (id)initWithFrame:(NSRect)frame { @@ -29,9 +29,6 @@ static void *kVolumeSliderContext = &kVolumeSliderContext; } - (void)awakeFromNib { - BOOL volumeLimit = [[[NSUserDefaultsController sharedUserDefaultsController] defaults] boolForKey:@"volumeLimit"]; - MAX_VOLUME = (volumeLimit) ? 100.0 : 800.0; - wasInsideSnapRange = NO; textView = [[NSText alloc] init]; [textView setFrame:NSMakeRect(0, 0, 50, 20)]; @@ -49,31 +46,33 @@ static void *kVolumeSliderContext = &kVolumeSliderContext; popover.animates = NO; [popover setContentSize:textView.bounds.size]; - [[NSUserDefaultsController sharedUserDefaultsController] addObserver:self forKeyPath:@"values.volumeLimit" options:0 context:kVolumeSliderContext]; - observersadded = YES; + /*observersadded = YES;*/ } -- (void)dealloc { +/*- (void)dealloc { if(observersadded) { - [[NSUserDefaultsController sharedUserDefaultsController] removeObserver:self forKeyPath:@"values.volumeLimit" context:kVolumeSliderContext]; } -} +}*/ - (void)updateToolTip { - const double value = [self doubleValue]; - // Sets volume to be the slider value if limit is set to 100% or the actual volume otherwise. - const double volume = (MAX_VOLUME == 100) ? value : linearToLogarithmic(value, MAX_VOLUME); + const double value = ([self doubleValue] - [self minValue]) * 100.0 / ([self maxValue] - [self minValue]); NSString *text; + + const double adjustedValue = ((value * value) * (5.0 - 0.2) / 10000.0) + 0.2; + + double tempo; + if(adjustedValue < 0.2) { + tempo = 0.2; + } else if(adjustedValue > 5.0) { + tempo = 5.0; + } else { + tempo = adjustedValue; + } - // If volume becomes less than 1%, display two decimal digits of precision (e.g. 0.34%). - if(volume < 1) - text = [NSString stringWithFormat:@"%0.2lf%%", volume]; - // Else if volume becomes less than 10%, display one decimal digit of precision (e.g. 3.4%). - else if(volume < 10) - text = [NSString stringWithFormat:@"%0.1lf%%", volume]; - // Else display no decimal digits. + if(tempo < 1) + text = [NSString stringWithFormat:@"%0.2lf×", tempo]; else - text = [NSString stringWithFormat:@"%0.lf%%", volume]; + text = [NSString stringWithFormat:@"%0.1lf×", tempo]; [textView setString:text]; } @@ -130,31 +129,31 @@ static void *kVolumeSliderContext = &kVolumeSliderContext; } } -- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context { - if(context != kVolumeSliderContext) { +/*- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context { + if(context != kTempoSliderContext) { [super observeValueForKeyPath:keyPath ofObject:object change:change context:context]; return; } - - if([keyPath isEqualToString:@"values.volumeLimit"]) { - BOOL volumeLimit = [[[NSUserDefaultsController sharedUserDefaultsController] defaults] boolForKey:@"volumeLimit"]; - const double new_MAX_VOLUME = (volumeLimit) ? 100.0 : 800.0; - - if(MAX_VOLUME != new_MAX_VOLUME) { - double currentLevel = linearToLogarithmic([self doubleValue], MAX_VOLUME); - [self setDoubleValue:logarithmicToLinear(currentLevel, new_MAX_VOLUME)]; - } - MAX_VOLUME = new_MAX_VOLUME; - } -} +}*/ - (BOOL)sendAction:(SEL)theAction to:(id)theTarget { - // Snap to 100% if value is close - double snapTarget = logarithmicToLinear(100.0, MAX_VOLUME); - double snapProgress = ([self doubleValue] - snapTarget) / (self.maxValue - self.minValue); + // Snap to 1.0× if value is close + double snapTarget = 1.0; + const double value = ([self doubleValue] - [self minValue]) * 100.0 / ([self maxValue] - [self minValue]); + const double adjustedValue = ((value * value) * (5.0 - 0.2) / 10000.0) + 0.2; + double snapProgress = (adjustedValue - snapTarget); - if(fabs(snapProgress) < 0.005) { - [self setDoubleValue:snapTarget]; + BOOL speedLock = [[NSUserDefaults standardUserDefaults] boolForKey:@"speedLock"]; + if(speedLock) { + [_PitchSlider setDoubleValue:[self doubleValue]]; + } + + if(fabs(snapProgress) < 0.01) { + const double inverseValue = sqrtf((snapTarget - 0.2) * 10000.0 / (5.0 - 0.2)); + [self setDoubleValue:inverseValue]; + if(speedLock) { + [_PitchSlider setDoubleValue:inverseValue]; + } if(!wasInsideSnapRange) { [[NSHapticFeedbackManager defaultPerformer] performFeedbackPattern:NSHapticFeedbackPatternGeneric performanceTime:NSHapticFeedbackPerformanceTimeDefault]; } @@ -163,7 +162,7 @@ static void *kVolumeSliderContext = &kVolumeSliderContext; wasInsideSnapRange = NO; } - [self showToolTip]; + [self showToolTipForDuration:1.0]; return [super sendAction:theAction to:theTarget]; } @@ -173,7 +172,14 @@ static void *kVolumeSliderContext = &kVolumeSliderContext; [self setDoubleValue:[self doubleValue] + change]; - [[self target] changeVolume:self]; + [[self target] changeTempo:self]; + + BOOL speedLock = [[NSUserDefaults standardUserDefaults] boolForKey:@"speedLock"]; + if(speedLock) { + [_PitchSlider setDoubleValue:[self doubleValue]]; + + [[self target] changePitch:self]; + } [self showToolTipForDuration:1.0]; } diff --git a/en.lproj/Credits.html b/en.lproj/Credits.html index 1162483e6..573672bd1 100644 --- a/en.lproj/Credits.html +++ b/en.lproj/Credits.html @@ -35,6 +35,7 @@

This program has been made possible through contributions from users like you.

All Cog code is copyrighted by me, and is licensed under the GPL. Cog contains bits of other code from third parties that are under their own licenses. +

Rubber Band Library was used under the GPL to provide pitch and/or time shifting. diff --git a/es.lproj/Credits.html b/es.lproj/Credits.html index 65dbb67a0..d4e4eef14 100644 --- a/es.lproj/Credits.html +++ b/es.lproj/Credits.html @@ -36,6 +36,7 @@

Este programa ha sido posible gracias a las contribuciones de usuarios y usuarias como tú.

Todo el código de Cog es de mi propiedad, y está licenciado bajo la GPL. Cog contiene código de terceros que están bajo sus propias licencias. +

La biblioteca Rubber Band se usa bajo licencia GPL para transponer tono y/o cambiar velocidad. diff --git a/pl.lproj/Credits.html b/pl.lproj/Credits.html index 1162483e6..25a5a352a 100644 --- a/pl.lproj/Credits.html +++ b/pl.lproj/Credits.html @@ -35,6 +35,7 @@

This program has been made possible through contributions from users like you.

All Cog code is copyrighted by me, and is licensed under the GPL. Cog contains bits of other code from third parties that are under their own licenses. +

Biblioteka Rubber Band Library była używana zgodnie z zasadami licencji GPL, aby dostarczyć funkcję zmiany tonu i/lub przerwy w czasie. diff --git a/ru.lproj/Credits.html b/ru.lproj/Credits.html index 2f2d000dd..6ebf4c7f7 100644 --- a/ru.lproj/Credits.html +++ b/ru.lproj/Credits.html @@ -35,6 +35,8 @@

Создние этой программы стало возможным благодаря вкладу таких пользователей, как вы.

Весь код Cog защищен моим авторским правом и распространяется под лицензией GPL. Cog содержит фрагменты другого кода от третьих сторон, который находятся под их собственными лицензиями. + +

Библиотека Rubber Band Library использовалась под лицензией GPL для предоставления функции изменения тона и/или сдвига во времени. diff --git a/tr.lproj/Credits.html b/tr.lproj/Credits.html index 1162483e6..194d3eea5 100644 --- a/tr.lproj/Credits.html +++ b/tr.lproj/Credits.html @@ -35,6 +35,7 @@

This program has been made possible through contributions from users like you.

All Cog code is copyrighted by me, and is licensed under the GPL. Cog contains bits of other code from third parties that are under their own licenses. +

Rubber Band Kütüphanesi, ton ve/veya zaman kayması sağlamak için GPL altında kullanıldı.