Refactor coreaudio host and add iOS support + ios-feedback example

This commit is contained in:
Michael Hills 2020-10-11 23:27:27 +11:00
parent 36ae2f02a8
commit 2cccf99d50
23 changed files with 2239 additions and 895 deletions

View file

@ -0,0 +1,17 @@
[package]
name = "cpal-ios-example"
version = "0.1.0"
authors = ["Michael Hills <mhills@gmail.com>"]
edition = "2018"
[lib]
name = "cpal_ios_example"
crate-type = ["staticlib"]
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[dependencies]
cpal = { path = "../.." }
anyhow = "1.0.12"
ringbuf = "0.1.6"

View file

@ -0,0 +1,25 @@
# iOS Feedback Example
This example is an Xcode project that exercises both input and output
audio streams. Audio samples are read in from your micrphone and then
routed to your audio output device with a small but noticeable delay
so you can verify it is working correctly.
To build the example you will need to still `cargo-lipo`. While not
necessary for building iOS binaries, it is used to build a universal
binary (x86 for simulator and aarch64 for device.)
```
cargo install cargo-lipo
```
Then open the XCode project and click run. A hook in the iOS application
lifecycle calls into the Rust code to start the input/output feedback
loop and immediately returns back control.
Before calling into Rust, the AVAudioSession category is configured.
This is important for controlling how audio is shared with the rest
of the system when your app is in the foreground. One example is
controlling whether other apps can play music in the background.
More information [here](https://developer.apple.com/library/archive/documentation/Audio/Conceptual/AudioSessionProgrammingGuide/AudioSessionCategoriesandModes/AudioSessionCategoriesandModes.html#//apple_ref/doc/uid/TP40007875-CH10).

View file

@ -0,0 +1,12 @@
#!/bin/sh
set -e
PATH=$PATH:$HOME/.cargo/bin
# If you want your build to run faster, add a "--targets x86_64-apple-ios" for just using the ios simulator.
if [ -n ${IOS_TARGETS} ]; then
cargo lipo --targets ${IOS_TARGETS}
else
cargo lipo
fi

View file

@ -0,0 +1,429 @@
// !$*UTF8*$!
{
archiveVersion = 1;
classes = {
};
objectVersion = 50;
objects = {
/* Begin PBXBuildFile section */
57AB5AF3252767460040DE8C /* AVFoundation.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 57AB5AF2252767460040DE8C /* AVFoundation.framework */; };
57AB5B07252769700040DE8C /* ViewController.m in Sources */ = {isa = PBXBuildFile; fileRef = 57AB5AFE252769700040DE8C /* ViewController.m */; };
57AB5B08252769700040DE8C /* LaunchScreen.storyboard in Resources */ = {isa = PBXBuildFile; fileRef = 57AB5AFF252769700040DE8C /* LaunchScreen.storyboard */; };
57AB5B09252769700040DE8C /* Main.storyboard in Resources */ = {isa = PBXBuildFile; fileRef = 57AB5B01252769700040DE8C /* Main.storyboard */; };
57AB5B0A252769700040DE8C /* main.m in Sources */ = {isa = PBXBuildFile; fileRef = 57AB5B03252769700040DE8C /* main.m */; };
57AB5B0B252769700040DE8C /* AppDelegate.m in Sources */ = {isa = PBXBuildFile; fileRef = 57AB5B04252769700040DE8C /* AppDelegate.m */; };
/* End PBXBuildFile section */
/* Begin PBXContainerItemProxy section */
57AB5AEE252766820040DE8C /* PBXContainerItemProxy */ = {
isa = PBXContainerItemProxy;
containerPortal = 57AB5AC2252762C00040DE8C /* Project object */;
proxyType = 1;
remoteGlobalIDString = 57AB5AE9252766240040DE8C;
remoteInfo = cargo_ios;
};
/* End PBXContainerItemProxy section */
/* Begin PBXFileReference section */
57AB5ACA252762C10040DE8C /* cpal-ios-example.app */ = {isa = PBXFileReference; explicitFileType = wrapper.application; includeInIndex = 0; path = "cpal-ios-example.app"; sourceTree = BUILT_PRODUCTS_DIR; };
57AB5AF2252767460040DE8C /* AVFoundation.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = AVFoundation.framework; path = System/Library/Frameworks/AVFoundation.framework; sourceTree = SDKROOT; };
57AB5AFD252769700040DE8C /* AppDelegate.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = AppDelegate.h; sourceTree = "<group>"; };
57AB5AFE252769700040DE8C /* ViewController.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = ViewController.m; sourceTree = "<group>"; };
57AB5B00252769700040DE8C /* Base */ = {isa = PBXFileReference; lastKnownFileType = file.storyboard; name = Base; path = Base.lproj/LaunchScreen.storyboard; sourceTree = "<group>"; };
57AB5B02252769700040DE8C /* Base */ = {isa = PBXFileReference; lastKnownFileType = file.storyboard; name = Base; path = Base.lproj/Main.storyboard; sourceTree = "<group>"; };
57AB5B03252769700040DE8C /* main.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = main.m; sourceTree = "<group>"; };
57AB5B04252769700040DE8C /* AppDelegate.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = AppDelegate.m; sourceTree = "<group>"; };
57AB5B05252769700040DE8C /* Info.plist */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = "<group>"; };
57AB5B06252769700040DE8C /* ViewController.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = ViewController.h; sourceTree = "<group>"; };
/* End PBXFileReference section */
/* Begin PBXFrameworksBuildPhase section */
57AB5AC7252762C10040DE8C /* Frameworks */ = {
isa = PBXFrameworksBuildPhase;
buildActionMask = 2147483647;
files = (
57AB5AF3252767460040DE8C /* AVFoundation.framework in Frameworks */,
);
runOnlyForDeploymentPostprocessing = 0;
};
/* End PBXFrameworksBuildPhase section */
/* Begin PBXGroup section */
57AB5AC1252762C00040DE8C = {
isa = PBXGroup;
children = (
57AB5AFC252769700040DE8C /* ios-src */,
57AB5ACB252762C10040DE8C /* Products */,
57AB5AF1252767460040DE8C /* Frameworks */,
);
sourceTree = "<group>";
};
57AB5ACB252762C10040DE8C /* Products */ = {
isa = PBXGroup;
children = (
57AB5ACA252762C10040DE8C /* cpal-ios-example.app */,
);
name = Products;
sourceTree = "<group>";
};
57AB5AF1252767460040DE8C /* Frameworks */ = {
isa = PBXGroup;
children = (
57AB5AF2252767460040DE8C /* AVFoundation.framework */,
);
name = Frameworks;
sourceTree = "<group>";
};
57AB5AFC252769700040DE8C /* ios-src */ = {
isa = PBXGroup;
children = (
57AB5AFD252769700040DE8C /* AppDelegate.h */,
57AB5B04252769700040DE8C /* AppDelegate.m */,
57AB5B06252769700040DE8C /* ViewController.h */,
57AB5AFE252769700040DE8C /* ViewController.m */,
57AB5AFF252769700040DE8C /* LaunchScreen.storyboard */,
57AB5B01252769700040DE8C /* Main.storyboard */,
57AB5B05252769700040DE8C /* Info.plist */,
57AB5B03252769700040DE8C /* main.m */,
);
path = "ios-src";
sourceTree = "<group>";
};
/* End PBXGroup section */
/* Begin PBXLegacyTarget section */
57AB5AE9252766240040DE8C /* cargo_ios */ = {
isa = PBXLegacyTarget;
buildArgumentsString = build_rust_deps.sh;
buildConfigurationList = 57AB5AEA252766240040DE8C /* Build configuration list for PBXLegacyTarget "cargo_ios" */;
buildPhases = (
);
buildToolPath = /bin/sh;
buildWorkingDirectory = .;
dependencies = (
);
name = cargo_ios;
passBuildSettingsInEnvironment = 1;
productName = cargo_ios;
};
/* End PBXLegacyTarget section */
/* Begin PBXNativeTarget section */
57AB5AC9252762C10040DE8C /* cpal-ios-example */ = {
isa = PBXNativeTarget;
buildConfigurationList = 57AB5AE3252762C30040DE8C /* Build configuration list for PBXNativeTarget "cpal-ios-example" */;
buildPhases = (
57AB5AC6252762C10040DE8C /* Sources */,
57AB5AC7252762C10040DE8C /* Frameworks */,
57AB5AC8252762C10040DE8C /* Resources */,
);
buildRules = (
);
dependencies = (
57AB5AEF252766820040DE8C /* PBXTargetDependency */,
);
name = "cpal-ios-example";
productName = "cpal-ios-example";
productReference = 57AB5ACA252762C10040DE8C /* cpal-ios-example.app */;
productType = "com.apple.product-type.application";
};
/* End PBXNativeTarget section */
/* Begin PBXProject section */
57AB5AC2252762C00040DE8C /* Project object */ = {
isa = PBXProject;
attributes = {
LastUpgradeCheck = 1200;
TargetAttributes = {
57AB5AC9252762C10040DE8C = {
CreatedOnToolsVersion = 12.0.1;
};
57AB5AE9252766240040DE8C = {
CreatedOnToolsVersion = 12.0.1;
};
};
};
buildConfigurationList = 57AB5AC5252762C00040DE8C /* Build configuration list for PBXProject "cpal-ios-example" */;
compatibilityVersion = "Xcode 9.3";
developmentRegion = en;
hasScannedForEncodings = 0;
knownRegions = (
en,
Base,
);
mainGroup = 57AB5AC1252762C00040DE8C;
productRefGroup = 57AB5ACB252762C10040DE8C /* Products */;
projectDirPath = "";
projectRoot = "";
targets = (
57AB5AC9252762C10040DE8C /* cpal-ios-example */,
57AB5AE9252766240040DE8C /* cargo_ios */,
);
};
/* End PBXProject section */
/* Begin PBXResourcesBuildPhase section */
57AB5AC8252762C10040DE8C /* Resources */ = {
isa = PBXResourcesBuildPhase;
buildActionMask = 2147483647;
files = (
57AB5B09252769700040DE8C /* Main.storyboard in Resources */,
57AB5B08252769700040DE8C /* LaunchScreen.storyboard in Resources */,
);
runOnlyForDeploymentPostprocessing = 0;
};
/* End PBXResourcesBuildPhase section */
/* Begin PBXSourcesBuildPhase section */
57AB5AC6252762C10040DE8C /* Sources */ = {
isa = PBXSourcesBuildPhase;
buildActionMask = 2147483647;
files = (
57AB5B0A252769700040DE8C /* main.m in Sources */,
57AB5B0B252769700040DE8C /* AppDelegate.m in Sources */,
57AB5B07252769700040DE8C /* ViewController.m in Sources */,
);
runOnlyForDeploymentPostprocessing = 0;
};
/* End PBXSourcesBuildPhase section */
/* Begin PBXTargetDependency section */
57AB5AEF252766820040DE8C /* PBXTargetDependency */ = {
isa = PBXTargetDependency;
target = 57AB5AE9252766240040DE8C /* cargo_ios */;
targetProxy = 57AB5AEE252766820040DE8C /* PBXContainerItemProxy */;
};
/* End PBXTargetDependency section */
/* Begin PBXVariantGroup section */
57AB5AFF252769700040DE8C /* LaunchScreen.storyboard */ = {
isa = PBXVariantGroup;
children = (
57AB5B00252769700040DE8C /* Base */,
);
name = LaunchScreen.storyboard;
sourceTree = "<group>";
};
57AB5B01252769700040DE8C /* Main.storyboard */ = {
isa = PBXVariantGroup;
children = (
57AB5B02252769700040DE8C /* Base */,
);
name = Main.storyboard;
sourceTree = "<group>";
};
/* End PBXVariantGroup section */
/* Begin XCBuildConfiguration section */
57AB5AE1252762C30040DE8C /* Debug */ = {
isa = XCBuildConfiguration;
buildSettings = {
ALWAYS_SEARCH_USER_PATHS = NO;
CLANG_ANALYZER_NONNULL = YES;
CLANG_ANALYZER_NUMBER_OBJECT_CONVERSION = YES_AGGRESSIVE;
CLANG_CXX_LANGUAGE_STANDARD = "gnu++14";
CLANG_CXX_LIBRARY = "libc++";
CLANG_ENABLE_MODULES = YES;
CLANG_ENABLE_OBJC_ARC = YES;
CLANG_ENABLE_OBJC_WEAK = YES;
CLANG_WARN_BLOCK_CAPTURE_AUTORELEASING = YES;
CLANG_WARN_BOOL_CONVERSION = YES;
CLANG_WARN_COMMA = YES;
CLANG_WARN_CONSTANT_CONVERSION = YES;
CLANG_WARN_DEPRECATED_OBJC_IMPLEMENTATIONS = YES;
CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR;
CLANG_WARN_DOCUMENTATION_COMMENTS = YES;
CLANG_WARN_EMPTY_BODY = YES;
CLANG_WARN_ENUM_CONVERSION = YES;
CLANG_WARN_INFINITE_RECURSION = YES;
CLANG_WARN_INT_CONVERSION = YES;
CLANG_WARN_NON_LITERAL_NULL_CONVERSION = YES;
CLANG_WARN_OBJC_IMPLICIT_RETAIN_SELF = YES;
CLANG_WARN_OBJC_LITERAL_CONVERSION = YES;
CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR;
CLANG_WARN_QUOTED_INCLUDE_IN_FRAMEWORK_HEADER = YES;
CLANG_WARN_RANGE_LOOP_ANALYSIS = YES;
CLANG_WARN_STRICT_PROTOTYPES = YES;
CLANG_WARN_SUSPICIOUS_MOVE = YES;
CLANG_WARN_UNGUARDED_AVAILABILITY = YES_AGGRESSIVE;
CLANG_WARN_UNREACHABLE_CODE = YES;
CLANG_WARN__DUPLICATE_METHOD_MATCH = YES;
COPY_PHASE_STRIP = NO;
DEBUG_INFORMATION_FORMAT = dwarf;
ENABLE_STRICT_OBJC_MSGSEND = YES;
ENABLE_TESTABILITY = YES;
GCC_C_LANGUAGE_STANDARD = gnu11;
GCC_DYNAMIC_NO_PIC = NO;
GCC_NO_COMMON_BLOCKS = YES;
GCC_OPTIMIZATION_LEVEL = 0;
GCC_PREPROCESSOR_DEFINITIONS = (
"DEBUG=1",
"$(inherited)",
);
GCC_WARN_64_TO_32_BIT_CONVERSION = YES;
GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR;
GCC_WARN_UNDECLARED_SELECTOR = YES;
GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE;
GCC_WARN_UNUSED_FUNCTION = YES;
GCC_WARN_UNUSED_VARIABLE = YES;
IPHONEOS_DEPLOYMENT_TARGET = 12.0;
MTL_ENABLE_DEBUG_INFO = INCLUDE_SOURCE;
MTL_FAST_MATH = YES;
ONLY_ACTIVE_ARCH = YES;
SDKROOT = iphoneos;
};
name = Debug;
};
57AB5AE2252762C30040DE8C /* Release */ = {
isa = XCBuildConfiguration;
buildSettings = {
ALWAYS_SEARCH_USER_PATHS = NO;
CLANG_ANALYZER_NONNULL = YES;
CLANG_ANALYZER_NUMBER_OBJECT_CONVERSION = YES_AGGRESSIVE;
CLANG_CXX_LANGUAGE_STANDARD = "gnu++14";
CLANG_CXX_LIBRARY = "libc++";
CLANG_ENABLE_MODULES = YES;
CLANG_ENABLE_OBJC_ARC = YES;
CLANG_ENABLE_OBJC_WEAK = YES;
CLANG_WARN_BLOCK_CAPTURE_AUTORELEASING = YES;
CLANG_WARN_BOOL_CONVERSION = YES;
CLANG_WARN_COMMA = YES;
CLANG_WARN_CONSTANT_CONVERSION = YES;
CLANG_WARN_DEPRECATED_OBJC_IMPLEMENTATIONS = YES;
CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR;
CLANG_WARN_DOCUMENTATION_COMMENTS = YES;
CLANG_WARN_EMPTY_BODY = YES;
CLANG_WARN_ENUM_CONVERSION = YES;
CLANG_WARN_INFINITE_RECURSION = YES;
CLANG_WARN_INT_CONVERSION = YES;
CLANG_WARN_NON_LITERAL_NULL_CONVERSION = YES;
CLANG_WARN_OBJC_IMPLICIT_RETAIN_SELF = YES;
CLANG_WARN_OBJC_LITERAL_CONVERSION = YES;
CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR;
CLANG_WARN_QUOTED_INCLUDE_IN_FRAMEWORK_HEADER = YES;
CLANG_WARN_RANGE_LOOP_ANALYSIS = YES;
CLANG_WARN_STRICT_PROTOTYPES = YES;
CLANG_WARN_SUSPICIOUS_MOVE = YES;
CLANG_WARN_UNGUARDED_AVAILABILITY = YES_AGGRESSIVE;
CLANG_WARN_UNREACHABLE_CODE = YES;
CLANG_WARN__DUPLICATE_METHOD_MATCH = YES;
COPY_PHASE_STRIP = NO;
DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym";
ENABLE_NS_ASSERTIONS = NO;
ENABLE_STRICT_OBJC_MSGSEND = YES;
GCC_C_LANGUAGE_STANDARD = gnu11;
GCC_NO_COMMON_BLOCKS = YES;
GCC_WARN_64_TO_32_BIT_CONVERSION = YES;
GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR;
GCC_WARN_UNDECLARED_SELECTOR = YES;
GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE;
GCC_WARN_UNUSED_FUNCTION = YES;
GCC_WARN_UNUSED_VARIABLE = YES;
IPHONEOS_DEPLOYMENT_TARGET = 12.0;
MTL_ENABLE_DEBUG_INFO = NO;
MTL_FAST_MATH = YES;
SDKROOT = iphoneos;
VALIDATE_PRODUCT = YES;
};
name = Release;
};
57AB5AE4252762C30040DE8C /* Debug */ = {
isa = XCBuildConfiguration;
buildSettings = {
ASSETCATALOG_COMPILER_GLOBAL_ACCENT_COLOR_NAME = AccentColor;
CODE_SIGN_STYLE = Automatic;
INFOPLIST_FILE = "ios-src/Info.plist";
IPHONEOS_DEPLOYMENT_TARGET = 12.0;
LD_RUNPATH_SEARCH_PATHS = (
"$(inherited)",
"@executable_path/Frameworks",
);
LIBRARY_SEARCH_PATHS = target/universal/debug;
OTHER_LDFLAGS = "-lcpal_ios_example";
OTHER_LIBTOOLFLAGS = "";
PRODUCT_BUNDLE_IDENTIFIER = "cpal.cpal-ios-example";
PRODUCT_NAME = "$(TARGET_NAME)";
TARGETED_DEVICE_FAMILY = "1,2";
};
name = Debug;
};
57AB5AE5252762C30040DE8C /* Release */ = {
isa = XCBuildConfiguration;
buildSettings = {
ASSETCATALOG_COMPILER_GLOBAL_ACCENT_COLOR_NAME = AccentColor;
CODE_SIGN_STYLE = Automatic;
INFOPLIST_FILE = "ios-src/Info.plist";
IPHONEOS_DEPLOYMENT_TARGET = 12.0;
LD_RUNPATH_SEARCH_PATHS = (
"$(inherited)",
"@executable_path/Frameworks",
);
LIBRARY_SEARCH_PATHS = target/universal/release;
OTHER_LDFLAGS = "-lcpal_ios_example";
OTHER_LIBTOOLFLAGS = "";
PRODUCT_BUNDLE_IDENTIFIER = "cpal.cpal-ios-example";
PRODUCT_NAME = "$(TARGET_NAME)";
TARGETED_DEVICE_FAMILY = "1,2";
};
name = Release;
};
57AB5AEB252766240040DE8C /* Debug */ = {
isa = XCBuildConfiguration;
buildSettings = {
CODE_SIGN_STYLE = Automatic;
DEBUGGING_SYMBOLS = YES;
DEBUG_INFORMATION_FORMAT = dwarf;
GCC_GENERATE_DEBUGGING_SYMBOLS = YES;
GCC_OPTIMIZATION_LEVEL = 0;
OTHER_CFLAGS = "";
OTHER_LDFLAGS = "";
PRODUCT_NAME = "$(TARGET_NAME)";
};
name = Debug;
};
57AB5AEC252766240040DE8C /* Release */ = {
isa = XCBuildConfiguration;
buildSettings = {
CODE_SIGN_STYLE = Automatic;
DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym";
OTHER_CFLAGS = "";
OTHER_LDFLAGS = "";
PRODUCT_NAME = "$(TARGET_NAME)";
};
name = Release;
};
/* End XCBuildConfiguration section */
/* Begin XCConfigurationList section */
57AB5AC5252762C00040DE8C /* Build configuration list for PBXProject "cpal-ios-example" */ = {
isa = XCConfigurationList;
buildConfigurations = (
57AB5AE1252762C30040DE8C /* Debug */,
57AB5AE2252762C30040DE8C /* Release */,
);
defaultConfigurationIsVisible = 0;
defaultConfigurationName = Release;
};
57AB5AE3252762C30040DE8C /* Build configuration list for PBXNativeTarget "cpal-ios-example" */ = {
isa = XCConfigurationList;
buildConfigurations = (
57AB5AE4252762C30040DE8C /* Debug */,
57AB5AE5252762C30040DE8C /* Release */,
);
defaultConfigurationIsVisible = 0;
defaultConfigurationName = Release;
};
57AB5AEA252766240040DE8C /* Build configuration list for PBXLegacyTarget "cargo_ios" */ = {
isa = XCConfigurationList;
buildConfigurations = (
57AB5AEB252766240040DE8C /* Debug */,
57AB5AEC252766240040DE8C /* Release */,
);
defaultConfigurationIsVisible = 0;
defaultConfigurationName = Release;
};
/* End XCConfigurationList section */
};
rootObject = 57AB5AC2252762C00040DE8C /* Project object */;
}

View file

@ -0,0 +1,7 @@
<?xml version="1.0" encoding="UTF-8"?>
<Workspace
version = "1.0">
<FileRef
location = "self:">
</FileRef>
</Workspace>

View file

@ -0,0 +1,8 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>IDEDidComputeMac32BitWarning</key>
<true/>
</dict>
</plist>

View file

@ -0,0 +1,19 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>SchemeUserState</key>
<dict>
<key>cargo_ios.xcscheme_^#shared#^_</key>
<dict>
<key>orderHint</key>
<integer>0</integer>
</dict>
<key>cpal-ios-example.xcscheme_^#shared#^_</key>
<dict>
<key>orderHint</key>
<integer>1</integer>
</dict>
</dict>
</dict>
</plist>

View file

@ -0,0 +1,15 @@
//
// AppDelegate.h
// cpal-ios-example
//
// Created by Michael Hills on 2/10/20.
//
#import <UIKit/UIKit.h>
@interface AppDelegate : UIResponder <UIApplicationDelegate>
@property (strong, nonatomic) UIWindow *window;
@end

View file

@ -0,0 +1,49 @@
//
// AppDelegate.m
// cpal-ios-example
//
// Created by Michael Hills on 2/10/20.
//
#import "AppDelegate.h"
@import AVFoundation;
void rust_ios_main(void);
@interface AppDelegate ()
@end
@implementation AppDelegate
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
// Override point for customization after application launch.
NSError *error;
BOOL success;
// It is necessary to access the sharedInstance so that calls to AudioSessionGetProperty
// will work.
AVAudioSession *session = AVAudioSession.sharedInstance;
// Setting up the category is not necessary, but generally advised.
// Since this demo records and plays, lets use AVAudioSessionCategoryPlayAndRecord.
// Also default to speaker as defaulting to the phone earpiece would be unusual.
// Allowing bluetooth should direct audio to your bluetooth headset.
success = [session setCategory:AVAudioSessionCategoryPlayAndRecord
withOptions:AVAudioSessionCategoryOptionDefaultToSpeaker | AVAudioSessionCategoryOptionAllowBluetooth
error:&error];
if (success) {
NSLog(@"Calling rust_ios_main()");
rust_ios_main();
} else {
NSLog(@"Failed to configure audio session category");
}
return YES;
}
@end

View file

@ -0,0 +1,25 @@
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<document type="com.apple.InterfaceBuilder3.CocoaTouch.Storyboard.XIB" version="3.0" toolsVersion="13122.16" targetRuntime="iOS.CocoaTouch" propertyAccessControl="none" useAutolayout="YES" launchScreen="YES" useTraitCollections="YES" useSafeAreas="YES" colorMatched="YES" initialViewController="01J-lp-oVM">
<dependencies>
<plugIn identifier="com.apple.InterfaceBuilder.IBCocoaTouchPlugin" version="13104.12"/>
<capability name="Safe area layout guides" minToolsVersion="9.0"/>
<capability name="documents saved in the Xcode 8 format" minToolsVersion="8.0"/>
</dependencies>
<scenes>
<!--View Controller-->
<scene sceneID="EHf-IW-A2E">
<objects>
<viewController id="01J-lp-oVM" sceneMemberID="viewController">
<view key="view" contentMode="scaleToFill" id="Ze5-6b-2t3">
<rect key="frame" x="0.0" y="0.0" width="375" height="667"/>
<autoresizingMask key="autoresizingMask" widthSizable="YES" heightSizable="YES"/>
<color key="backgroundColor" xcode11CocoaTouchSystemColor="systemBackgroundColor" cocoaTouchSystemColor="whiteColor"/>
<viewLayoutGuide key="safeArea" id="6Tk-OE-BBY"/>
</view>
</viewController>
<placeholder placeholderIdentifier="IBFirstResponder" id="iYj-Kq-Ea1" userLabel="First Responder" sceneMemberID="firstResponder"/>
</objects>
<point key="canvasLocation" x="53" y="375"/>
</scene>
</scenes>
</document>

View file

@ -0,0 +1,24 @@
<?xml version="1.0" encoding="UTF-8"?>
<document type="com.apple.InterfaceBuilder3.CocoaTouch.Storyboard.XIB" version="3.0" toolsVersion="13122.16" targetRuntime="iOS.CocoaTouch" propertyAccessControl="none" useAutolayout="YES" useTraitCollections="YES" useSafeAreas="YES" colorMatched="YES" initialViewController="BYZ-38-t0r">
<dependencies>
<plugIn identifier="com.apple.InterfaceBuilder.IBCocoaTouchPlugin" version="13104.12"/>
<capability name="Safe area layout guides" minToolsVersion="9.0"/>
<capability name="documents saved in the Xcode 8 format" minToolsVersion="8.0"/>
</dependencies>
<scenes>
<!--View Controller-->
<scene sceneID="tne-QT-ifu">
<objects>
<viewController id="BYZ-38-t0r" customClass="ViewController" customModuleProvider="" sceneMemberID="viewController">
<view key="view" contentMode="scaleToFill" id="8bC-Xf-vdC">
<rect key="frame" x="0.0" y="0.0" width="375" height="667"/>
<autoresizingMask key="autoresizingMask" widthSizable="YES" heightSizable="YES"/>
<color key="backgroundColor" xcode11CocoaTouchSystemColor="systemBackgroundColor" cocoaTouchSystemColor="whiteColor"/>
<viewLayoutGuide key="safeArea" id="6Tk-OE-BBY"/>
</view>
</viewController>
<placeholder placeholderIdentifier="IBFirstResponder" id="dkx-z0-nzr" sceneMemberID="firstResponder"/>
</objects>
</scene>
</scenes>
</document>

View file

@ -0,0 +1,49 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>CFBundleDevelopmentRegion</key>
<string>$(DEVELOPMENT_LANGUAGE)</string>
<key>CFBundleExecutable</key>
<string>$(EXECUTABLE_NAME)</string>
<key>CFBundleIdentifier</key>
<string>$(PRODUCT_BUNDLE_IDENTIFIER)</string>
<key>CFBundleInfoDictionaryVersion</key>
<string>6.0</string>
<key>CFBundleName</key>
<string>$(PRODUCT_NAME)</string>
<key>CFBundlePackageType</key>
<string>$(PRODUCT_BUNDLE_PACKAGE_TYPE)</string>
<key>CFBundleShortVersionString</key>
<string>1.0</string>
<key>CFBundleVersion</key>
<string>1</string>
<key>LSRequiresIPhoneOS</key>
<true/>
<key>UIApplicationSupportsIndirectInputEvents</key>
<true/>
<key>UILaunchStoryboardName</key>
<string>LaunchScreen</string>
<key>UIMainStoryboardFile</key>
<string>Main</string>
<key>UIRequiredDeviceCapabilities</key>
<array>
<string>armv7</string>
</array>
<key>UISupportedInterfaceOrientations</key>
<array>
<string>UIInterfaceOrientationPortrait</string>
<string>UIInterfaceOrientationLandscapeLeft</string>
<string>UIInterfaceOrientationLandscapeRight</string>
</array>
<key>NSMicrophoneUsageDescription</key>
<string>cpal feedback demo</string>
<key>UISupportedInterfaceOrientations~ipad</key>
<array>
<string>UIInterfaceOrientationPortrait</string>
<string>UIInterfaceOrientationPortraitUpsideDown</string>
<string>UIInterfaceOrientationLandscapeLeft</string>
<string>UIInterfaceOrientationLandscapeRight</string>
</array>
</dict>
</plist>

View file

@ -0,0 +1,14 @@
//
// ViewController.h
// cpal-ios-example
//
// Created by Michael Hills on 2/10/20.
//
#import <UIKit/UIKit.h>
@interface ViewController : UIViewController
@end

View file

@ -0,0 +1,22 @@
//
// ViewController.m
// cpal-ios-example
//
// Created by Michael Hills on 2/10/20.
//
#import "ViewController.h"
@interface ViewController ()
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view.
}
@end

View file

@ -0,0 +1,18 @@
//
// main.m
// cpal-ios-example
//
// Created by Michael Hills on 2/10/20.
//
#import <UIKit/UIKit.h>
#import "AppDelegate.h"
int main(int argc, char * argv[]) {
NSString * appDelegateClassName;
@autoreleasepool {
// Setup code that might create autoreleased objects goes here.
appDelegateClassName = NSStringFromClass([AppDelegate class]);
}
return UIApplicationMain(argc, argv, nil, appDelegateClassName);
}

View file

@ -0,0 +1,108 @@
//! Feeds back the input stream directly into the output stream.
//!
//! Assumes that the input and output devices can use the same stream configuration and that they
//! support the f32 sample format.
//!
//! Uses a delay of `LATENCY_MS` milliseconds in case the default input and output streams are not
//! precisely synchronised.
extern crate anyhow;
extern crate cpal;
extern crate ringbuf;
use cpal::traits::{DeviceTrait, HostTrait, StreamTrait};
use ringbuf::RingBuffer;
const LATENCY_MS: f32 = 1000.0;
pub fn run_example() -> Result<(), anyhow::Error> {
let host = cpal::default_host();
// Default devices.
let input_device = host
.default_input_device()
.expect("failed to get default input device");
let output_device = host
.default_output_device()
.expect("failed to get default output device");
println!("Using default input device: \"{}\"", input_device.name()?);
println!("Using default output device: \"{}\"", output_device.name()?);
// We'll try and use the same configuration between streams to keep it simple.
let config: cpal::StreamConfig = input_device.default_input_config()?.into();
// Create a delay in case the input and output devices aren't synced.
let latency_frames = (LATENCY_MS / 1_000.0) * config.sample_rate.0 as f32;
let latency_samples = latency_frames as usize * config.channels as usize;
// The buffer to share samples
let ring = RingBuffer::new(latency_samples * 2);
let (mut producer, mut consumer) = ring.split();
// Fill the samples with 0.0 equal to the length of the delay.
for _ in 0..latency_samples {
// The ring buffer has twice as much space as necessary to add latency here,
// so this should never fail
producer.push(0.0).unwrap();
}
let input_data_fn = move |data: &[f32], _: &cpal::InputCallbackInfo| {
let mut output_fell_behind = false;
for &sample in data {
if producer.push(sample).is_err() {
output_fell_behind = true;
}
}
if output_fell_behind {
eprintln!("output stream fell behind: try increasing latency");
}
};
let output_data_fn = move |data: &mut [f32], _: &cpal::OutputCallbackInfo| {
let mut input_fell_behind = None;
for sample in data {
*sample = match consumer.pop() {
Ok(s) => s,
Err(err) => {
input_fell_behind = Some(err);
0.0
}
};
}
if let Some(err) = input_fell_behind {
eprintln!(
"input stream fell behind: {:?}: try increasing latency",
err
);
}
};
// Build streams.
println!(
"Attempting to build both streams with f32 samples and `{:?}`.",
config
);
println!("setup is");
let input_stream = input_device.build_input_stream(&config, input_data_fn, err_fn)?;
println!("setup os");
let output_stream = output_device.build_output_stream(&config, output_data_fn, err_fn)?;
println!("Successfully built streams.");
// Play the streams.
println!(
"Starting the input and output streams with `{}` milliseconds of latency.",
LATENCY_MS
);
input_stream.play()?;
output_stream.play()?;
// for the purposes of this demo, leak these so that after returning the audio units will
// keep running
std::mem::forget(input_stream);
std::mem::forget(output_stream);
Ok(())
}
fn err_fn(err: cpal::StreamError) {
eprintln!("an error occurred on stream: {}", err);
}

View file

@ -0,0 +1,6 @@
mod feedback;
#[no_mangle]
pub extern "C" fn rust_ios_main() {
feedback::run_example().unwrap();
}