Update OpenAL-soft to 1.21.0

This allows OpenAL-soft to use Oboe backend which uses AAudio in Android 8
or OpenSLES in earlier Android version. This switch is necessary for
Android 11 compatibility as OpenSLES is now deprecated in Android 11.

Plus, we also have low latency audio for free.
This commit is contained in:
Miku AuahDark
2020-12-24 15:01:23 +08:00
parent 96f7387ac5
commit dfe836d39c
1544 changed files with 266546 additions and 62914 deletions
+6
View File
@@ -0,0 +1,6 @@
*/.DS_Store
.DS_Store
.externalNativeBuild/
.cxx/
.idea
build
+30
View File
@@ -0,0 +1,30 @@
language: android
sudo: true
android:
components:
- tools
- platform-tools
- extra-google-m2repository
- extra-android-m2repository
addons:
apt_packages:
- pandoc
before_install:
- sudo apt-get install ant
install:
- touch ~/.android/repositories.cfg
- echo y | sdkmanager "ndk-bundle"
- echo y | sdkmanager "cmake;3.6.4111459"
# the following line triggers Trivis-CI's 4MB log limit
# - sdkmanager --update
before_script:
- export ANDROID_NDK_HOME=$ANDROID_HOME/ndk-bundle
script:
# scripts excutes inside our repo directory on CI machine
- export SAMPLE_CI_RESULT=0
- source .ci_tools/setup_env.sh
- source .ci_tools/build_samples.sh
- source .ci_tools/run_samples.sh
- source .ci_tools/misc_ci.sh
- eval "[[ $SAMPLE_CI_RESULT == 0 ]]"
+9
View File
@@ -0,0 +1,9 @@
# This is the official list of authors for copyright purposes.
# This file is distinct from the CONTRIBUTORS files.
# See the latter for an explanation.
# Names should be added to this file as:
# Name or Organization <email address>
# The email address is not required for organizations.
Google Inc.
+84
View File
@@ -0,0 +1,84 @@
LOCAL_PATH:= $(call my-dir)
include $(CLEAR_VARS)
#
# Module
#
LOCAL_MODULE := oboe
LOCAL_ARM_NEON := true
#
# Flags
#
LOCAL_CFLAGS := -Wall -Wextra-semi -Wshadow -Wshadow-field
LOCAL_CPPFLAGS := -std=c++14
#
# Include paths
#
LOCAL_C_INCLUDES := \
$(LOCAL_PATH)/include \
$(LOCAL_PATH)/src
LOCAL_EXPORT_C_INCLUDES := $(LOCAL_PATH)/include
#
# Source files
#
LOCAL_SRC_FILES := \
src/aaudio/AAudioLoader.cpp \
src/aaudio/AudioStreamAAudio.cpp \
src/common/AudioSourceCaller.cpp \
src/common/AudioStream.cpp \
src/common/AudioStreamBuilder.cpp \
src/common/DataConversionFlowGraph.cpp \
src/common/FilterAudioStream.cpp \
src/common/FixedBlockAdapter.cpp \
src/common/FixedBlockReader.cpp \
src/common/FixedBlockWriter.cpp \
src/common/LatencyTuner.cpp \
src/common/SourceFloatCaller.cpp \
src/common/SourceI16Caller.cpp \
src/common/Utilities.cpp \
src/common/QuirksManager.cpp \
src/fifo/FifoBuffer.cpp \
src/fifo/FifoController.cpp \
src/fifo/FifoControllerBase.cpp \
src/fifo/FifoControllerIndirect.cpp \
src/flowgraph/FlowGraphNode.cpp \
src/flowgraph/ClipToRange.cpp \
src/flowgraph/ManyToMultiConverter.cpp \
src/flowgraph/MonoToMultiConverter.cpp \
src/flowgraph/RampLinear.cpp \
src/flowgraph/SampleRateConverter.cpp \
src/flowgraph/SinkFloat.cpp \
src/flowgraph/SinkI16.cpp \
src/flowgraph/SinkI24.cpp \
src/flowgraph/SourceFloat.cpp \
src/flowgraph/SourceI16.cpp \
src/flowgraph/SourceI24.cpp \
src/flowgraph/resampler/IntegerRatio.cpp \
src/flowgraph/resampler/LinearResampler.cpp \
src/flowgraph/resampler/MultiChannelResampler.cpp \
src/flowgraph/resampler/PolyphaseResampler.cpp \
src/flowgraph/resampler/PolyphaseResamplerMono.cpp \
src/flowgraph/resampler/PolyphaseResamplerStereo.cpp \
src/flowgraph/resampler/SincResampler.cpp \
src/flowgraph/resampler/SincResamplerStereo.cpp \
src/opensles/AudioInputStreamOpenSLES.cpp \
src/opensles/AudioOutputStreamOpenSLES.cpp \
src/opensles/AudioStreamBuffered.cpp \
src/opensles/AudioStreamOpenSLES.cpp \
src/opensles/EngineOpenSLES.cpp \
src/opensles/OpenSLESUtilities.cpp \
src/opensles/OutputMixerOpenSLES.cpp \
src/common/StabilizedCallback.cpp \
src/common/Trace.cpp \
src/common/Version.cpp
#
# Libraries related
#
LOCAL_LDLIBS := -llog
# Build
include $(BUILD_STATIC_LIBRARY)
+92
View File
@@ -0,0 +1,92 @@
cmake_minimum_required(VERSION 3.4.1)
# Set the name of the project and store it in PROJECT_NAME. Also set the following variables:
# PROJECT_SOURCE_DIR (usually the root directory where Oboe has been cloned e.g.)
# PROJECT_BINARY_DIR (usually the containing project's binary directory,
# e.g. ${OBOE_HOME}/samples/RhythmGame/.externalNativeBuild/cmake/ndkExtractorDebug/x86/oboe-bin)
project(oboe)
set (oboe_sources
src/aaudio/AAudioLoader.cpp
src/aaudio/AudioStreamAAudio.cpp
src/common/AudioSourceCaller.cpp
src/common/AudioStream.cpp
src/common/AudioStreamBuilder.cpp
src/common/DataConversionFlowGraph.cpp
src/common/FilterAudioStream.cpp
src/common/FixedBlockAdapter.cpp
src/common/FixedBlockReader.cpp
src/common/FixedBlockWriter.cpp
src/common/LatencyTuner.cpp
src/common/SourceFloatCaller.cpp
src/common/SourceI16Caller.cpp
src/common/Utilities.cpp
src/common/QuirksManager.cpp
src/fifo/FifoBuffer.cpp
src/fifo/FifoController.cpp
src/fifo/FifoControllerBase.cpp
src/fifo/FifoControllerIndirect.cpp
src/flowgraph/FlowGraphNode.cpp
src/flowgraph/ClipToRange.cpp
src/flowgraph/ManyToMultiConverter.cpp
src/flowgraph/MonoToMultiConverter.cpp
src/flowgraph/RampLinear.cpp
src/flowgraph/SampleRateConverter.cpp
src/flowgraph/SinkFloat.cpp
src/flowgraph/SinkI16.cpp
src/flowgraph/SinkI24.cpp
src/flowgraph/SourceFloat.cpp
src/flowgraph/SourceI16.cpp
src/flowgraph/SourceI24.cpp
src/flowgraph/resampler/IntegerRatio.cpp
src/flowgraph/resampler/LinearResampler.cpp
src/flowgraph/resampler/MultiChannelResampler.cpp
src/flowgraph/resampler/PolyphaseResampler.cpp
src/flowgraph/resampler/PolyphaseResamplerMono.cpp
src/flowgraph/resampler/PolyphaseResamplerStereo.cpp
src/flowgraph/resampler/SincResampler.cpp
src/flowgraph/resampler/SincResamplerStereo.cpp
src/opensles/AudioInputStreamOpenSLES.cpp
src/opensles/AudioOutputStreamOpenSLES.cpp
src/opensles/AudioStreamBuffered.cpp
src/opensles/AudioStreamOpenSLES.cpp
src/opensles/EngineOpenSLES.cpp
src/opensles/OpenSLESUtilities.cpp
src/opensles/OutputMixerOpenSLES.cpp
src/common/StabilizedCallback.cpp
src/common/Trace.cpp
src/common/Version.cpp
)
add_library(oboe ${oboe_sources})
# Specify directories which the compiler should look for headers
target_include_directories(oboe
PRIVATE src
PUBLIC include)
# Compile Flags:
# Enable -Werror when building debug config
# Enable -Ofast
target_compile_options(oboe
PRIVATE
-std=c++14
-Wall
-Wextra-semi
-Wshadow
-Wshadow-field
-Ofast
"$<$<CONFIG:DEBUG>:-Werror>")
# Enable logging of D,V for debug builds
target_compile_definitions(oboe PUBLIC $<$<CONFIG:DEBUG>:OBOE_ENABLE_LOGGING=1>)
target_link_libraries(oboe PRIVATE log OpenSLES)
# When installing oboe put the libraries in the lib/<ABI> folder e.g. lib/arm64-v8a
install(TARGETS oboe
LIBRARY DESTINATION lib/${ANDROID_ABI}
ARCHIVE DESTINATION lib/${ANDROID_ABI})
# Also install the headers
install(DIRECTORY include/oboe DESTINATION include)
+1
View File
@@ -0,0 +1 @@
Please see the CONTRIBUTING.md file for more information.
+25
View File
@@ -0,0 +1,25 @@
Want to contribute? Great! First, read this page (including the small print at the end).
### Before you contribute
Before we can use your code, you must sign the
[Google Individual Contributor License
Agreement](https://developers.google.com/open-source/cla/individual?csw=1)
(CLA), which you can do online. The CLA is necessary mainly because you own the
copyright to your changes, even after your contribution becomes part of our
codebase, so we need your permission to use and distribute your code. We also
need to be sure of various other things—for instance that you'll tell us if you
know that your code infringes on other people's patents. You don't have to sign
the CLA until after you've submitted your code for review and a member has
approved it, but you must do it before we can put your code into our codebase.
Before you start working on a larger contribution, you should get in touch with
us first through the issue tracker with your idea so that we can help out and
possibly guide you. Coordinating up front makes it much easier to avoid
frustration later on.
### Code reviews
All submissions, including submissions by project members, require review. We
use Github pull requests for this purpose.
### The small print
Contributions made by corporations are covered by a different agreement than
the one above, the Software Grant and Corporate Contributor License Agreement.
+14
View File
@@ -0,0 +1,14 @@
# People who have agreed to one of the CLAs and can contribute patches.
# The AUTHORS file lists the copyright holders; this file
# lists people. For example, Google employees are listed here
# but not in AUTHORS, because Google holds the copyright.
#
# https://developers.google.com/open-source/cla/individual
# https://developers.google.com/open-source/cla/corporate
#
# Names should be added to this file as:
# Name <email address>
Phil Burk <philburk@google.com>
Don Turner <donturner@google.com>
Mikhail Naganov <mnaganov@google.com>
File diff suppressed because it is too large Load Diff
+202
View File
@@ -0,0 +1,202 @@
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "[]"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. We also recommend that a
file or class name and description of purpose be included on the
same "printed page" as the copyright notice for easier
identification within third-party archives.
Copyright [yyyy] [name of copyright owner]
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
+1
View File
@@ -0,0 +1 @@
Please see the README.md file for more information.
+53
View File
@@ -0,0 +1,53 @@
# Oboe [![Build Status](https://travis-ci.org/google/oboe.svg?branch=master)](https://travis-ci.org/google/oboe)
[![Introduction to Oboe video](docs/images/getting-started-video.jpg)](https://www.youtube.com/watch?v=csfHAbr5ilI&list=PLWz5rJ2EKKc_duWv9IPNvx9YBudNMmLSa)
Oboe is a C++ library which makes it easy to build high-performance audio apps on Android. It was created primarily to allow developers to target a simplified API that works across multiple API levels back to API level 16 (Jelly Bean).
## Features
- Compatible with API 16 onwards - runs on 99% of Android devices
- Chooses the audio API (OpenSL ES on API 16+ or AAudio on API 27+) which will give the best audio performance on the target Android device
- Automatic latency tuning
- Modern C++ allowing you to write clean, elegant code
- [Used by popular apps and frameworks](docs/AppsUsingOboe.md)
## Requirements
To build Oboe you'll need a compiler which supports C++14 and the Android header files. The easiest way to obtain these is by downloading the Android NDK r17 or above. It can be installed using Android Studio's SDK manager, or via [direct download](https://developer.android.com/ndk/downloads/).
## API Documentation
- [Getting Started Guide](docs/GettingStarted.md)
- [Full Guide to Oboe](docs/FullGuide.md)
- [API reference](https://google.github.io/oboe/reference)
- [Tech Notes](docs/notes/)
- [History of Audio features/bugs by Android version](docs/AndroidAudioHistory.md)
- [Frequently Asked Questions](docs/FAQ.md) (FAQ)
- [Our roadmap](https://github.com/google/oboe/milestones) - Vote on a feature/issue by adding a thumbs up to the first comment.
## Testing
- [**OboeTester** app for measuring latency, glitches, etc.](https://github.com/google/oboe/tree/master/apps/OboeTester/docs)
- [Oboe unit tests](https://github.com/google/oboe/tree/master/tests)
## Videos
- [Getting started with Oboe](https://www.youtube.com/playlist?list=PLWz5rJ2EKKc_duWv9IPNvx9YBudNMmLSa)
- [Low Latency Audio - Because Your Ears Are Worth It](https://www.youtube.com/watch?v=8vOf_fDtur4) (Android Dev Summit '18)
- [Real-time audio with the 100 oscillator synthesizer](https://www.youtube.com/watch?v=J04iPJBkAKs) (DroidCon Berlin '18)
- [Winning on Android](https://www.youtube.com/watch?v=tWBojmBpS74) - How to optimize an Android audio app. (ADC '18)
- [Real-Time Processing on Android](https://youtu.be/hY9BrS2uX-c) (ADC '19)
## Sample code and apps
- Sample apps can be found in the [samples directory](samples).
- A complete "effects processor" app called FXLab can be found in the [apps/fxlab folder](apps/fxlab).
- Also check out the [Rhythm Game codelab](https://codelabs.developers.google.com/codelabs/musicalgame-using-oboe/index.html#0).
### Third party sample code
- [Ableton Link integration demo](https://github.com/jbloit/AndroidLinkAudio) (author: jbloit)
## Contributing
We would love to receive your pull requests. Before we can though, please read the [contributing](CONTRIBUTING.md) guidelines.
## Version history
View the [releases page](../../releases).
## License
[LICENSE](LICENSE)
@@ -0,0 +1,11 @@
.gradle
/local.properties
/.idea/workspace.xml
/.idea/libraries
.DS_Store
/build/
.idea/
/app/build/
/app/app.iml
*.iml
/app/externalNativeBuild/
@@ -0,0 +1,7 @@
status: PUBLISHED
technologies: [Android, NDK]
categories: [NDK, C++]
languages: [C++, Java]
solutions: [Mobile]
github: googlesamples/android-ndk
license: apache2
@@ -0,0 +1,6 @@
# Oboe Tester
OboeTester is an app that can be used to test many of the features of Oboe, AAudio and OpenSL ES.
It can also be used to measure device latency and glitches.
# [OboeTester Documentation](docs)
@@ -0,0 +1,34 @@
cmake_minimum_required(VERSION 3.4.1)
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -Werror -Wall -std=c++14")
set(CMAKE_CXX_FLAGS_DEBUG "${CMAKE_CXX_FLAGS_DEBUG} -O2")
set(CMAKE_CXX_FLAGS_RELEASE "${CMAKE_CXX_FLAGS_RELEASE} -O3")
link_directories(${CMAKE_CURRENT_LIST_DIR}/..)
file(GLOB_RECURSE app_native_sources src/main/cpp/*)
### Name must match loadLibrary() call in MainActivity.java
add_library(oboetester SHARED ${app_native_sources})
### INCLUDE OBOE LIBRARY ###
# Set the path to the Oboe library directory
set (OBOE_DIR ${CMAKE_CURRENT_SOURCE_DIR}/../../..)
# Add the Oboe library as a subproject. Since Oboe is an out-of-tree source library we must also
# specify a binary directory
add_subdirectory(${OBOE_DIR} ./oboe-bin)
# Specify the path to the Oboe header files and the source.
include_directories(
${OBOE_DIR}/include
${OBOE_DIR}/src
)
### END OBOE INCLUDE SECTION ###
# link to oboe
target_link_libraries(oboetester log oboe atomic)
# bump 2 to resync CMake
@@ -0,0 +1,44 @@
apply plugin: 'com.android.application'
android {
compileSdkVersion 28
defaultConfig {
applicationId = "com.google.sample.oboe.manualtest"
minSdkVersion 23
targetSdkVersion 28
// Also update the version in the AndroidManifest.xml file.
versionCode 32
versionName "1.5.24"
testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
externalNativeBuild {
cmake {
cppFlags "-std=c++14"
abiFilters "x86", "x86_64", "armeabi-v7a", "arm64-v8a"
}
}
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}
debug {
jniDebuggable true
}
}
externalNativeBuild {
cmake {
path "CMakeLists.txt"
}
}
}
dependencies {
implementation fileTree(include: ['*.jar'], dir: 'libs')
implementation 'com.android.support.constraint:constraint-layout:2.0.0-beta4'
testImplementation 'junit:junit:4.13-beta-3'
implementation 'com.android.support:appcompat-v7:28.0.0'
androidTestImplementation 'com.android.support.test:runner:1.0.2'
androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.2'
}
@@ -0,0 +1,6 @@
#Thu Apr 11 16:29:30 PDT 2019
distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-4.10.1-all.zip
+172
View File
@@ -0,0 +1,172 @@
#!/usr/bin/env sh
##############################################################################
##
## Gradle start up script for UN*X
##
##############################################################################
# Attempt to set APP_HOME
# Resolve links: $0 may be a link
PRG="$0"
# Need this for relative symlinks.
while [ -h "$PRG" ] ; do
ls=`ls -ld "$PRG"`
link=`expr "$ls" : '.*-> \(.*\)$'`
if expr "$link" : '/.*' > /dev/null; then
PRG="$link"
else
PRG=`dirname "$PRG"`"/$link"
fi
done
SAVED="`pwd`"
cd "`dirname \"$PRG\"`/" >/dev/null
APP_HOME="`pwd -P`"
cd "$SAVED" >/dev/null
APP_NAME="Gradle"
APP_BASE_NAME=`basename "$0"`
# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
DEFAULT_JVM_OPTS=""
# Use the maximum available, or set MAX_FD != -1 to use that value.
MAX_FD="maximum"
warn () {
echo "$*"
}
die () {
echo
echo "$*"
echo
exit 1
}
# OS specific support (must be 'true' or 'false').
cygwin=false
msys=false
darwin=false
nonstop=false
case "`uname`" in
CYGWIN* )
cygwin=true
;;
Darwin* )
darwin=true
;;
MINGW* )
msys=true
;;
NONSTOP* )
nonstop=true
;;
esac
CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar
# Determine the Java command to use to start the JVM.
if [ -n "$JAVA_HOME" ] ; then
if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
# IBM's JDK on AIX uses strange locations for the executables
JAVACMD="$JAVA_HOME/jre/sh/java"
else
JAVACMD="$JAVA_HOME/bin/java"
fi
if [ ! -x "$JAVACMD" ] ; then
die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME
Please set the JAVA_HOME variable in your environment to match the
location of your Java installation."
fi
else
JAVACMD="java"
which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
Please set the JAVA_HOME variable in your environment to match the
location of your Java installation."
fi
# Increase the maximum file descriptors if we can.
if [ "$cygwin" = "false" -a "$darwin" = "false" -a "$nonstop" = "false" ] ; then
MAX_FD_LIMIT=`ulimit -H -n`
if [ $? -eq 0 ] ; then
if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then
MAX_FD="$MAX_FD_LIMIT"
fi
ulimit -n $MAX_FD
if [ $? -ne 0 ] ; then
warn "Could not set maximum file descriptor limit: $MAX_FD"
fi
else
warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT"
fi
fi
# For Darwin, add options to specify how the application appears in the dock
if $darwin; then
GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\""
fi
# For Cygwin, switch paths to Windows format before running java
if $cygwin ; then
APP_HOME=`cygpath --path --mixed "$APP_HOME"`
CLASSPATH=`cygpath --path --mixed "$CLASSPATH"`
JAVACMD=`cygpath --unix "$JAVACMD"`
# We build the pattern for arguments to be converted via cygpath
ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null`
SEP=""
for dir in $ROOTDIRSRAW ; do
ROOTDIRS="$ROOTDIRS$SEP$dir"
SEP="|"
done
OURCYGPATTERN="(^($ROOTDIRS))"
# Add a user-defined pattern to the cygpath arguments
if [ "$GRADLE_CYGPATTERN" != "" ] ; then
OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)"
fi
# Now convert the arguments - kludge to limit ourselves to /bin/sh
i=0
for arg in "$@" ; do
CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -`
CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option
if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition
eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"`
else
eval `echo args$i`="\"$arg\""
fi
i=$((i+1))
done
case $i in
(0) set -- ;;
(1) set -- "$args0" ;;
(2) set -- "$args0" "$args1" ;;
(3) set -- "$args0" "$args1" "$args2" ;;
(4) set -- "$args0" "$args1" "$args2" "$args3" ;;
(5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;;
(6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;;
(7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;;
(8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;;
(9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;;
esac
fi
# Escape application args
save () {
for i do printf %s\\n "$i" | sed "s/'/'\\\\''/g;1s/^/'/;\$s/\$/' \\\\/" ; done
echo " "
}
APP_ARGS=$(save "$@")
# Collect all arguments for the java command, following the shell quoting and substitution rules
eval set -- $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS "\"-Dorg.gradle.appname=$APP_BASE_NAME\"" -classpath "\"$CLASSPATH\"" org.gradle.wrapper.GradleWrapperMain "$APP_ARGS"
# by default we should be in the correct project dir, but when run from Finder on Mac, the cwd is wrong
if [ "$(uname)" = "Darwin" ] && [ "$HOME" = "$PWD" ]; then
cd "$(dirname "$0")"
fi
exec "$JAVACMD" "$@"
+84
View File
@@ -0,0 +1,84 @@
@if "%DEBUG%" == "" @echo off
@rem ##########################################################################
@rem
@rem Gradle startup script for Windows
@rem
@rem ##########################################################################
@rem Set local scope for the variables with windows NT shell
if "%OS%"=="Windows_NT" setlocal
set DIRNAME=%~dp0
if "%DIRNAME%" == "" set DIRNAME=.
set APP_BASE_NAME=%~n0
set APP_HOME=%DIRNAME%
@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
set DEFAULT_JVM_OPTS=
@rem Find java.exe
if defined JAVA_HOME goto findJavaFromJavaHome
set JAVA_EXE=java.exe
%JAVA_EXE% -version >NUL 2>&1
if "%ERRORLEVEL%" == "0" goto init
echo.
echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
echo.
echo Please set the JAVA_HOME variable in your environment to match the
echo location of your Java installation.
goto fail
:findJavaFromJavaHome
set JAVA_HOME=%JAVA_HOME:"=%
set JAVA_EXE=%JAVA_HOME%/bin/java.exe
if exist "%JAVA_EXE%" goto init
echo.
echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME%
echo.
echo Please set the JAVA_HOME variable in your environment to match the
echo location of your Java installation.
goto fail
:init
@rem Get command-line arguments, handling Windows variants
if not "%OS%" == "Windows_NT" goto win9xME_args
:win9xME_args
@rem Slurp the command line arguments.
set CMD_LINE_ARGS=
set _SKIP=2
:win9xME_args_slurp
if "x%~1" == "x" goto execute
set CMD_LINE_ARGS=%*
:execute
@rem Setup the command line
set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar
@rem Execute Gradle
"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS%
:end
@rem End local scope for the variables with windows NT shell
if "%ERRORLEVEL%"=="0" goto mainEnd
:fail
rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of
rem the _cmd.exe /c_ return code!
if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1
exit /b 1
:mainEnd
if "%OS%"=="Windows_NT" endlocal
:omega
@@ -0,0 +1,17 @@
# Add project specific ProGuard rules here.
# By default, the flags in this file are appended to flags specified
# in /Users/gfan/dev/android-sdk/tools/proguard/proguard-android.txt
# You can edit the include path and order by changing the proguardFiles
# directive in build.gradle.
#
# For more details, see
# http://developer.android.com/guide/developing/tools/proguard.html
# Add any project specific keep options here:
# If your project uses WebView with JS, uncomment the following
# and specify the fully qualified class name to the JavaScript interface
# class:
#-keepclassmembers class fqcn.of.javascript.interface.for.webview {
# public *;
#}
@@ -0,0 +1,119 @@
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.google.sample.oboe.manualtest"
android:versionCode="32"
android:versionName="1.5.24">
<!-- versionCode and versionName also have to be updated in build.gradle -->
<uses-feature android:name="android.hardware.microphone" android:required="true" />
<uses-feature android:name="android.hardware.audio.output" android:required="true" />
<uses-feature android:name="android.software.midi" android:required="true" />
<uses-permission android:name="android.permission.RECORD_AUDIO" />
<uses-permission android:name="android.permission.MODIFY_AUDIO_SETTINGS" />
<uses-permission android:name="android.permission.INTERNET" />
<!-- debug-writing file need external storage writing -->
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_PHONE_STATE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<application
android:allowBackup="false"
android:fullBackupContent="false"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity
android:name="com.google.sample.oboe.manualtest.MainActivity"
android:launchMode="singleTask"
android:label="@string/app_name"
android:screenOrientation="portrait">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name="com.google.sample.oboe.manualtest.TestOutputActivity"
android:label="@string/title_activity_test_output"
android:screenOrientation="portrait">
</activity>
<activity
android:name="com.google.sample.oboe.manualtest.TestInputActivity"
android:label="@string/title_activity_test_input"
android:screenOrientation="portrait">
</activity>
<activity
android:name="com.google.sample.oboe.manualtest.TapToToneActivity"
android:label="@string/title_activity_output_latency"
android:screenOrientation="portrait">
</activity>
<activity
android:name="com.google.sample.oboe.manualtest.RecorderActivity"
android:label="@string/title_activity_recorder"
android:screenOrientation="portrait">
</activity>
<activity
android:name="com.google.sample.oboe.manualtest.EchoActivity"
android:label="@string/title_activity_echo"
android:screenOrientation="portrait">
</activity>
<activity
android:name="com.google.sample.oboe.manualtest.RoundTripLatencyActivity"
android:label="@string/title_activity_rt_latency"
android:screenOrientation="portrait">
</activity>
<activity
android:name="com.google.sample.oboe.manualtest.ManualGlitchActivity"
android:label="@string/title_activity_glitches"
android:screenOrientation="portrait">
</activity>
<activity
android:name="com.google.sample.oboe.manualtest.AutoGlitchActivity"
android:label="@string/title_activity_glitches"
android:screenOrientation="portrait">
</activity>
<activity
android:name="com.google.sample.oboe.manualtest.TestDisconnectActivity"
android:label="@string/title_test_disconnect"
android:screenOrientation="portrait">
</activity>
<service
android:name="com.google.sample.oboe.manualtest.AudioMidiTester"
android:permission="android.permission.BIND_MIDI_DEVICE_SERVICE">
<intent-filter>
<action android:name="android.media.midi.MidiDeviceService" />
</intent-filter>
<meta-data
android:name="android.media.midi.MidiDeviceService"
android:resource="@xml/service_device_info" />
</service>
<provider
android:name="android.support.v4.content.FileProvider"
android:authorities="${applicationId}.provider"
android:exported="false"
android:grantUriPermissions="true">
<meta-data
android:name="android.support.FILE_PROVIDER_PATHS"
android:resource="@xml/provider_paths"/>
</provider>
</application>
</manifest>
@@ -0,0 +1,45 @@
/*
* Copyright 2016 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <cstring>
#include <sched.h>
#include "oboe/Oboe.h"
#include "AudioStreamGateway.h"
using namespace flowgraph;
oboe::DataCallbackResult AudioStreamGateway::onAudioReady(
oboe::AudioStream *audioStream,
void *audioData,
int numFrames) {
if (!mSchedulerChecked) {
mScheduler = sched_getscheduler(gettid());
mSchedulerChecked = true;
}
if (mAudioSink != nullptr) {
mAudioSink->read(mFramePosition, audioData, numFrames);
mFramePosition += numFrames;
}
return oboe::DataCallbackResult::Continue;
}
int AudioStreamGateway::getScheduler() {
return mScheduler;
}
@@ -0,0 +1,62 @@
/*
* Copyright 2016 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef NATIVEOBOE_AUDIOGRAPHRUNNER_H
#define NATIVEOBOE_AUDIOGRAPHRUNNER_H
#include <unistd.h>
#include <sys/types.h>
#include "flowgraph/FlowGraphNode.h"
#include "oboe/Oboe.h"
using namespace flowgraph;
/**
* Bridge between an audio flowgraph and an audio device.
* Pass in an AudioSink and then pass
* this object to the AudioStreamBuilder as a callback.
*/
class AudioStreamGateway : public oboe::AudioStreamCallback {
public:
// AudioStreamGateway(int samplesPerFrame);
virtual ~AudioStreamGateway() = default;
void setAudioSink(std::shared_ptr<flowgraph::FlowGraphSink> sink) {
mAudioSink = sink;
if (sink) {
mFramePosition = sink->getLastFramePosition();
}
}
/**
* Called by Oboe when the stream is ready to process audio.
*/
oboe::DataCallbackResult onAudioReady(
oboe::AudioStream *audioStream,
void *audioData,
int numFrames) override;
int getScheduler();
private:
int64_t mFramePosition = 0;
bool mSchedulerChecked = false;
int mScheduler;
std::shared_ptr<flowgraph::FlowGraphSink> mAudioSink;
};
#endif //NATIVEOBOE_AUDIOGRAPHRUNNER_H
@@ -0,0 +1,66 @@
/*
* Copyright 2019 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "common/OboeDebug.h"
#include "FullDuplexAnalyzer.h"
oboe::Result FullDuplexAnalyzer::start() {
getLoopbackProcessor()->setSampleRate(getOutputStream()->getSampleRate());
getLoopbackProcessor()->onStartTest();
return FullDuplexStream::start();
}
oboe::DataCallbackResult FullDuplexAnalyzer::onBothStreamsReady(
const void *inputData,
int numInputFrames,
void *outputData,
int numOutputFrames) {
int32_t inputStride = getInputStream()->getChannelCount();
int32_t outputStride = getOutputStream()->getChannelCount();
float *inputFloat = (float *) inputData;
float *outputFloat = (float *) outputData;
(void) getLoopbackProcessor()->process(inputFloat, inputStride, numInputFrames,
outputFloat, outputStride, numOutputFrames);
// write the first channel of output and input to the stereo recorder
if (mRecording != nullptr) {
float buffer[2];
int numBoth = std::min(numInputFrames, numOutputFrames);
for (int i = 0; i < numBoth; i++) {
buffer[0] = *outputFloat;
outputFloat += outputStride;
buffer[1] = *inputFloat;
inputFloat += inputStride;
mRecording->write(buffer, 1);
}
// Handle mismatch in in numFrames.
buffer[0] = 0.0f; // gap in output
for (int i = numBoth; i < numInputFrames; i++) {
buffer[1] = *inputFloat;
inputFloat += inputStride;
mRecording->write(buffer, 1);
}
buffer[1] = 0.0f; // gap in input
for (int i = numBoth; i < numOutputFrames; i++) {
buffer[0] = *outputFloat;
outputFloat += outputStride;
mRecording->write(buffer, 1);
}
}
return oboe::DataCallbackResult::Continue;
};
@@ -0,0 +1,62 @@
/*
* Copyright 2019 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef OBOETESTER_FULL_DUPLEX_ANALYZER_H
#define OBOETESTER_FULL_DUPLEX_ANALYZER_H
#include <unistd.h>
#include <sys/types.h>
#include "oboe/Oboe.h"
#include "FullDuplexStream.h"
#include "analyzer/LatencyAnalyzer.h"
#include "MultiChannelRecording.h"
class FullDuplexAnalyzer : public FullDuplexStream {
public:
FullDuplexAnalyzer() {}
/**
* Called when data is available on both streams.
* Caller should override this method.
*/
oboe::DataCallbackResult onBothStreamsReady(
const void *inputData,
int numInputFrames,
void *outputData,
int numOutputFrames
) override;
oboe::Result start() override;
bool isDone() {
return false;
}
virtual LoopbackProcessor *getLoopbackProcessor() = 0;
void setRecording(MultiChannelRecording *recording) {
mRecording = recording;
}
private:
MultiChannelRecording *mRecording = nullptr;
};
#endif //OBOETESTER_FULL_DUPLEX_ANALYZER_H
@@ -0,0 +1,49 @@
/*
* Copyright 2019 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "common/OboeDebug.h"
#include "FullDuplexEcho.h"
oboe::Result FullDuplexEcho::start() {
int32_t delayFrames = (int32_t) (kMaxDelayTimeSeconds * getOutputStream()->getSampleRate());
mDelayLine = std::make_unique<InterpolatingDelayLine>(delayFrames);
return FullDuplexStream::start();
}
oboe::DataCallbackResult FullDuplexEcho::onBothStreamsReady(
const void *inputData,
int numInputFrames,
void *outputData,
int numOutputFrames) {
// FIXME only handles matching stream formats.
// TODO Add delay node
// TODO use flowgraph to handle format conversion
int32_t framesToEcho = std::min(numInputFrames, numOutputFrames);
float *inputFloat = (float *)inputData;
float *outputFloat = (float *)outputData;
// zero out entire output array
memset(outputFloat, 0, numOutputFrames * getOutputStream()->getBytesPerFrame());
int32_t inputStride = getInputStream()->getChannelCount();
int32_t outputStride = getOutputStream()->getChannelCount();
float delayFrames = mDelayTimeSeconds * getOutputStream()->getSampleRate();
while (framesToEcho-- > 0) {
*outputFloat = mDelayLine->process(delayFrames, *inputFloat); // mono delay
inputFloat += inputStride;
outputFloat += outputStride;
}
return oboe::DataCallbackResult::Continue;
};
@@ -0,0 +1,57 @@
/*
* Copyright 2019 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef OBOETESTER_FULL_DUPLEX_ECHO_H
#define OBOETESTER_FULL_DUPLEX_ECHO_H
#include <unistd.h>
#include <sys/types.h>
#include "oboe/Oboe.h"
#include "FullDuplexStream.h"
#include "InterpolatingDelayLine.h"
class FullDuplexEcho : public FullDuplexStream {
public:
FullDuplexEcho() {
setMNumInputBurstsCushion(0);
}
/**
* Called when data is available on both streams.
* Caller should override this method.
*/
oboe::DataCallbackResult onBothStreamsReady(
const void *inputData,
int numInputFrames,
void *outputData,
int numOutputFrames
) override;
oboe::Result start() override;
void setDelayTime(double delayTimeSeconds) {
mDelayTimeSeconds = delayTimeSeconds;
}
private:
std::unique_ptr<InterpolatingDelayLine> mDelayLine;
static constexpr double kMaxDelayTimeSeconds = 4.0;
double mDelayTimeSeconds = kMaxDelayTimeSeconds;
};
#endif //OBOETESTER_FULL_DUPLEX_ECHO_H
@@ -0,0 +1,18 @@
/*
* Copyright 2019 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "common/OboeDebug.h"
#include "FullDuplexGlitches.h"
@@ -0,0 +1,53 @@
/*
* Copyright 2019 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef OBOETESTER_FULL_DUPLEX_GLITCHES_H
#define OBOETESTER_FULL_DUPLEX_GLITCHES_H
#include <unistd.h>
#include <sys/types.h>
#include "oboe/Oboe.h"
#include "FullDuplexAnalyzer.h"
#include "analyzer/GlitchAnalyzer.h"
class FullDuplexGlitches : public FullDuplexAnalyzer {
public:
FullDuplexGlitches() {
setMNumInputBurstsCushion(1);
}
bool isDone() {
return false;
}
GlitchAnalyzer *getGlitchAnalyzer() {
return &mGlitchAnalyzer;
}
LoopbackProcessor *getLoopbackProcessor() override {
return (LoopbackProcessor *) &mGlitchAnalyzer;
}
private:
GlitchAnalyzer mGlitchAnalyzer;
};
#endif //OBOETESTER_FULL_DUPLEX_GLITCHES_H
@@ -0,0 +1,44 @@
/*
* Copyright 2019 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <thread>
#include "common/OboeDebug.h"
#include "FullDuplexLatency.h"
static void analyze_data(FullDuplexLatency *fullDuplexLatency) {
fullDuplexLatency->analyzeData();
}
oboe::DataCallbackResult FullDuplexLatency::onBothStreamsReady(
const void *inputData,
int numInputFrames,
void *outputData,
int numOutputFrames) {
oboe::DataCallbackResult callbackResult = FullDuplexAnalyzer::onBothStreamsReady(
inputData, numInputFrames, outputData, numOutputFrames);
// Are we done?
if (mEchoAnalyzer.hasEnoughData()) {
// Crunch the numbers on a separate thread.
std::thread t(analyze_data, this);
t.detach();
callbackResult = oboe::DataCallbackResult::Stop;
}
return callbackResult;
};
@@ -0,0 +1,65 @@
/*
* Copyright 2019 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef OBOETESTER_FULL_DUPLEX_LATENCY_H
#define OBOETESTER_FULL_DUPLEX_LATENCY_H
#include <unistd.h>
#include <sys/types.h>
#include "oboe/Oboe.h"
#include "FullDuplexAnalyzer.h"
class FullDuplexLatency : public FullDuplexAnalyzer {
public:
FullDuplexLatency() {}
/**
* Called when data is available on both streams.
* Caller should override this method.
*/
oboe::DataCallbackResult onBothStreamsReady(
const void *inputData,
int numInputFrames,
void *outputData,
int numOutputFrames
) override;
bool isDone() {
return mEchoAnalyzer.isDone();
}
void analyzeData() {
mEchoAnalyzer.analyze();
}
LatencyAnalyzer *getLatencyAnalyzer() {
return &mEchoAnalyzer;
}
LoopbackProcessor *getLoopbackProcessor() override {
return (LoopbackProcessor *) &mEchoAnalyzer;
}
private:
PulseLatencyAnalyzer mEchoAnalyzer;
};
#endif //OBOETESTER_FULL_DUPLEX_LATENCY_H
@@ -0,0 +1,137 @@
/*
* Copyright 2019 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "common/OboeDebug.h"
#include "FullDuplexStream.h"
oboe::DataCallbackResult FullDuplexStream::onAudioReady(
oboe::AudioStream *outputStream,
void *audioData,
int numFrames) {
oboe::DataCallbackResult callbackResult = oboe::DataCallbackResult::Continue;
int32_t actualFramesRead = 0;
// Silence the output.
int32_t numBytes = numFrames * outputStream->getBytesPerFrame();
memset(audioData, 0 /* value */, numBytes);
if (mCountCallbacksToDrain > 0) {
// Drain the input.
int32_t totalFramesRead = 0;
do {
oboe::ResultWithValue<int32_t> result = getInputStream()->read(mInputBuffer.get(),
numFrames,
0 /* timeout */);
if (!result) {
// Ignore errors because input stream may not be started yet.
break;
}
actualFramesRead = result.value();
totalFramesRead += actualFramesRead;
} while (actualFramesRead > 0);
// Only counts if we actually got some data.
if (totalFramesRead > 0) {
mCountCallbacksToDrain--;
}
} else if (mCountInputBurstsCushion > 0) {
// Let the input fill up a bit so we are not so close to the write pointer.
mCountInputBurstsCushion--;
} else if (mCountCallbacksToDiscard > 0) {
mCountCallbacksToDiscard--;
// Ignore. Allow the input to reach to equilibrium with the output.
oboe::ResultWithValue<int32_t> resultAvailable = getInputStream()->getAvailableFrames();
if (!resultAvailable) {
LOGE("%s() getAvailableFrames() returned %s\n",
__func__, convertToText(resultAvailable.error()));
callbackResult = oboe::DataCallbackResult::Stop;
} else {
int32_t framesAvailable = resultAvailable.value();
if (framesAvailable >= mMinimumFramesBeforeRead) {
oboe::ResultWithValue<int32_t> resultRead = getInputStream()->read(mInputBuffer.get(), numFrames, 0 /* timeout */);
if (!resultRead) {
LOGE("%s() read() returned %s\n", __func__, convertToText(resultRead.error()));
callbackResult = oboe::DataCallbackResult::Stop;
}
}
}
} else {
int32_t framesRead = 0;
oboe::ResultWithValue<int32_t> resultAvailable = getInputStream()->getAvailableFrames();
if (!resultAvailable) {
LOGE("%s() getAvailableFrames() returned %s\n", __func__, convertToText(resultAvailable.error()));
callbackResult = oboe::DataCallbackResult::Stop;
} else {
int32_t framesAvailable = resultAvailable.value();
if (framesAvailable >= mMinimumFramesBeforeRead) {
// Read data into input buffer.
oboe::ResultWithValue<int32_t> resultRead = getInputStream()->read(mInputBuffer.get(), numFrames, 0 /* timeout */);
if (!resultRead) {
LOGE("%s() read() returned %s\n", __func__, convertToText(resultRead.error()));
callbackResult = oboe::DataCallbackResult::Stop;
} else {
framesRead = resultRead.value();
}
}
}
if (callbackResult == oboe::DataCallbackResult::Continue) {
callbackResult = onBothStreamsReady(
mInputBuffer.get(), framesRead,
audioData, numFrames);
}
}
if (callbackResult == oboe::DataCallbackResult::Stop) {
getInputStream()->requestStop();
}
return callbackResult;
}
oboe::Result FullDuplexStream::start() {
mCountCallbacksToDrain = kNumCallbacksToDrain;
mCountInputBurstsCushion = mNumInputBurstsCushion;
mCountCallbacksToDiscard = kNumCallbacksToDiscard;
// Determine maximum size that could possibly be called.
int32_t bufferSize = getOutputStream()->getBufferCapacityInFrames()
* getOutputStream()->getChannelCount();
if (bufferSize > mBufferSize) {
mInputBuffer = std::make_unique<float[]>(bufferSize);
mBufferSize = bufferSize;
}
oboe::Result result = getInputStream()->requestStart();
if (result != oboe::Result::OK) {
return result;
}
return getOutputStream()->requestStart();
}
oboe::Result FullDuplexStream::stop() {
getOutputStream()->requestStop(); // TODO result?
return getInputStream()->requestStop();
}
int32_t FullDuplexStream::getMNumInputBurstsCushion() const {
return mNumInputBurstsCushion;
}
void FullDuplexStream::setMNumInputBurstsCushion(int32_t numBursts) {
FullDuplexStream::mNumInputBurstsCushion = numBursts;
}
@@ -0,0 +1,115 @@
/*
* Copyright 2019 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef OBOETESTER_FULL_DUPLEX_STREAM_H
#define OBOETESTER_FULL_DUPLEX_STREAM_H
#include <unistd.h>
#include <sys/types.h>
#include "oboe/Oboe.h"
class FullDuplexStream : public oboe::AudioStreamCallback {
public:
FullDuplexStream() {}
virtual ~FullDuplexStream() = default;
void setInputStream(oboe::AudioStream *stream) {
mInputStream = stream;
}
oboe::AudioStream *getInputStream() {
return mInputStream;
}
void setOutputStream(oboe::AudioStream *stream) {
mOutputStream = stream;
}
oboe::AudioStream *getOutputStream() {
return mOutputStream;
}
virtual oboe::Result start();
virtual oboe::Result stop();
/**
* Called when data is available on both streams.
* Caller should override this method.
*/
virtual oboe::DataCallbackResult onBothStreamsReady(
const void *inputData,
int numInputFrames,
void *outputData,
int numOutputFrames
) = 0;
/**
* Called by Oboe when the stream is ready to process audio.
*/
oboe::DataCallbackResult onAudioReady(
oboe::AudioStream *audioStream,
void *audioData,
int numFrames) override;
int32_t getMNumInputBurstsCushion() const;
/**
* Number of bursts to leave in the input buffer as a cushion.
* Typically 0 for latency measurements
* or 1 for glitch tests.
*
* @param mNumInputBurstsCushion
*/
void setMNumInputBurstsCushion(int32_t mNumInputBurstsCushion);
void setMinimumFramesBeforeRead(int32_t numFrames) {
mMinimumFramesBeforeRead = numFrames;
}
int32_t getMinimumFramesBeforeRead() const {
return mMinimumFramesBeforeRead;
}
private:
// TODO add getters and setters
static constexpr int32_t kNumCallbacksToDrain = 20;
static constexpr int32_t kNumCallbacksToDiscard = 30;
// let input fill back up, usually 0 or 1
int32_t mNumInputBurstsCushion = 0;
int32_t mMinimumFramesBeforeRead = 0;
// We want to reach a state where the input buffer is empty and
// the output buffer is full.
// These are used in order.
// Drain several callback so that input is empty.
int32_t mCountCallbacksToDrain = kNumCallbacksToDrain;
// Let the input fill back up slightly so we don't run dry.
int32_t mCountInputBurstsCushion = mNumInputBurstsCushion;
// Discard some callbacks so the input and output reach equilibrium.
int32_t mCountCallbacksToDiscard = kNumCallbacksToDiscard;
oboe::AudioStream *mInputStream = nullptr;
oboe::AudioStream *mOutputStream = nullptr;
int32_t mBufferSize = 0;
std::unique_ptr<float[]> mInputBuffer;
};
#endif //OBOETESTER_FULL_DUPLEX_STREAM_H
@@ -0,0 +1,57 @@
/*
* Copyright 2015 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "common/OboeDebug.h"
#include "InputStreamCallbackAnalyzer.h"
oboe::DataCallbackResult InputStreamCallbackAnalyzer::onAudioReady(
oboe::AudioStream *audioStream,
void *audioData,
int numFrames) {
int32_t channelCount = audioStream->getChannelCount();
if (audioStream->getFormat() == oboe::AudioFormat::I16) {
int16_t *shortData = (int16_t *) audioData;
if (mRecording != nullptr) {
mRecording->write(shortData, numFrames);
}
int16_t *frameData = shortData;
for (int iFrame = 0; iFrame < numFrames; iFrame++) {
for (int iChannel = 0; iChannel < channelCount; iChannel++) {
float sample = frameData[iChannel] / 32768.0f;
mPeakDetectors[iChannel].process(sample);
}
frameData += channelCount;
}
} else if (audioStream->getFormat() == oboe::AudioFormat::Float) {
float *floatData = (float *) audioData;
if (mRecording != nullptr) {
mRecording->write(floatData, numFrames);
}
float *frameData = floatData;
for (int iFrame = 0; iFrame < numFrames; iFrame++) {
for (int iChannel = 0; iChannel < channelCount; iChannel++) {
float sample = frameData[iChannel];
mPeakDetectors[iChannel].process(sample);
}
frameData += channelCount;
}
}
audioStream->waitForAvailableFrames(mMinimumFramesBeforeRead, oboe::kNanosPerSecond);
return oboe::DataCallbackResult::Continue;
}
@@ -0,0 +1,72 @@
/*
* Copyright 2016 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef NATIVEOBOE_INPUTSTREAMCALLBACKANALYZER_H
#define NATIVEOBOE_INPUTSTREAMCALLBACKANALYZER_H
#include <unistd.h>
#include <sys/types.h>
// TODO #include "flowgraph/FlowGraph.h"
#include "oboe/Oboe.h"
#include "MultiChannelRecording.h"
#include "analyzer/PeakDetector.h"
constexpr int kMaxInputChannels = 8;
class InputStreamCallbackAnalyzer : public oboe::AudioStreamCallback {
public:
void reset() {
for (auto detector : mPeakDetectors) {
detector.reset();
}
}
/**
* Called by Oboe when the stream is ready to process audio.
*/
oboe::DataCallbackResult onAudioReady(
oboe::AudioStream *audioStream,
void *audioData,
int numFrames) override;
void setRecording(MultiChannelRecording *recording) {
mRecording = recording;
}
double getPeakLevel(int index) {
return mPeakDetectors[index].getLevel();
}
void setMinimumFramesBeforeRead(int32_t numFrames) {
mMinimumFramesBeforeRead = numFrames;
}
int32_t getMinimumFramesBeforeRead() {
return mMinimumFramesBeforeRead;
}
public:
PeakDetector mPeakDetectors[kMaxInputChannels];
MultiChannelRecording *mRecording = nullptr;
private:
int32_t mMinimumFramesBeforeRead = 0;
};
#endif //NATIVEOBOE_INPUTSTREAMCALLBACKANALYZER_H
@@ -0,0 +1,42 @@
/*
* Copyright 2019 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "common/OboeDebug.h"
#include "InterpolatingDelayLine.h"
InterpolatingDelayLine::InterpolatingDelayLine(int32_t delaySize) {
mDelaySize = delaySize;
mDelayLine = std::make_unique<float[]>(delaySize);
}
float InterpolatingDelayLine::process(float delay, float input) {
float *writeAddress = mDelayLine.get() + mCursor;
*writeAddress = input;
mDelayLine.get()[mCursor] = input;
int32_t delayInt = std::min(mDelaySize - 1, (int32_t) delay);
int32_t readIndex = mCursor - delayInt;
if (readIndex < 0) {
readIndex += mDelaySize;
}
// TODO interpolate
float *readAddress = mDelayLine.get() + readIndex;
float output = *readAddress;
mCursor++;
if (mCursor >= mDelaySize) {
mCursor = 0;
}
return output;
};
@@ -0,0 +1,48 @@
/*
* Copyright 2019 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef OBOETESTER_INTERPOLATING_DELAY_LINE_H
#define OBOETESTER_INTERPOLATING_DELAY_LINE_H
#include <memory>
#include <unistd.h>
#include <sys/types.h>
#include "oboe/Oboe.h"
#include "FullDuplexStream.h"
/**
* Monophonic delay line.
*/
class InterpolatingDelayLine {
public:
explicit InterpolatingDelayLine(int32_t delaySize);
/**
* @param input sample to be written to the delay line
* @param delay number of samples to delay the output
* @return delayed value
*/
float process(float delay, float input);
private:
std::unique_ptr<float[]> mDelayLine;
int32_t mCursor = 0;
int32_t mDelaySize = 0;
};
#endif //OBOETESTER_INTERPOLATING_DELAY_LINE_H
@@ -0,0 +1,161 @@
/*
* Copyright 2015 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef NATIVEOBOE_MULTICHANNEL_RECORDING_H
#define NATIVEOBOE_MULTICHANNEL_RECORDING_H
#include <memory.h>
#include <unistd.h>
#include <sys/types.h>
/**
* Store multi-channel audio data in float format.
* The most recent data will be saved.
* Old data may be overwritten.
*
* Note that this is not thread safe. Do not read and write from separate threads.
*/
class MultiChannelRecording {
public:
MultiChannelRecording(int32_t channelCount, int32_t maxFrames)
: mChannelCount(channelCount)
, mMaxFrames(maxFrames) {
mData = new float[channelCount * maxFrames];
}
~MultiChannelRecording() {
delete[] mData;
}
void rewind() {
mReadCursorFrames = mWriteCursorFrames - getSizeInFrames();
}
void clear() {
mReadCursorFrames = 0;
mWriteCursorFrames = 0;
}
int32_t getChannelCount() {
return mChannelCount;
}
int32_t getSizeInFrames() {
return (int32_t) std::min(mWriteCursorFrames, static_cast<int64_t>(mMaxFrames));
}
int32_t getReadIndex() {
return mReadCursorFrames % mMaxFrames;
}
int32_t getWriteIndex() {
return mWriteCursorFrames % mMaxFrames;
}
/**
* Write numFrames from the short buffer into the recording.
* Overwrite old data if necessary.
* Convert shorts to floats.
*
* @param buffer
* @param numFrames
* @return number of frames actually written.
*/
int32_t write(int16_t *buffer, int32_t numFrames) {
int32_t framesLeft = numFrames;
while (framesLeft > 0) {
int32_t indexFrame = getWriteIndex();
// contiguous writes
int32_t framesToEndOfBuffer = mMaxFrames - indexFrame;
int32_t framesNow = std::min(framesLeft, framesToEndOfBuffer);
int32_t numSamples = framesNow * mChannelCount;
int32_t sampleIndex = indexFrame * mChannelCount;
for (int i = 0; i < numSamples; i++) {
mData[sampleIndex++] = *buffer++ * (1.0f / 32768);
}
mWriteCursorFrames += framesNow;
framesLeft -= framesNow;
}
return numFrames - framesLeft;
}
/**
* Write all numFrames from the float buffer into the recording.
* Overwrite old data if full.
* @param buffer
* @param numFrames
* @return number of frames actually written.
*/
int32_t write(float *buffer, int32_t numFrames) {
int32_t framesLeft = numFrames;
while (framesLeft > 0) {
int32_t indexFrame = getWriteIndex();
// contiguous writes
int32_t framesToEnd = mMaxFrames - indexFrame;
int32_t framesNow = std::min(framesLeft, framesToEnd);
int32_t numSamples = framesNow * mChannelCount;
int32_t sampleIndex = indexFrame * mChannelCount;
memcpy(&mData[sampleIndex],
buffer,
(numSamples * sizeof(float)));
buffer += numSamples;
mWriteCursorFrames += framesNow;
framesLeft -= framesNow;
}
return numFrames;
}
/**
* Read numFrames from the recording into the buffer, if there is enough data.
* Start at the cursor position, aligned up to the next frame.
* @param buffer
* @param numFrames
* @return number of frames actually read.
*/
int32_t read(float *buffer, int32_t numFrames) {
int32_t framesRead = 0;
int32_t framesLeft = std::min(numFrames,
std::min(mMaxFrames, (int32_t)(mWriteCursorFrames - mReadCursorFrames)));
while (framesLeft > 0) {
int32_t indexFrame = getReadIndex();
// contiguous reads
int32_t framesToEnd = mMaxFrames - indexFrame;
int32_t framesNow = std::min(framesLeft, framesToEnd);
int32_t numSamples = framesNow * mChannelCount;
int32_t sampleIndex = indexFrame * mChannelCount;
memcpy(buffer,
&mData[sampleIndex],
(numSamples * sizeof(float)));
mReadCursorFrames += framesNow;
framesLeft -= framesNow;
framesRead += framesNow;
}
return framesRead;
}
private:
float *mData = nullptr;
int64_t mReadCursorFrames = 0;
int64_t mWriteCursorFrames = 0; // monotonically increasing
const int32_t mChannelCount;
const int32_t mMaxFrames;
};
#endif //NATIVEOBOE_MULTICHANNEL_RECORDING_H
@@ -0,0 +1,619 @@
/*
* Copyright 2017 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <fstream>
#include <iostream>
#include <vector>
#include "util/WaveFileWriter.h"
#include "NativeAudioContext.h"
using namespace oboe;
static oboe::AudioApi convertNativeApiToAudioApi(int nativeApi) {
switch (nativeApi) {
default:
case NATIVE_MODE_UNSPECIFIED:
return oboe::AudioApi::Unspecified;
case NATIVE_MODE_AAUDIO:
return oboe::AudioApi::AAudio;
case NATIVE_MODE_OPENSLES:
return oboe::AudioApi::OpenSLES;
}
}
class MyOboeOutputStream : public WaveFileOutputStream {
public:
void write(uint8_t b) override {
mData.push_back(b);
}
int32_t length() {
return (int32_t) mData.size();
}
uint8_t *getData() {
return mData.data();
}
private:
std::vector<uint8_t> mData;
};
bool ActivityContext::mUseCallback = true;
int ActivityContext::callbackSize = 0;
oboe::AudioStream * ActivityContext::getOutputStream() {
for (auto entry : mOboeStreams) {
oboe::AudioStream *oboeStream = entry.second.get();
if (oboeStream->getDirection() == oboe::Direction::Output) {
return oboeStream;
}
}
return nullptr;
}
oboe::AudioStream * ActivityContext::getInputStream() {
for (auto entry : mOboeStreams) {
oboe::AudioStream *oboeStream = entry.second.get();
if (oboeStream != nullptr) {
if (oboeStream->getDirection() == oboe::Direction::Input) {
return oboeStream;
}
}
}
return nullptr;
}
void ActivityContext::freeStreamIndex(int32_t streamIndex) {
mOboeStreams[streamIndex].reset();
mOboeStreams.erase(streamIndex);
}
int32_t ActivityContext::allocateStreamIndex() {
return mNextStreamHandle++;
}
void ActivityContext::close(int32_t streamIndex) {
stopBlockingIOThread();
oboe::AudioStream *oboeStream = getStream(streamIndex);
if (oboeStream != nullptr) {
oboeStream->close();
LOGD("ActivityContext::%s() delete stream %d ", __func__, streamIndex);
freeStreamIndex(streamIndex);
}
}
bool ActivityContext::isMMapUsed(int32_t streamIndex) {
oboe::AudioStream *oboeStream = getStream(streamIndex);
if (oboeStream == nullptr) return false;
if (oboeStream->getAudioApi() != AudioApi::AAudio) return false;
return AAudioExtensions::getInstance().isMMapUsed(oboeStream);
}
oboe::Result ActivityContext::pause() {
oboe::Result result = oboe::Result::OK;
stopBlockingIOThread();
for (auto entry : mOboeStreams) {
oboe::AudioStream *oboeStream = entry.second.get();
result = oboeStream->requestPause();
printScheduler();
}
return result;
}
oboe::Result ActivityContext::stopAllStreams() {
oboe::Result result = oboe::Result::OK;
stopBlockingIOThread();
for (auto entry : mOboeStreams) {
oboe::AudioStream *oboeStream = entry.second.get();
result = oboeStream->requestStop();
printScheduler();
}
return result;
}
void ActivityContext::configureBuilder(bool isInput, oboe::AudioStreamBuilder &builder) {
// We needed the proxy because we did not know the channelCount when we setup the Builder.
if (mUseCallback) {
LOGD("ActivityContext::open() set callback to use oboeCallbackProxy, callback size = %d",
callbackSize);
builder.setCallback(&oboeCallbackProxy);
builder.setFramesPerCallback(callbackSize);
}
}
int ActivityContext::open(jint nativeApi,
jint sampleRate,
jint channelCount,
jint format,
jint sharingMode,
jint performanceMode,
jint inputPreset,
jint deviceId,
jint sessionId,
jint framesPerBurst,
jboolean channelConversionAllowed,
jboolean formatConversionAllowed,
jint rateConversionQuality,
jboolean isMMap,
jboolean isInput) {
oboe::AudioApi audioApi = oboe::AudioApi::Unspecified;
switch (nativeApi) {
case NATIVE_MODE_UNSPECIFIED:
case NATIVE_MODE_AAUDIO:
case NATIVE_MODE_OPENSLES:
audioApi = convertNativeApiToAudioApi(nativeApi);
break;
default:
return (jint) oboe::Result::ErrorOutOfRange;
}
int32_t streamIndex = allocateStreamIndex();
if (streamIndex < 0) {
LOGE("ActivityContext::open() stream array full");
return (jint) oboe::Result::ErrorNoFreeHandles;
}
if (channelCount < 0 || channelCount > 256) {
LOGE("ActivityContext::open() channels out of range");
return (jint) oboe::Result::ErrorOutOfRange;
}
// Create an audio stream.
oboe::AudioStreamBuilder builder;
builder.setChannelCount(channelCount)
->setDirection(isInput ? oboe::Direction::Input : oboe::Direction::Output)
->setSharingMode((oboe::SharingMode) sharingMode)
->setPerformanceMode((oboe::PerformanceMode) performanceMode)
->setInputPreset((oboe::InputPreset)inputPreset)
->setDeviceId(deviceId)
->setSessionId((oboe::SessionId) sessionId)
->setSampleRate(sampleRate)
->setFormat((oboe::AudioFormat) format)
->setChannelConversionAllowed(channelConversionAllowed)
->setFormatConversionAllowed(formatConversionAllowed)
->setSampleRateConversionQuality((oboe::SampleRateConversionQuality) rateConversionQuality)
;
configureBuilder(isInput, builder);
builder.setAudioApi(audioApi);
// Temporarily set the AAudio MMAP policy to disable MMAP or not.
bool oldMMapEnabled = AAudioExtensions::getInstance().isMMapEnabled();
AAudioExtensions::getInstance().setMMapEnabled(isMMap);
// Open a stream based on the builder settings.
std::shared_ptr<oboe::AudioStream> oboeStream;
Result result = builder.openStream(oboeStream);
AAudioExtensions::getInstance().setMMapEnabled(oldMMapEnabled);
if (result != Result::OK) {
freeStreamIndex(streamIndex);
streamIndex = -1;
} else {
mOboeStreams[streamIndex] = oboeStream; // save shared_ptr
mChannelCount = oboeStream->getChannelCount(); // FIXME store per stream
mFramesPerBurst = oboeStream->getFramesPerBurst();
mSampleRate = oboeStream->getSampleRate();
createRecording();
finishOpen(isInput, oboeStream.get());
}
if (!mUseCallback) {
int numSamples = getFramesPerBlock() * mChannelCount;
dataBuffer = std::make_unique<float[]>(numSamples);
}
return (result != Result::OK) ? (int)result : streamIndex;
}
oboe::Result ActivityContext::start() {
oboe::Result result = oboe::Result::OK;
oboe::AudioStream *inputStream = getInputStream();
oboe::AudioStream *outputStream = getOutputStream();
if (inputStream == nullptr && outputStream == nullptr) {
LOGD("%s() - no streams defined", __func__);
return oboe::Result::ErrorInvalidState; // not open
}
configureForStart();
result = startStreams();
if (!mUseCallback && result == oboe::Result::OK) {
// Instead of using the callback, start a thread that writes the stream.
threadEnabled.store(true);
dataThread = new std::thread(threadCallback, this);
}
return result;
}
int32_t ActivityContext::saveWaveFile(const char *filename) {
if (mRecording == nullptr) {
LOGW("ActivityContext::saveWaveFile(%s) but no recording!", filename);
return -1;
}
if (mRecording->getSizeInFrames() == 0) {
LOGW("ActivityContext::saveWaveFile(%s) but no frames!", filename);
return -2;
}
MyOboeOutputStream outStream;
WaveFileWriter writer(&outStream);
writer.setFrameRate(mSampleRate);
writer.setSamplesPerFrame(mRecording->getChannelCount());
writer.setBitsPerSample(24);
float buffer[mRecording->getChannelCount()];
// Read samples from start to finish.
mRecording->rewind();
for (int32_t frameIndex = 0; frameIndex < mRecording->getSizeInFrames(); frameIndex++) {
mRecording->read(buffer, 1 /* numFrames */);
for (int32_t i = 0; i < mRecording->getChannelCount(); i++) {
writer.write(buffer[i]);
}
}
writer.close();
if (outStream.length() > 0) {
auto myfile = std::ofstream(filename, std::ios::out | std::ios::binary);
myfile.write((char *) outStream.getData(), outStream.length());
myfile.close();
}
return outStream.length();
}
// =================================================================== ActivityTestOutput
void ActivityTestOutput::close(int32_t streamIndex) {
ActivityContext::close(streamIndex);
manyToMulti.reset(nullptr);
monoToMulti.reset(nullptr);
mSinkFloat.reset();
mSinkI16.reset();
}
void ActivityTestOutput::setChannelEnabled(int channelIndex, bool enabled) {
if (manyToMulti == nullptr) {
return;
}
if (enabled) {
switch (mSignalType) {
case SignalType::Sine:
sineOscillators[channelIndex].frequency.disconnect();
sineOscillators[channelIndex].output.connect(manyToMulti->inputs[channelIndex].get());
break;
case SignalType::Sawtooth:
sawtoothOscillators[channelIndex].output.connect(manyToMulti->inputs[channelIndex].get());
break;
case SignalType::FreqSweep:
mLinearShape.output.connect(&sineOscillators[channelIndex].frequency);
sineOscillators[channelIndex].output.connect(manyToMulti->inputs[channelIndex].get());
break;
case SignalType::PitchSweep:
mExponentialShape.output.connect(&sineOscillators[channelIndex].frequency);
sineOscillators[channelIndex].output.connect(manyToMulti->inputs[channelIndex].get());
break;
default:
break;
}
} else {
manyToMulti->inputs[channelIndex]->disconnect();
}
}
void ActivityTestOutput::configureForStart() {
manyToMulti = std::make_unique<ManyToMultiConverter>(mChannelCount);
mSinkFloat = std::make_unique<SinkFloat>(mChannelCount);
mSinkI16 = std::make_unique<SinkI16>(mChannelCount);
oboe::AudioStream *outputStream = getOutputStream();
mTriangleOscillator.setSampleRate(outputStream->getSampleRate());
mTriangleOscillator.frequency.setValue(1.0/kSweepPeriod);
mTriangleOscillator.amplitude.setValue(1.0);
mTriangleOscillator.setPhase(-1.0);
mLinearShape.setMinimum(0.0);
mLinearShape.setMaximum(outputStream->getSampleRate() * 0.5); // Nyquist
mExponentialShape.setMinimum(110.0);
mExponentialShape.setMaximum(outputStream->getSampleRate() * 0.5); // Nyquist
mTriangleOscillator.output.connect(&(mLinearShape.input));
mTriangleOscillator.output.connect(&(mExponentialShape.input));
{
double frequency = 330.0;
for (int i = 0; i < mChannelCount; i++) {
sineOscillators[i].setSampleRate(outputStream->getSampleRate());
sineOscillators[i].frequency.setValue(frequency);
frequency *= 4.0 / 3.0; // each sine is at a higher frequency
sineOscillators[i].amplitude.setValue(AMPLITUDE_SINE);
setChannelEnabled(i, true);
}
}
manyToMulti->output.connect(&(mSinkFloat.get()->input));
manyToMulti->output.connect(&(mSinkI16.get()->input));
// Clear framePosition in sine oscillators.
mSinkFloat->pullReset();
mSinkI16->pullReset();
configureStreamGateway();
}
void ActivityTestOutput::configureStreamGateway() {
oboe::AudioStream *outputStream = getOutputStream();
if (outputStream->getFormat() == oboe::AudioFormat::I16) {
audioStreamGateway.setAudioSink(mSinkI16);
} else if (outputStream->getFormat() == oboe::AudioFormat::Float) {
audioStreamGateway.setAudioSink(mSinkFloat);
}
if (mUseCallback) {
oboeCallbackProxy.setCallback(&audioStreamGateway);
}
}
void ActivityTestOutput::runBlockingIO() {
int32_t framesPerBlock = getFramesPerBlock();
oboe::DataCallbackResult callbackResult = oboe::DataCallbackResult::Continue;
oboe::AudioStream *oboeStream = getOutputStream();
if (oboeStream == nullptr) {
LOGE("%s() : no stream found\n", __func__);
return;
}
while (threadEnabled.load()
&& callbackResult == oboe::DataCallbackResult::Continue) {
// generate output by calling the callback
callbackResult = audioStreamGateway.onAudioReady(oboeStream,
dataBuffer.get(),
framesPerBlock);
auto result = oboeStream->write(dataBuffer.get(),
framesPerBlock,
NANOS_PER_SECOND);
if (!result) {
LOGE("%s() returned %s\n", __func__, convertToText(result.error()));
break;
}
int32_t framesWritten = result.value();
if (framesWritten < framesPerBlock) {
LOGE("%s() : write() wrote %d of %d\n", __func__, framesWritten, framesPerBlock);
break;
}
}
}
// ======================================================================= ActivityTestInput
void ActivityTestInput::configureForStart() {
mInputAnalyzer.reset();
if (mUseCallback) {
oboeCallbackProxy.setCallback(&mInputAnalyzer);
}
mInputAnalyzer.setRecording(mRecording.get());
}
void ActivityTestInput::runBlockingIO() {
int32_t framesPerBlock = getFramesPerBlock();
oboe::DataCallbackResult callbackResult = oboe::DataCallbackResult::Continue;
oboe::AudioStream *oboeStream = getInputStream();
if (oboeStream == nullptr) {
LOGE("%s() : no stream found\n", __func__);
return;
}
while (threadEnabled.load()
&& callbackResult == oboe::DataCallbackResult::Continue) {
// Avoid glitches by waiting until there is extra data in the FIFO.
auto err = oboeStream->waitForAvailableFrames(mMinimumFramesBeforeRead, kNanosPerSecond);
if (!err) break;
// read from input
auto result = oboeStream->read(dataBuffer.get(),
framesPerBlock,
NANOS_PER_SECOND);
if (!result) {
LOGE("%s() : read() returned %s\n", __func__, convertToText(result.error()));
break;
}
int32_t framesRead = result.value();
if (framesRead < framesPerBlock) { // timeout?
LOGE("%s() : read() read %d of %d\n", __func__, framesRead, framesPerBlock);
break;
}
// analyze input
callbackResult = mInputAnalyzer.onAudioReady(oboeStream,
dataBuffer.get(),
framesRead);
}
}
oboe::Result ActivityRecording::stopPlayback() {
oboe::Result result = oboe::Result::OK;
if (playbackStream != nullptr) {
result = playbackStream->requestStop();
playbackStream->close();
mPlayRecordingCallback.setRecording(nullptr);
delete playbackStream;
playbackStream = nullptr;
}
return result;
}
oboe::Result ActivityRecording::startPlayback() {
stop();
oboe::AudioStreamBuilder builder;
builder.setChannelCount(mChannelCount)
->setSampleRate(mSampleRate)
->setFormat(oboe::AudioFormat::Float)
->setCallback(&mPlayRecordingCallback)
->setAudioApi(oboe::AudioApi::OpenSLES);
oboe::Result result = builder.openStream(&playbackStream);
if (result != oboe::Result::OK) {
delete playbackStream;
playbackStream = nullptr;
} else if (playbackStream != nullptr) {
if (mRecording != nullptr) {
mRecording->rewind();
mPlayRecordingCallback.setRecording(mRecording.get());
result = playbackStream->requestStart();
}
}
return result;
}
// ======================================================================= ActivityTapToTone
void ActivityTapToTone::configureForStart() {
monoToMulti = std::make_unique<MonoToMultiConverter>(mChannelCount);
mSinkFloat = std::make_unique<SinkFloat>(mChannelCount);
mSinkI16 = std::make_unique<SinkI16>(mChannelCount);
oboe::AudioStream *outputStream = getOutputStream();
sawPingGenerator.setSampleRate(outputStream->getSampleRate());
sawPingGenerator.frequency.setValue(FREQUENCY_SAW_PING);
sawPingGenerator.amplitude.setValue(AMPLITUDE_SAW_PING);
sawPingGenerator.output.connect(&(monoToMulti->input));
monoToMulti->output.connect(&(mSinkFloat.get()->input));
monoToMulti->output.connect(&(mSinkI16.get()->input));
sawPingGenerator.setEnabled(false);
configureStreamGateway();
}
// ======================================================================= ActivityRoundTripLatency
void ActivityFullDuplex::configureBuilder(bool isInput, oboe::AudioStreamBuilder &builder) {
if (isInput) {
// Ideally the output streams should be opened first.
oboe::AudioStream *outputStream = getOutputStream();
if (outputStream != nullptr) {
// Make sure the capacity is bigger than two bursts.
int32_t burst = outputStream->getFramesPerBurst();
builder.setBufferCapacityInFrames(2 * burst);
}
}
}
// ======================================================================= ActivityEcho
void ActivityEcho::configureBuilder(bool isInput, oboe::AudioStreamBuilder &builder) {
ActivityFullDuplex::configureBuilder(isInput, builder);
if (mFullDuplexEcho.get() == nullptr) {
mFullDuplexEcho = std::make_unique<FullDuplexEcho>();
}
// only output uses a callback, input is polled
if (!isInput) {
builder.setCallback(mFullDuplexEcho.get());
}
}
void ActivityEcho::finishOpen(bool isInput, oboe::AudioStream *oboeStream) {
if (isInput) {
mFullDuplexEcho->setInputStream(oboeStream);
} else {
mFullDuplexEcho->setOutputStream(oboeStream);
}
}
// ======================================================================= ActivityRoundTripLatency
void ActivityRoundTripLatency::configureBuilder(bool isInput, oboe::AudioStreamBuilder &builder) {
ActivityFullDuplex::configureBuilder(isInput, builder);
if (mFullDuplexLatency.get() == nullptr) {
mFullDuplexLatency = std::make_unique<FullDuplexLatency>();
}
if (!isInput) {
// only output uses a callback, input is polled
builder.setCallback(mFullDuplexLatency.get());
}
}
void ActivityRoundTripLatency::finishOpen(bool isInput, oboe::AudioStream *oboeStream) {
if (isInput) {
mFullDuplexLatency->setInputStream(oboeStream);
mFullDuplexLatency->setRecording(mRecording.get());
} else {
mFullDuplexLatency->setOutputStream(oboeStream);
}
}
// ======================================================================= ActivityGlitches
void ActivityGlitches::configureBuilder(bool isInput, oboe::AudioStreamBuilder &builder) {
ActivityFullDuplex::configureBuilder(isInput, builder);
if (mFullDuplexGlitches.get() == nullptr) {
mFullDuplexGlitches = std::make_unique<FullDuplexGlitches>();
}
if (!isInput) {
// only output uses a callback, input is polled
builder.setCallback(mFullDuplexGlitches.get());
}
}
void ActivityGlitches::finishOpen(bool isInput, oboe::AudioStream *oboeStream) {
if (isInput) {
mFullDuplexGlitches->setInputStream(oboeStream);
mFullDuplexGlitches->setRecording(mRecording.get());
} else {
mFullDuplexGlitches->setOutputStream(oboeStream);
}
}
// =================================================================== ActivityTestDisconnect
void ActivityTestDisconnect::close(int32_t streamIndex) {
ActivityContext::close(streamIndex);
mSinkFloat.reset();
}
void ActivityTestDisconnect::configureForStart() {
oboe::AudioStream *outputStream = getOutputStream();
oboe::AudioStream *inputStream = getInputStream();
if (outputStream) {
mSinkFloat = std::make_unique<SinkFloat>(mChannelCount);
sineOscillator = std::make_unique<SineOscillator>();
monoToMulti = std::make_unique<MonoToMultiConverter>(mChannelCount);
sineOscillator->setSampleRate(outputStream->getSampleRate());
sineOscillator->frequency.setValue(440.0);
sineOscillator->amplitude.setValue(AMPLITUDE_SINE);
sineOscillator->output.connect(&(monoToMulti->input));
monoToMulti->output.connect(&(mSinkFloat->input));
// Clear framePosition in sine oscillators.
mSinkFloat->pullReset();
audioStreamGateway.setAudioSink(mSinkFloat);
} else if (inputStream) {
audioStreamGateway.setAudioSink(nullptr);
}
oboeCallbackProxy.setCallback(&audioStreamGateway);
}
@@ -0,0 +1,718 @@
/*
* Copyright 2015 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef NATIVEOBOE_NATIVEAUDIOCONTEXT_H
#define NATIVEOBOE_NATIVEAUDIOCONTEXT_H
#include <dlfcn.h>
#include <jni.h>
#include <sys/system_properties.h>
#include <thread>
#include <unordered_map>
#include <vector>
#include "common/OboeDebug.h"
#include "oboe/Oboe.h"
#include "AudioStreamGateway.h"
#include "flowunits/ImpulseOscillator.h"
#include "flowgraph/ManyToMultiConverter.h"
#include "flowgraph/MonoToMultiConverter.h"
#include "flowgraph/SinkFloat.h"
#include "flowgraph/SinkI16.h"
#include "flowunits/ExponentialShape.h"
#include "flowunits/LinearShape.h"
#include "flowunits/SineOscillator.h"
#include "flowunits/SawtoothOscillator.h"
#include "FullDuplexEcho.h"
#include "FullDuplexGlitches.h"
#include "FullDuplexLatency.h"
#include "FullDuplexStream.h"
#include "InputStreamCallbackAnalyzer.h"
#include "MultiChannelRecording.h"
#include "OboeStreamCallbackProxy.h"
#include "PlayRecordingCallback.h"
#include "SawPingGenerator.h"
#include "flowunits/TriangleOscillator.h"
// These must match order in strings.xml and in StreamConfiguration.java
#define NATIVE_MODE_UNSPECIFIED 0
#define NATIVE_MODE_OPENSLES 1
#define NATIVE_MODE_AAUDIO 2
#define MAX_SINE_OSCILLATORS 8
#define AMPLITUDE_SINE 1.0
#define AMPLITUDE_SAWTOOTH 0.5
#define FREQUENCY_SAW_PING 800.0
#define AMPLITUDE_SAW_PING 0.8
#define AMPLITUDE_IMPULSE 0.7
#define NANOS_PER_MICROSECOND ((int64_t) 1000)
#define NANOS_PER_MILLISECOND (1000 * NANOS_PER_MICROSECOND)
#define NANOS_PER_SECOND (1000 * NANOS_PER_MILLISECOND)
#define LIB_AAUDIO_NAME "libaaudio.so"
#define FUNCTION_IS_MMAP "AAudioStream_isMMapUsed"
#define FUNCTION_SET_MMAP_POLICY "AAudio_setMMapPolicy"
#define FUNCTION_GET_MMAP_POLICY "AAudio_getMMapPolicy"
#define SECONDS_TO_RECORD 10
typedef struct AAudioStreamStruct AAudioStream;
/**
* Call some AAudio test routines that are not part of the normal API.
*/
class AAudioExtensions {
public:
AAudioExtensions() {
int32_t policy = getIntegerProperty("aaudio.mmap_policy", 0);
mMMapSupported = isPolicyEnabled(policy);
policy = getIntegerProperty("aaudio.mmap_exclusive_policy", 0);
mMMapExclusiveSupported = isPolicyEnabled(policy);
}
static bool isPolicyEnabled(int32_t policy) {
return (policy == AAUDIO_POLICY_AUTO || policy == AAUDIO_POLICY_ALWAYS);
}
static AAudioExtensions &getInstance() {
static AAudioExtensions instance;
return instance;
}
bool isMMapUsed(oboe::AudioStream *oboeStream) {
if (!loadLibrary()) return false;
AAudioStream *aaudioStream = (AAudioStream *) oboeStream->getUnderlyingStream();
return mAAudioStream_isMMap(aaudioStream);
}
bool setMMapEnabled(bool enabled) {
if (!loadLibrary()) return false;
return mAAudio_setMMapPolicy(enabled ? AAUDIO_POLICY_AUTO : AAUDIO_POLICY_NEVER);
}
bool isMMapEnabled() {
if (!loadLibrary()) return false;
int32_t policy = mAAudio_getMMapPolicy();
return isPolicyEnabled(policy);
}
bool isMMapSupported() {
return mMMapSupported;
}
bool isMMapExclusiveSupported() {
return mMMapExclusiveSupported;
}
private:
enum {
AAUDIO_POLICY_NEVER = 1,
AAUDIO_POLICY_AUTO,
AAUDIO_POLICY_ALWAYS
};
typedef int32_t aaudio_policy_t;
int getIntegerProperty(const char *name, int defaultValue) {
int result = defaultValue;
char valueText[PROP_VALUE_MAX] = {0};
if (__system_property_get(name, valueText) != 0) {
result = atoi(valueText);
}
return result;
}
// return true if it succeeds
bool loadLibrary() {
if (mFirstTime) {
mFirstTime = false;
mLibHandle = dlopen(LIB_AAUDIO_NAME, 0);
if (mLibHandle == nullptr) {
LOGI("%s() could not find " LIB_AAUDIO_NAME, __func__);
return false;
}
mAAudioStream_isMMap = (bool (*)(AAudioStream *stream))
dlsym(mLibHandle, FUNCTION_IS_MMAP);
if (mAAudioStream_isMMap == nullptr) {
LOGI("%s() could not find " FUNCTION_IS_MMAP, __func__);
return false;
}
mAAudio_setMMapPolicy = (int32_t (*)(aaudio_policy_t policy))
dlsym(mLibHandle, FUNCTION_SET_MMAP_POLICY);
if (mAAudio_setMMapPolicy == nullptr) {
LOGI("%s() could not find " FUNCTION_SET_MMAP_POLICY, __func__);
return false;
}
mAAudio_getMMapPolicy = (aaudio_policy_t (*)())
dlsym(mLibHandle, FUNCTION_GET_MMAP_POLICY);
if (mAAudio_getMMapPolicy == nullptr) {
LOGI("%s() could not find " FUNCTION_GET_MMAP_POLICY, __func__);
return false;
}
}
return true;
}
bool mFirstTime = true;
void *mLibHandle = nullptr;
bool (*mAAudioStream_isMMap)(AAudioStream *stream) = nullptr;
int32_t (*mAAudio_setMMapPolicy)(aaudio_policy_t policy) = nullptr;
aaudio_policy_t (*mAAudio_getMMapPolicy)() = nullptr;
bool mMMapSupported = false;
bool mMMapExclusiveSupported = false;
};
/**
* Abstract base class that corresponds to a test at the Java level.
*/
class ActivityContext {
public:
ActivityContext() {}
virtual ~ActivityContext() = default;
oboe::AudioStream *getStream(int32_t streamIndex) {
auto it = mOboeStreams.find(streamIndex);
if (it != mOboeStreams.end()) {
return it->second.get();
} else {
return nullptr;
}
}
virtual void configureBuilder(bool isInput, oboe::AudioStreamBuilder &builder);
int open(jint nativeApi,
jint sampleRate,
jint channelCount,
jint format,
jint sharingMode,
jint performanceMode,
jint inputPreset,
jint deviceId,
jint sessionId,
jint framesPerBurst,
jboolean channelConversionAllowed,
jboolean formatConversionAllowed,
jint rateConversionQuality,
jboolean isMMap,
jboolean isInput);
virtual void close(int32_t streamIndex);
void printScheduler() {
#if OBOE_ENABLE_LOGGING
int scheduler = audioStreamGateway.getScheduler();
#endif
LOGI("scheduler = 0x%08x, SCHED_FIFO = 0x%08X\n", scheduler, SCHED_FIFO);
}
virtual void configureForStart() {}
oboe::Result start();
oboe::Result pause();
oboe::Result stopAllStreams();
virtual oboe::Result stop() {
return stopAllStreams();
}
double getCpuLoad() {
return oboeCallbackProxy.getCpuLoad();
}
void setWorkload(double workload) {
oboeCallbackProxy.setWorkload(workload);
}
virtual oboe::Result startPlayback() {
return oboe::Result::OK;
}
virtual oboe::Result stopPlayback() {
return oboe::Result::OK;
}
virtual void runBlockingIO() {};
static void threadCallback(ActivityContext *context) {
context->runBlockingIO();
}
void stopBlockingIOThread() {
if (dataThread != nullptr) {
// stop a thread that runs in place of the callback
threadEnabled.store(false); // ask thread to exit its loop
dataThread->join();
dataThread = nullptr;
}
}
virtual double getPeakLevel(int index) {
return 0.0;
}
virtual void setEnabled(bool enabled) {
}
bool isMMapUsed(int32_t streamIndex);
int32_t getFramesPerBlock() {
return (callbackSize == 0) ? mFramesPerBurst : callbackSize;
}
int64_t getCallbackCount() {
return oboeCallbackProxy.getCallbackCount();
}
int32_t getFramesPerCallback() {
return oboeCallbackProxy.getFramesPerCallback();
}
virtual void setChannelEnabled(int channelIndex, bool enabled) {}
virtual void setSignalType(int signalType) {}
virtual int32_t saveWaveFile(const char *filename);
virtual void setMinimumFramesBeforeRead(int32_t numFrames) {}
static bool mUseCallback;
static int callbackSize;
protected:
oboe::AudioStream *getInputStream();
oboe::AudioStream *getOutputStream();
int32_t allocateStreamIndex();
void freeStreamIndex(int32_t streamIndex);
virtual void createRecording() {
mRecording = std::make_unique<MultiChannelRecording>(mChannelCount,
SECONDS_TO_RECORD * mSampleRate);
}
virtual void finishOpen(bool isInput, oboe::AudioStream *oboeStream) {}
virtual oboe::Result startStreams() = 0;
std::unique_ptr<float []> dataBuffer{};
AudioStreamGateway audioStreamGateway;
OboeStreamCallbackProxy oboeCallbackProxy;
std::unique_ptr<MultiChannelRecording> mRecording{};
int32_t mNextStreamHandle = 0;
std::unordered_map<int32_t, std::shared_ptr<oboe::AudioStream>> mOboeStreams;
int32_t mFramesPerBurst = 0; // TODO per stream
int32_t mChannelCount = 0; // TODO per stream
int32_t mSampleRate = 0; // TODO per stream
std::atomic<bool> threadEnabled{false};
std::thread *dataThread = nullptr;
private:
};
/**
* Test a single input stream.
*/
class ActivityTestInput : public ActivityContext {
public:
ActivityTestInput() {}
virtual ~ActivityTestInput() = default;
void configureForStart() override;
double getPeakLevel(int index) override {
return mInputAnalyzer.getPeakLevel(index);
}
void runBlockingIO() override;
InputStreamCallbackAnalyzer mInputAnalyzer;
void setMinimumFramesBeforeRead(int32_t numFrames) override {
mInputAnalyzer.setMinimumFramesBeforeRead(numFrames);
mMinimumFramesBeforeRead = numFrames;
}
int32_t getMinimumFramesBeforeRead() const {
return mMinimumFramesBeforeRead;
}
protected:
oboe::Result startStreams() override {
mInputAnalyzer.reset();
return getInputStream()->requestStart();
}
int32_t mMinimumFramesBeforeRead = 0;
};
/**
* Record a configured input stream and play it back some simple way.
*/
class ActivityRecording : public ActivityTestInput {
public:
ActivityRecording() {}
virtual ~ActivityRecording() = default;
oboe::Result stop() override {
oboe::Result resultStopPlayback = stopPlayback();
oboe::Result resultStopAudio = ActivityContext::stop();
return (resultStopPlayback != oboe::Result::OK) ? resultStopPlayback : resultStopAudio;
}
oboe::Result startPlayback() override;
oboe::Result stopPlayback() override;
PlayRecordingCallback mPlayRecordingCallback;
oboe::AudioStream *playbackStream = nullptr;
};
/**
* Test a single output stream.
*/
class ActivityTestOutput : public ActivityContext {
public:
ActivityTestOutput()
: sineOscillators(MAX_SINE_OSCILLATORS)
, sawtoothOscillators(MAX_SINE_OSCILLATORS) {}
virtual ~ActivityTestOutput() = default;
void close(int32_t streamIndex) override;
oboe::Result startStreams() override {
return getOutputStream()->start();
}
void configureForStart() override;
virtual void configureStreamGateway();
void runBlockingIO() override;
void setChannelEnabled(int channelIndex, bool enabled) override;
// WARNING - must match order in strings.xml and OboeAudioOutputStream.java
enum SignalType {
Sine = 0,
Sawtooth = 1,
FreqSweep = 2,
PitchSweep = 3,
WhiteNoise = 4
};
void setSignalType(int signalType) override {
mSignalType = (SignalType) signalType;
}
protected:
SignalType mSignalType = SignalType::Sine;
std::vector<SineOscillator> sineOscillators;
std::vector<SawtoothOscillator> sawtoothOscillators;
static constexpr float kSweepPeriod = 10.0; // for triangle up and down
// A triangle LFO is shaped into either a linear or an exponential range.
TriangleOscillator mTriangleOscillator;
LinearShape mLinearShape;
ExponentialShape mExponentialShape;
std::unique_ptr<ManyToMultiConverter> manyToMulti;
std::unique_ptr<MonoToMultiConverter> monoToMulti;
std::shared_ptr<flowgraph::SinkFloat> mSinkFloat;
std::shared_ptr<flowgraph::SinkI16> mSinkI16;
};
/**
* Generate a short beep with a very short attack.
* This is used by Java to measure output latency.
*/
class ActivityTapToTone : public ActivityTestOutput {
public:
ActivityTapToTone() {}
virtual ~ActivityTapToTone() = default;
void configureForStart() override;
virtual void setEnabled(bool enabled) override {
sawPingGenerator.setEnabled(enabled);
}
SawPingGenerator sawPingGenerator;
};
/**
* Activity that uses synchronized input/output streams.
*/
class ActivityFullDuplex : public ActivityContext {
public:
void configureBuilder(bool isInput, oboe::AudioStreamBuilder &builder) override;
virtual int32_t getState() { return -1; }
virtual int32_t getResult() { return -1; }
virtual bool isAnalyzerDone() { return false; }
void setMinimumFramesBeforeRead(int32_t numFrames) override {
getFullDuplexAnalyzer()->setMinimumFramesBeforeRead(numFrames);
}
virtual FullDuplexAnalyzer *getFullDuplexAnalyzer() = 0;
int32_t getResetCount() {
return getFullDuplexAnalyzer()->getLoopbackProcessor()->getResetCount();
}
protected:
void createRecording() override {
mRecording = std::make_unique<MultiChannelRecording>(2, // output and input
SECONDS_TO_RECORD * mSampleRate);
}
};
/**
* Echo input to output through a delay line.
*/
class ActivityEcho : public ActivityFullDuplex {
public:
oboe::Result startStreams() override {
return mFullDuplexEcho->start();
}
void configureBuilder(bool isInput, oboe::AudioStreamBuilder &builder) override;
void setDelayTime(double delayTimeSeconds) {
if (mFullDuplexEcho) {
mFullDuplexEcho->setDelayTime(delayTimeSeconds);
}
}
FullDuplexAnalyzer *getFullDuplexAnalyzer() override {
return (FullDuplexAnalyzer *) mFullDuplexEcho.get();
}
protected:
void finishOpen(bool isInput, oboe::AudioStream *oboeStream) override;
private:
std::unique_ptr<FullDuplexEcho> mFullDuplexEcho{};
};
/**
* Measure Round Trip Latency
*/
class ActivityRoundTripLatency : public ActivityFullDuplex {
public:
oboe::Result startStreams() override {
return mFullDuplexLatency->start();
}
void configureBuilder(bool isInput, oboe::AudioStreamBuilder &builder) override;
LatencyAnalyzer *getLatencyAnalyzer() {
return mFullDuplexLatency->getLatencyAnalyzer();
}
int32_t getState() override {
return getLatencyAnalyzer()->getState();
}
int32_t getResult() override {
return getLatencyAnalyzer()->getState();
}
bool isAnalyzerDone() override {
return mFullDuplexLatency->isDone();
}
FullDuplexAnalyzer *getFullDuplexAnalyzer() override {
return (FullDuplexAnalyzer *) mFullDuplexLatency.get();
}
protected:
void finishOpen(bool isInput, oboe::AudioStream *oboeStream) override;
private:
std::unique_ptr<FullDuplexLatency> mFullDuplexLatency{};
};
/**
* Measure Glitches
*/
class ActivityGlitches : public ActivityFullDuplex {
public:
oboe::Result startStreams() override {
return mFullDuplexGlitches->start();
}
void configureBuilder(bool isInput, oboe::AudioStreamBuilder &builder) override;
GlitchAnalyzer *getGlitchAnalyzer() {
if (!mFullDuplexGlitches) return nullptr;
return mFullDuplexGlitches->getGlitchAnalyzer();
}
int32_t getState() override {
return getGlitchAnalyzer()->getState();
}
int32_t getResult() override {
return getGlitchAnalyzer()->getResult();
}
bool isAnalyzerDone() override {
return mFullDuplexGlitches->isDone();
}
FullDuplexAnalyzer *getFullDuplexAnalyzer() override {
return (FullDuplexAnalyzer *) mFullDuplexGlitches.get();
}
protected:
void finishOpen(bool isInput, oboe::AudioStream *oboeStream) override;
private:
std::unique_ptr<FullDuplexGlitches> mFullDuplexGlitches{};
};
/**
* Test a single output stream.
*/
class ActivityTestDisconnect : public ActivityContext {
public:
ActivityTestDisconnect() {}
virtual ~ActivityTestDisconnect() = default;
void close(int32_t streamIndex) override;
oboe::Result startStreams() override {
oboe::AudioStream *outputStream = getOutputStream();
if (outputStream) {
return outputStream->start();
}
oboe::AudioStream *inputStream = getInputStream();
if (inputStream) {
return inputStream->start();
}
return oboe::Result::ErrorNull;
}
void configureForStart() override;
private:
std::unique_ptr<SineOscillator> sineOscillator;
std::unique_ptr<MonoToMultiConverter> monoToMulti;
std::shared_ptr<flowgraph::SinkFloat> mSinkFloat;
};
/**
* Switch between various
*/
class NativeAudioContext {
public:
ActivityContext *getCurrentActivity() {
return currentActivity;
};
void setActivityType(int activityType) {
mActivityType = (ActivityType) activityType;
switch(mActivityType) {
default:
case ActivityType::Undefined:
case ActivityType::TestOutput:
currentActivity = &mActivityTestOutput;
break;
case ActivityType::TestInput:
currentActivity = &mActivityTestInput;
break;
case ActivityType::TapToTone:
currentActivity = &mActivityTapToTone;
break;
case ActivityType::RecordPlay:
currentActivity = &mActivityRecording;
break;
case ActivityType::Echo:
currentActivity = &mActivityEcho;
break;
case ActivityType::RoundTripLatency:
currentActivity = &mActivityRoundTripLatency;
break;
case ActivityType::Glitches:
currentActivity = &mActivityGlitches;
break;
case ActivityType::TestDisconnect:
currentActivity = &mActivityTestDisconnect;
break;
}
}
void setDelayTime(double delayTimeMillis) {
mActivityEcho.setDelayTime(delayTimeMillis);
}
ActivityTestOutput mActivityTestOutput;
ActivityTestInput mActivityTestInput;
ActivityTapToTone mActivityTapToTone;
ActivityRecording mActivityRecording;
ActivityEcho mActivityEcho;
ActivityRoundTripLatency mActivityRoundTripLatency;
ActivityGlitches mActivityGlitches;
ActivityTestDisconnect mActivityTestDisconnect;
private:
// WARNING - must match definitions in TestAudioActivity.java
enum ActivityType {
Undefined = -1,
TestOutput = 0,
TestInput = 1,
TapToTone = 2,
RecordPlay = 3,
Echo = 4,
RoundTripLatency = 5,
Glitches = 6,
TestDisconnect = 7,
};
ActivityType mActivityType = ActivityType::Undefined;
ActivityContext *currentActivity = &mActivityTestOutput;
};
#endif //NATIVEOBOE_NATIVEAUDIOCONTEXT_H
@@ -0,0 +1,95 @@
/*
* Copyright 2017 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "common/OboeDebug.h"
#include "OboeStreamCallbackProxy.h"
// Linear congruential random number generator.
static uint32_t s_random16() {
static uint32_t seed = 1234;
seed = ((seed * 31421) + 6927) & 0x0FFFF;
return seed;
}
/**
* The random number generator is good for burning CPU because the compiler cannot
* easily optimize away the computation.
* @param workload number of times to execute the loop
* @return a white noise value between -1.0 and +1.0
*/
static float s_burnCPU(int32_t workload) {
uint32_t random = 0;
for (int32_t i = 0; i < workload; i++) {
for (int32_t j = 0; j < 10; j++) {
random = random ^ s_random16();
}
}
return (random - 32768) * (1.0 / 32768);
}
bool OboeStreamCallbackProxy::mCallbackReturnStop = false;
int64_t OboeStreamCallbackProxy::getNanoseconds(clockid_t clockId) {
struct timespec time;
int result = clock_gettime(clockId, &time);
if (result < 0) {
return result;
}
return (time.tv_sec * 1e9) + time.tv_nsec;
}
oboe::DataCallbackResult OboeStreamCallbackProxy::onAudioReady(
oboe::AudioStream *audioStream,
void *audioData,
int numFrames) {
oboe::DataCallbackResult callbackResult = oboe::DataCallbackResult::Stop;
int64_t startTimeNanos = getNanoseconds();
mCallbackCount++;
mFramesPerCallback = numFrames;
if (mCallbackReturnStop) {
return oboe::DataCallbackResult::Stop;
}
s_burnCPU((int32_t)(mWorkload * kWorkloadScaler * numFrames));
if (mCallback != nullptr) {
callbackResult = mCallback->onAudioReady(audioStream, audioData, numFrames);
}
// Update CPU load
double calculationTime = (double)(getNanoseconds() - startTimeNanos);
double inverseRealTime = audioStream->getSampleRate() / (1.0e9 * numFrames);
double currentCpuLoad = calculationTime * inverseRealTime; // avoid a divide
mCpuLoad = (mCpuLoad * 0.95) + (currentCpuLoad * 0.05); // simple low pass filter
return callbackResult;
}
void OboeStreamCallbackProxy::onErrorBeforeClose(oboe::AudioStream *audioStream, oboe::Result error) {
LOGD("OboeStreamCallbackProxy::%s(%p, %d) called", __func__, audioStream, error);
if (mCallback != nullptr) {
mCallback->onErrorBeforeClose(audioStream, error);
}
}
void OboeStreamCallbackProxy::onErrorAfterClose(oboe::AudioStream *audioStream, oboe::Result error) {
LOGD("OboeStreamCallbackProxy::%s(%p, %d) called", __func__, audioStream, error);
if (mCallback != nullptr) {
mCallback->onErrorAfterClose(audioStream, error);
}
}
@@ -0,0 +1,92 @@
/*
* Copyright 2017 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef NATIVEOBOE_OBOESTREAMCALLBACKPROXY_H
#define NATIVEOBOE_OBOESTREAMCALLBACKPROXY_H
#include <unistd.h>
#include <sys/types.h>
#include "oboe/Oboe.h"
class OboeStreamCallbackProxy : public oboe::AudioStreamCallback {
public:
void setCallback(oboe::AudioStreamCallback *callback) {
mCallback = callback;
setCallbackCount(0);
}
static void setCallbackReturnStop(bool b) {
mCallbackReturnStop = b;
}
int64_t getCallbackCount() {
return mCallbackCount;
}
void setCallbackCount(int64_t count) {
mCallbackCount = count;
}
int32_t getFramesPerCallback() {
return mFramesPerCallback.load();
}
/**
* Called when the stream is ready to process audio.
*/
oboe::DataCallbackResult onAudioReady(
oboe::AudioStream *audioStream,
void *audioData,
int numFrames) override;
void onErrorBeforeClose(oboe::AudioStream *audioStream, oboe::Result error) override;
void onErrorAfterClose(oboe::AudioStream *audioStream, oboe::Result error) override;
/**
* Specify the amount of artificial workload that will waste CPU cycles
* and increase the CPU load.
* @param workload typically ranges from 0.0 to 100.0
*/
void setWorkload(double workload) {
mWorkload = std::max(0.0, workload);
}
double getWorkload() const {
return mWorkload;
}
double getCpuLoad() const {
return mCpuLoad;
}
static int64_t getNanoseconds(clockid_t clockId = CLOCK_MONOTONIC);
private:
static constexpr int32_t kWorkloadScaler = 500;
double mWorkload = 0.0;
std::atomic<double> mCpuLoad{0};
oboe::AudioStreamCallback *mCallback = nullptr;
static bool mCallbackReturnStop;
int64_t mCallbackCount = 0;
std::atomic<int32_t> mFramesPerCallback{0};
};
#endif //NATIVEOBOE_OBOESTREAMCALLBACKPROXY_H
@@ -0,0 +1,33 @@
/*
* Copyright 2018 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "PlayRecordingCallback.h"
/**
* Called when the stream is ready to process audio.
*/
oboe::DataCallbackResult PlayRecordingCallback::onAudioReady(
oboe::AudioStream *audioStream,
void *audioData,
int numFrames) {
float *floatData = (float *)audioData;
// Read stored data into the buffer provided.
int32_t framesRead = mRecording->read(floatData, numFrames);
// LOGI("%s() framesRead = %d, numFrames = %d", __func__, framesRead, numFrames);
return framesRead > 0
? oboe::DataCallbackResult::Continue
: oboe::DataCallbackResult::Stop;
}
@@ -0,0 +1,46 @@
/*
* Copyright 2018 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef NATIVEOBOE_PLAY_RECORDING_CALLBACK_H
#define NATIVEOBOE_PLAY_RECORDING_CALLBACK_H
#include "oboe/Oboe.h"
#include "MultiChannelRecording.h"
class PlayRecordingCallback : public oboe::AudioStreamCallback {
public:
PlayRecordingCallback() {}
~PlayRecordingCallback() = default;
void setRecording(MultiChannelRecording *recording) {
mRecording = recording;
}
/**
* Called when the stream is ready to process audio.
*/
oboe::DataCallbackResult onAudioReady(
oboe::AudioStream *audioStream,
void *audioData,
int numFrames);
private:
MultiChannelRecording *mRecording = nullptr;
};
#endif //NATIVEOBOE_PLAYRECORDINGCALLBACK_H
@@ -0,0 +1,68 @@
/*
* Copyright 2015 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <unistd.h>
#include "common/OboeDebug.h"
#include "oboe/Definitions.h"
#include "SawPingGenerator.h"
using namespace flowgraph;
SawPingGenerator::SawPingGenerator()
: OscillatorBase()
, mRequestCount(0)
, mAcknowledgeCount(0)
, mLevel(0.0f) {
}
SawPingGenerator::~SawPingGenerator() { }
int32_t SawPingGenerator::onProcess(int numFrames) {
const float *frequencies = frequency.getBuffer();
const float *amplitudes = amplitude.getBuffer();
float *buffer = output.getBuffer();
if (mRequestCount.load() > mAcknowledgeCount.load()) {
mPhase = -1.0f;
mLevel = 1.0;
mAcknowledgeCount++;
}
// Check level to prevent numeric underflow.
if (mLevel > 0.000001) {
for (int i = 0; i < numFrames; i++) {
float sawtooth = incrementPhase(frequencies[i]);
*buffer++ = (float) (sawtooth * mLevel * amplitudes[i]);
mLevel *= 0.999;
}
} else {
for (int i = 0; i < numFrames; i++) {
*buffer++ = 0.0f;
}
}
return numFrames;
}
void SawPingGenerator::setEnabled(bool enabled) {
if (enabled) {
mRequestCount++;
} else {
mAcknowledgeCount.store(mRequestCount.load());
}
}
@@ -0,0 +1,44 @@
/*
* Copyright 2015 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef NATIVEOBOE_SAWPINGGENERATOR_H
#define NATIVEOBOE_SAWPINGGENERATOR_H
#include <atomic>
#include <unistd.h>
#include <sys/types.h>
#include "flowgraph/FlowGraphNode.h"
#include "flowunits/OscillatorBase.h"
class SawPingGenerator : public OscillatorBase {
public:
SawPingGenerator();
virtual ~SawPingGenerator();
int32_t onProcess(int numFrames) override;
void setEnabled(bool enabled);
private:
std::atomic<int> mRequestCount; // external thread increments this to request a beep
std::atomic<int> mAcknowledgeCount; // audio thread sets this to acknowledge
double mLevel;
};
#endif //NATIVEOBOE_SAWPINGGENERATOR_H
@@ -0,0 +1,438 @@
/*
* Copyright (C) 2017 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef OBOETESTER_GLITCHANALYZER_H
#define OBOETESTER_GLITCHANALYZER_H
#include <cctype>
#include "PseudoRandom.h"
#include "LatencyAnalyzer.h"
#include "InfiniteRecording.h"
/**
* Output a steady sinewave and analyze the return signal.
*
* Use a cosine transform to measure the predicted magnitude and relative phase of the
* looped back sine wave. Then generate a predicted signal and compare with the actual signal.
*/
class GlitchAnalyzer : public LoopbackProcessor {
public:
GlitchAnalyzer()
: LoopbackProcessor()
, mInfiniteRecording(64 * 1024) {}
int32_t getState() {
return mState;
}
float getPeakAmplitude() {
return mPeakFollower.getLevel();
}
float getTolerance() {
return mTolerance;
}
void setTolerance(float tolerance) {
mTolerance = tolerance;
mScaledTolerance = mMagnitude * mTolerance;
}
void setMagnitude(double magnitude) {
mMagnitude = magnitude;
mScaledTolerance = mMagnitude * mTolerance;
}
int32_t getGlitchCount() {
return mGlitchCount;
}
int32_t getStateFrameCount(int state) {
return mStateFrameCounters[state];
}
double getSignalToNoiseDB() {
static const double threshold = 1.0e-14;
if (mMeanSquareSignal < threshold || mMeanSquareNoise < threshold) {
return 0.0;
} else {
double signalToNoise = mMeanSquareSignal / mMeanSquareNoise; // power ratio
double signalToNoiseDB = 10.0 * log(signalToNoise);
if (signalToNoiseDB < MIN_SNRATIO_DB) {
LOGD("ERROR - signal to noise ratio is too low! < %d dB. Adjust volume.",
MIN_SNRATIO_DB);
setResult(ERROR_VOLUME_TOO_LOW);
}
return signalToNoiseDB;
}
}
void analyze() override {
LOGD("GlitchAnalyzer ------------------");
LOGD(LOOPBACK_RESULT_TAG "peak.amplitude = %8f", getPeakAmplitude());
LOGD(LOOPBACK_RESULT_TAG "sine.magnitude = %8f", mMagnitude);
LOGD(LOOPBACK_RESULT_TAG "rms.noise = %8f", mMeanSquareNoise);
LOGD(LOOPBACK_RESULT_TAG "signal.to.noise.db = %8.2f", getSignalToNoiseDB());
LOGD(LOOPBACK_RESULT_TAG "frames.accumulated = %8d", mFramesAccumulated);
LOGD(LOOPBACK_RESULT_TAG "sine.period = %8d", mSinePeriod);
LOGD(LOOPBACK_RESULT_TAG "test.state = %8d", mState);
LOGD(LOOPBACK_RESULT_TAG "frame.count = %8d", mFrameCounter);
// Did we ever get a lock?
bool gotLock = (mState == STATE_LOCKED) || (mGlitchCount > 0);
if (!gotLock) {
LOGD("ERROR - failed to lock on reference sine tone");
setResult(ERROR_NO_LOCK);
} else {
// Only print if meaningful.
LOGD(LOOPBACK_RESULT_TAG "glitch.count = %8d", mGlitchCount);
LOGD(LOOPBACK_RESULT_TAG "max.glitch = %8f", mMaxGlitchDelta);
if (mGlitchCount > 0) {
LOGD("ERROR - number of glitches > 0");
setResult(ERROR_GLITCHES);
}
}
}
void printStatus() override {
LOGD("st = %d, #gl = %3d,", mState, mGlitchCount);
}
double calculateMagnitude(double *phasePtr = NULL) {
if (mFramesAccumulated == 0) {
return 0.0;
}
double sinMean = mSinAccumulator / mFramesAccumulated;
double cosMean = mCosAccumulator / mFramesAccumulated;
double magnitude = 2.0 * sqrt( (sinMean * sinMean) + (cosMean * cosMean ));
if( phasePtr != NULL )
{
double phase = M_PI_2 - atan2( sinMean, cosMean );
*phasePtr = phase;
}
return magnitude;
}
/**
* @param frameData contains microphone data with sine signal feedback
* @param channelCount
*/
result_code processInputFrame(float *frameData, int channelCount) override {
result_code result = RESULT_OK;
float sample = frameData[0];
float peak = mPeakFollower.process(sample);
mInfiniteRecording.write(sample);
// Force a periodic glitch!
if (mForceGlitchDuration > 0) {
if (mForceGlitchCounter == 0) {
LOGE("%s: force a glitch!!", __func__);
mForceGlitchCounter = getSampleRate();
} else if (mForceGlitchCounter <= mForceGlitchDuration) {
sample += (sample > 0.0) ? -0.5f : 0.5f;
}
--mForceGlitchCounter;
}
mStateFrameCounters[mState]++; // count how many frames we are in each state
switch (mState) {
case STATE_IDLE:
mDownCounter--;
if (mDownCounter <= 0) {
mState = STATE_IMMUNE;
mDownCounter = IMMUNE_FRAME_COUNT;
mInputPhase = 0.0; // prevent spike at start
mOutputPhase = 0.0;
}
break;
case STATE_IMMUNE:
mDownCounter--;
if (mDownCounter <= 0) {
mState = STATE_WAITING_FOR_SIGNAL;
}
break;
case STATE_WAITING_FOR_SIGNAL:
if (peak > mThreshold) {
mState = STATE_WAITING_FOR_LOCK;
//LOGD("%5d: switch to STATE_WAITING_FOR_LOCK", mFrameCounter);
resetAccumulator();
}
break;
case STATE_WAITING_FOR_LOCK:
mSinAccumulator += sample * sinf(mInputPhase);
mCosAccumulator += sample * cosf(mInputPhase);
mFramesAccumulated++;
// Must be a multiple of the period or the calculation will not be accurate.
if (mFramesAccumulated == mSinePeriod * PERIODS_NEEDED_FOR_LOCK) {
double phaseOffset = 0.0;
setMagnitude(calculateMagnitude(&phaseOffset));
// LOGD("%s() mag = %f, offset = %f, prev = %f",
// __func__, mMagnitude, mPhaseOffset, mPreviousPhaseOffset);
if (mMagnitude > mThreshold) {
if (abs(phaseOffset) < kMaxPhaseError) {
mState = STATE_LOCKED;
// LOGD("%5d: switch to STATE_LOCKED", mFrameCounter);
}
// Adjust mInputPhase to match measured phase
mInputPhase += phaseOffset;
}
resetAccumulator();
}
incrementInputPhase();
break;
case STATE_LOCKED: {
// Predict next sine value
float predicted = sinf(mInputPhase) * mMagnitude;
float diff = predicted - sample;
float absDiff = fabs(diff);
mMaxGlitchDelta = std::max(mMaxGlitchDelta, absDiff);
if (absDiff > mScaledTolerance) {
result = ERROR_GLITCHES;
onGlitchStart();
// LOGI("diff glitch detected, absDiff = %g", absDiff);
} else {
mSumSquareSignal += predicted * predicted;
mSumSquareNoise += diff * diff;
// Track incoming signal and slowly adjust magnitude to account
// for drift in the DRC or AGC.
mSinAccumulator += sample * sinf(mInputPhase);
mCosAccumulator += sample * cosf(mInputPhase);
mFramesAccumulated++;
// Must be a multiple of the period or the calculation will not be accurate.
if (mFramesAccumulated == mSinePeriod) {
const double coefficient = 0.1;
double phaseOffset = 0.0;
double magnitude = calculateMagnitude(&phaseOffset);
// One pole averaging filter.
setMagnitude((mMagnitude * (1.0 - coefficient)) + (magnitude * coefficient));
mMeanSquareNoise = mSumSquareNoise * mInverseSinePeriod;
mMeanSquareSignal = mSumSquareSignal * mInverseSinePeriod;
resetAccumulator();
if (abs(phaseOffset) > kMaxPhaseError) {
result = ERROR_GLITCHES;
onGlitchStart();
LOGD("phase glitch detected, phaseOffset = %g", phaseOffset);
} else if (mMagnitude < mThreshold) {
result = ERROR_GLITCHES;
onGlitchStart();
LOGD("magnitude glitch detected, mMagnitude = %g", mMagnitude);
}
}
}
incrementInputPhase();
} break;
case STATE_GLITCHING: {
// Predict next sine value
mGlitchLength++;
float predicted = sinf(mInputPhase) * mMagnitude;
float diff = predicted - sample;
float absDiff = fabs(diff);
mMaxGlitchDelta = std::max(mMaxGlitchDelta, absDiff);
if (absDiff < mScaledTolerance) { // close enough?
// If we get a full sine period of non-glitch samples in a row then consider the glitch over.
// We don't want to just consider a zero crossing the end of a glitch.
if (mNonGlitchCount++ > mSinePeriod) {
onGlitchEnd();
}
} else {
mNonGlitchCount = 0;
if (mGlitchLength > (4 * mSinePeriod)) {
relock();
}
}
incrementInputPhase();
} break;
case NUM_STATES: // not a real state
break;
}
mFrameCounter++;
return result;
}
// advance and wrap phase
void incrementInputPhase() {
mInputPhase += mPhaseIncrement;
if (mInputPhase > M_PI) {
mInputPhase -= (2.0 * M_PI);
}
}
// advance and wrap phase
void incrementOutputPhase() {
mOutputPhase += mPhaseIncrement;
if (mOutputPhase > M_PI) {
mOutputPhase -= (2.0 * M_PI);
}
}
/**
* @param frameData upon return, contains the reference sine wave
* @param channelCount
*/
result_code processOutputFrame(float *frameData, int channelCount) override {
float output = 0.0f;
// Output sine wave so we can measure it.
if (mState != STATE_IDLE) {
float sinOut = sinf(mOutputPhase);
incrementOutputPhase();
output = (sinOut * mOutputAmplitude)
+ (mWhiteNoise.nextRandomDouble() * kNoiseAmplitude);
// LOGD("%5d: sin(%f) = %f, %f", i, mPhase, sinOut, mPhaseIncrement);
}
frameData[0] = output;
for (int i = 1; i < channelCount; i++) {
frameData[i] = 0.0f;
}
return RESULT_OK;
}
void onGlitchStart() {
mGlitchCount++;
// LOGD("%5d: STARTED a glitch # %d", mFrameCounter, mGlitchCount);
mState = STATE_GLITCHING;
mGlitchLength = 1;
mNonGlitchCount = 0;
mLastGlitchPosition = mInfiniteRecording.getTotalWritten();
}
void onGlitchEnd() {
// LOGD("%5d: ENDED a glitch # %d, length = %d", mFrameCounter, mGlitchCount, mGlitchLength);
mState = STATE_LOCKED;
resetAccumulator();
}
// reset the sine wave detector
void resetAccumulator() {
mFramesAccumulated = 0;
mSinAccumulator = 0.0;
mCosAccumulator = 0.0;
mSumSquareSignal = 0.0;
mSumSquareNoise = 0.0;
}
void relock() {
// LOGD("relock: %d because of a very long %d glitch", mFrameCounter, mGlitchLength);
mState = STATE_WAITING_FOR_LOCK;
resetAccumulator();
}
void reset() override {
LoopbackProcessor::reset();
mState = STATE_IDLE;
mDownCounter = IDLE_FRAME_COUNT;
resetAccumulator();
}
void onStartTest() override {
LoopbackProcessor::onStartTest();
mSinePeriod = getSampleRate() / kTargetGlitchFrequency;
mOutputPhase = 0.0f;
mInverseSinePeriod = 1.0 / mSinePeriod;
mPhaseIncrement = 2.0 * M_PI * mInverseSinePeriod;
mGlitchCount = 0;
mMaxGlitchDelta = 0.0;
for (int i = 0; i < NUM_STATES; i++) {
mStateFrameCounters[i] = 0;
}
}
int32_t getLastGlitch(float *buffer, int32_t length) {
return mInfiniteRecording.readFrom(buffer, mLastGlitchPosition - 32, length);
}
private:
// These must match the values in GlitchActivity.java
enum sine_state_t {
STATE_IDLE, // beginning
STATE_IMMUNE, // ignoring input, waiting fo HW to settle
STATE_WAITING_FOR_SIGNAL, // looking for a loud signal
STATE_WAITING_FOR_LOCK, // trying to lock onto the phase of the sine
STATE_LOCKED, // locked on the sine wave, looking for glitches
STATE_GLITCHING, // locked on the sine wave but glitching
NUM_STATES
};
enum constants {
// Arbitrary durations, assuming 48000 Hz
IDLE_FRAME_COUNT = 48 * 100,
IMMUNE_FRAME_COUNT = 48 * 100,
PERIODS_NEEDED_FOR_LOCK = 8,
MIN_SNRATIO_DB = 65
};
static constexpr float kNoiseAmplitude = 0.00; // Used to experiment with warbling caused by DRC.
static constexpr int kTargetGlitchFrequency = 607;
static constexpr double kMaxPhaseError = M_PI * 0.05;
float mTolerance = 0.10; // scaled from 0.0 to 1.0
double mThreshold = 0.005;
int mSinePeriod = 1; // this will be set before use
double mInverseSinePeriod = 1.0;
int32_t mStateFrameCounters[NUM_STATES];
double mPhaseIncrement = 0.0;
double mInputPhase = 0.0;
double mOutputPhase = 0.0;
double mMagnitude = 0.0;
int32_t mFramesAccumulated = 0;
double mSinAccumulator = 0.0;
double mCosAccumulator = 0.0;
float mMaxGlitchDelta = 0.0f;
int32_t mGlitchCount = 0;
int32_t mNonGlitchCount = 0;
int32_t mGlitchLength = 0;
float mScaledTolerance = 0.0;
int mDownCounter = IDLE_FRAME_COUNT;
int32_t mFrameCounter = 0;
float mOutputAmplitude = 0.75;
int32_t mForceGlitchDuration = 0; // if > 0 then force a glitch for debugging
int32_t mForceGlitchCounter = 4 * 48000; // count down and trigger at zero
// measure background noise continuously as a deviation from the expected signal
double mSumSquareSignal = 0.0;
double mSumSquareNoise = 0.0;
double mMeanSquareSignal = 0.0;
double mMeanSquareNoise = 0.0;
PeakDetector mPeakFollower;
PseudoRandom mWhiteNoise;
sine_state_t mState = STATE_IDLE;
InfiniteRecording<float> mInfiniteRecording;
int64_t mLastGlitchPosition;
};
#endif //OBOETESTER_GLITCHANALYZER_H
@@ -0,0 +1,67 @@
/*
* Copyright (C) 2019 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef OBOETESTER_INFINITE_RECORDING_H
#define OBOETESTER_INFINITE_RECORDING_H
#include <memory>
#include <unistd.h>
/**
* Record forever. Keep last data.
*/
template <typename T>
class InfiniteRecording {
public:
InfiniteRecording(size_t maxSamples)
: mMaxSamples(maxSamples) {
mData = std::make_unique<T[]>(mMaxSamples);
}
int32_t readFrom(T *buffer, size_t position, size_t count) {
const size_t maxPosition = mWritten.load();
position = std::min(position, maxPosition);
size_t numToRead = std::min(count, mMaxSamples);
numToRead = std::min(numToRead, maxPosition - position);
if (numToRead == 0) return 0;
// We may need to read in two parts if it wraps.
const size_t offset = position % mMaxSamples;
const size_t firstReadSize = std::min(numToRead, mMaxSamples - offset); // till end
std::copy(&mData[offset], &mData[offset + firstReadSize], buffer);
if (firstReadSize < numToRead) {
// Second read needed.
std::copy(&mData[0], &mData[numToRead - firstReadSize], &buffer[firstReadSize]);
}
return numToRead;
}
void write(T sample) {
const size_t position = mWritten.load();
const size_t offset = position % mMaxSamples;
mData[offset] = sample;
mWritten++;
}
int64_t getTotalWritten() {
return mWritten.load();
}
private:
std::unique_ptr<T[]> mData;
std::atomic<size_t> mWritten{0};
const size_t mMaxSamples;
};
#endif //OBOETESTER_INFINITE_RECORDING_H
@@ -0,0 +1,611 @@
/*
* Copyright (C) 2017 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* Tools for measuring latency and for detecting glitches.
* These classes are pure math and can be used with any audio system.
*/
#ifndef ANALYZER_LATENCY_ANALYZER_H
#define ANALYZER_LATENCY_ANALYZER_H
#include <algorithm>
#include <assert.h>
#include <cctype>
#include <math.h>
#include <memory>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <vector>
#include "RandomPulseGenerator.h"
#include "PeakDetector.h"
#include "PseudoRandom.h"
#define LOOPBACK_RESULT_TAG "RESULT: "
static constexpr int32_t kDefaultSampleRate = 48000;
static constexpr int32_t kMillisPerSecond = 1000;
static constexpr int32_t kMaxLatencyMillis = 700; // arbitrary and generous
static constexpr double kMinimumConfidence = 0.2;
typedef struct LatencyReport_s {
int32_t latencyInFrames = 0.0;
double confidence = 0.0;
void reset() {
latencyInFrames = 0;
confidence = 0.0;
}
} LatencyReport;
// Calculate a normalized cross correlation.
static double calculateNormalizedCorrelation(const float *a,
const float *b,
int windowSize)
{
double correlation = 0.0;
double sumProducts = 0.0;
double sumSquares = 0.0;
// Correlate a against b.
for (int i = 0; i < windowSize; i++) {
float s1 = a[i];
float s2 = b[i];
// Use a normalized cross-correlation.
sumProducts += s1 * s2;
sumSquares += ((s1 * s1) + (s2 * s2));
}
if (sumSquares >= 1.0e-9) {
correlation = (float) (2.0 * sumProducts / sumSquares);
}
return correlation;
}
static double calculateRootMeanSquare(float *data, int32_t numSamples) {
double sum = 0.0;
for (int32_t i = 0; i < numSamples; i++) {
float sample = data[i];
sum += sample * sample;
}
return sqrt(sum / numSamples);
}
/**
* Monophonic recording with processing.
*/
class AudioRecording
{
public:
AudioRecording() {
}
~AudioRecording() {
delete[] mData;
}
void allocate(int maxFrames) {
delete[] mData;
mData = new float[maxFrames];
mMaxFrames = maxFrames;
}
// Write SHORT data from the first channel.
int32_t write(int16_t *inputData, int32_t inputChannelCount, int32_t numFrames) {
// stop at end of buffer
if ((mFrameCounter + numFrames) > mMaxFrames) {
numFrames = mMaxFrames - mFrameCounter;
}
for (int i = 0; i < numFrames; i++) {
mData[mFrameCounter++] = inputData[i * inputChannelCount] * (1.0f / 32768);
}
return numFrames;
}
// Write FLOAT data from the first channel.
int32_t write(float *inputData, int32_t inputChannelCount, int32_t numFrames) {
// stop at end of buffer
if ((mFrameCounter + numFrames) > mMaxFrames) {
numFrames = mMaxFrames - mFrameCounter;
}
for (int i = 0; i < numFrames; i++) {
mData[mFrameCounter++] = inputData[i * inputChannelCount];
}
return numFrames;
}
// Write FLOAT data from the first channel.
int32_t write(float sample) {
// stop at end of buffer
if (mFrameCounter < mMaxFrames) {
mData[mFrameCounter++] = sample;
}
return 1;
}
void clear() {
mFrameCounter = 0;
}
int32_t size() {
return mFrameCounter;
}
bool isFull() {
return mFrameCounter >= mMaxFrames;
}
float *getData() {
return mData;
}
void setSampleRate(int32_t sampleRate) {
mSampleRate = sampleRate;
}
int32_t getSampleRate() {
return mSampleRate;
}
/**
* Square the samples so they are all positive and so the peaks are emphasized.
*/
void square() {
for (int i = 0; i < mFrameCounter; i++) {
const float sample = mData[i];
mData[i] = sample * sample;
}
}
/**
* Amplify a signal so that the peak matches the specified target.
*
* @param target final max value
* @return gain applied to signal
*/
float normalize(float target) {
float maxValue = 1.0e-9f;
for (int i = 0; i < mFrameCounter; i++) {
maxValue = std::max(maxValue, abs(mData[i]));
}
float gain = target / maxValue;
for (int i = 0; i < mFrameCounter; i++) {
mData[i] *= gain;
}
return gain;
}
private:
float *mData = nullptr;
int32_t mFrameCounter = 0;
int32_t mMaxFrames = 0;
int32_t mSampleRate = kDefaultSampleRate; // common default
};
static int measureLatencyFromPulse(AudioRecording &recorded,
AudioRecording &pulse,
int32_t framesPerEncodedBit,
LatencyReport *report) {
report->latencyInFrames = 0;
report->confidence = 0.0;
int numCorrelations = recorded.size() - pulse.size();
if (numCorrelations < 10) {
LOGE("%s() recording too small = %d frames", __func__, recorded.size());
return -1;
}
std::unique_ptr<float[]> correlations= std::make_unique<float[]>(numCorrelations);
// Correlate pulse against the recorded data.
for (int i = 0; i < numCorrelations; i++) {
float correlation = (float) calculateNormalizedCorrelation(&recorded.getData()[i],
&pulse.getData()[0],
pulse.size());
correlations[i] = correlation;
}
// Find highest peak in correlation array.
float peakCorrelation = 0.0;
int peakIndex = -1;
for (int i = 0; i < numCorrelations; i++) {
float value = abs(correlations[i]);
if (value > peakCorrelation) {
peakCorrelation = value;
peakIndex = i;
}
}
if (peakIndex < 0) {
LOGE("%s() no signal for correlation", __func__);
return -2;
}
report->latencyInFrames = peakIndex;
report->confidence = peakCorrelation;
return 0;
}
// ====================================================================================
class LoopbackProcessor {
public:
virtual ~LoopbackProcessor() = default;
// Note that these values must match the switch in RoundTripLatencyActivity.h
enum result_code {
RESULT_OK = 0,
ERROR_NOISY = -99,
ERROR_VOLUME_TOO_LOW,
ERROR_VOLUME_TOO_HIGH,
ERROR_CONFIDENCE,
ERROR_INVALID_STATE,
ERROR_GLITCHES,
ERROR_NO_LOCK
};
virtual void onStartTest() {
reset();
}
virtual void reset() {
mResult = 0;
mResetCount++;
}
virtual result_code processInputFrame(float *frameData, int channelCount) = 0;
virtual result_code processOutputFrame(float *frameData, int channelCount) = 0;
void process(float *inputData, int inputChannelCount, int numInputFrames,
float *outputData, int outputChannelCount, int numOutputFrames) {
int numBoth = std::min(numInputFrames, numOutputFrames);
// Process one frame at a time.
for (int i = 0; i < numBoth; i++) {
processInputFrame(inputData, inputChannelCount);
inputData += inputChannelCount;
processOutputFrame(outputData, outputChannelCount);
outputData += outputChannelCount;
}
// If there is more input than output.
for (int i = numBoth; i < numInputFrames; i++) {
processInputFrame(inputData, inputChannelCount);
inputData += inputChannelCount;
}
// If there is more output than input.
for (int i = numBoth; i < numOutputFrames; i++) {
processOutputFrame(outputData, outputChannelCount);
outputData += outputChannelCount;
}
}
virtual void analyze() = 0;
virtual void printStatus() {};
int32_t getResult() {
return mResult;
}
void setResult(int32_t result) {
mResult = result;
}
virtual bool isDone() {
return false;
}
virtual int save(const char *fileName) {
(void) fileName;
return -1;
}
virtual int load(const char *fileName) {
(void) fileName;
return -1;
}
virtual void setSampleRate(int32_t sampleRate) {
mSampleRate = sampleRate;
}
int32_t getSampleRate() {
return mSampleRate;
}
int32_t getResetCount() {
return mResetCount;
}
/** Called when not enough input frames could be read after synchronization.
*/
virtual void onInsufficientRead() {
reset();
}
protected:
int32_t mResetCount = 0;
private:
int32_t mSampleRate = kDefaultSampleRate;
int32_t mResult = 0;
};
class LatencyAnalyzer : public LoopbackProcessor {
public:
LatencyAnalyzer() : LoopbackProcessor() {}
virtual ~LatencyAnalyzer() = default;
virtual int32_t getProgress() = 0;
virtual int getState() = 0;
// @return latency in frames
virtual int32_t getMeasuredLatency() = 0;
virtual double getMeasuredConfidence() = 0;
virtual double getBackgroundRMS() = 0;
virtual double getSignalRMS() = 0;
};
// ====================================================================================
/**
* Measure latency given a loopback stream data.
* Use an encoded bit train as the sound source because it
* has an unambiguous correlation value.
* Uses a state machine to cycle through various stages.
*
*/
class PulseLatencyAnalyzer : public LatencyAnalyzer {
public:
PulseLatencyAnalyzer() : LatencyAnalyzer() {
int32_t maxLatencyFrames = getSampleRate() * kMaxLatencyMillis / kMillisPerSecond;
int32_t numPulseBits = getSampleRate() * kPulseLengthMillis
/ (kFramesPerEncodedBit * kMillisPerSecond);
int32_t pulseLength = numPulseBits * kFramesPerEncodedBit;
mFramesToRecord = pulseLength + maxLatencyFrames;
LOGD("PulseLatencyAnalyzer: allocate recording with %d frames", mFramesToRecord);
mAudioRecording.allocate(mFramesToRecord);
mAudioRecording.setSampleRate(getSampleRate());
generateRandomPulse(pulseLength);
}
void generateRandomPulse(int32_t pulseLength) {
mPulse.allocate(pulseLength);
RandomPulseGenerator pulser(kFramesPerEncodedBit);
for (int i = 0; i < pulseLength; i++) {
mPulse.write(pulser.nextFloat());
}
}
int getState() override {
return mState;
}
void setSampleRate(int32_t sampleRate) override {
LoopbackProcessor::setSampleRate(sampleRate);
mAudioRecording.setSampleRate(sampleRate);
}
void reset() override {
LoopbackProcessor::reset();
mDownCounter = getSampleRate() / 2;
mLoopCounter = 0;
mPulseCursor = 0;
mBackgroundSumSquare = 0.0f;
mBackgroundSumCount = 0;
mBackgroundRMS = 0.0f;
mSignalRMS = 0.0f;
LOGD("state reset to STATE_MEASURE_BACKGROUND");
mState = STATE_MEASURE_BACKGROUND;
mAudioRecording.clear();
mLatencyReport.reset();
}
bool hasEnoughData() {
return mAudioRecording.isFull();
}
bool isDone() override {
return mState == STATE_DONE;
}
int32_t getProgress() override {
return mAudioRecording.size();
}
void analyze() override {
LOGD("PulseLatencyAnalyzer ---------------");
LOGD(LOOPBACK_RESULT_TAG "test.state = %8d", mState);
LOGD(LOOPBACK_RESULT_TAG "test.state.name = %8s", convertStateToText(mState));
LOGD(LOOPBACK_RESULT_TAG "background.rms = %8f", mBackgroundRMS);
int32_t newResult = RESULT_OK;
if (mState != STATE_GOT_DATA) {
LOGD("WARNING - Bad state. Check volume on device.");
// setResult(ERROR_INVALID_STATE);
} else {
LOGD("Please wait several seconds for cross-correlation to complete.");
float gain = mAudioRecording.normalize(1.0f);
measureLatencyFromPulse(mAudioRecording,
mPulse,
kFramesPerEncodedBit,
&mLatencyReport);
if (mLatencyReport.confidence < kMinimumConfidence) {
LOGD(" ERROR - confidence too low!");
newResult = ERROR_CONFIDENCE;
} else {
mSignalRMS = calculateRootMeanSquare(
&mAudioRecording.getData()[mLatencyReport.latencyInFrames], mPulse.size())
/ gain;
}
#if OBOE_ENABLE_LOGGING
double latencyMillis = kMillisPerSecond * (double) mLatencyReport.latencyInFrames
/ getSampleRate();
#endif
LOGD(LOOPBACK_RESULT_TAG "latency.frames = %8d",
mLatencyReport.latencyInFrames);
LOGD(LOOPBACK_RESULT_TAG "latency.msec = %8.2f",
latencyMillis);
LOGD(LOOPBACK_RESULT_TAG "latency.confidence = %8.6f",
mLatencyReport.confidence);
}
mState = STATE_DONE;
if (getResult() == RESULT_OK) {
setResult(newResult);
}
}
int32_t getMeasuredLatency() override {
return mLatencyReport.latencyInFrames;
}
double getMeasuredConfidence() override {
return mLatencyReport.confidence;
}
double getBackgroundRMS() override {
return mBackgroundRMS;
}
double getSignalRMS() override {
return mSignalRMS;
}
void printStatus() override {
LOGD("st = %d", mState);
}
result_code processInputFrame(float *frameData, int channelCount) override {
echo_state nextState = mState;
mLoopCounter++;
switch (mState) {
case STATE_MEASURE_BACKGROUND:
// Measure background RMS on channel 0
mBackgroundSumSquare += frameData[0] * frameData[0];
mBackgroundSumCount++;
mDownCounter--;
if (mDownCounter <= 0) {
mBackgroundRMS = sqrtf(mBackgroundSumSquare / mBackgroundSumCount);
nextState = STATE_IN_PULSE;
mPulseCursor = 0;
LOGD("LatencyAnalyzer state => STATE_SENDING_PULSE");
}
break;
case STATE_IN_PULSE:
// Record input until the mAudioRecording is full.
mAudioRecording.write(frameData, channelCount, 1);
if (hasEnoughData()) {
LOGD("LatencyAnalyzer state => STATE_GOT_DATA");
nextState = STATE_GOT_DATA;
}
break;
case STATE_GOT_DATA:
case STATE_DONE:
default:
break;
}
mState = nextState;
return RESULT_OK;
}
result_code processOutputFrame(float *frameData, int channelCount) override {
switch (mState) {
case STATE_IN_PULSE:
if (mPulseCursor < mPulse.size()) {
float pulseSample = mPulse.getData()[mPulseCursor++];
for (int i = 0; i < channelCount; i++) {
frameData[i] = pulseSample;
}
} else {
for (int i = 0; i < channelCount; i++) {
frameData[i] = 0;
}
}
break;
case STATE_MEASURE_BACKGROUND:
case STATE_GOT_DATA:
case STATE_DONE:
default:
for (int i = 0; i < channelCount; i++) {
frameData[i] = 0.0f; // silence
}
break;
}
return RESULT_OK;
}
private:
enum echo_state {
STATE_MEASURE_BACKGROUND,
STATE_IN_PULSE,
STATE_GOT_DATA, // must match RoundTripLatencyActivity.java
STATE_DONE,
};
const char *convertStateToText(echo_state state) {
const char *result = "Unknown";
switch(state) {
case STATE_MEASURE_BACKGROUND:
result = "INIT";
break;
case STATE_IN_PULSE:
result = "PULSE";
break;
case STATE_GOT_DATA:
result = "GOT_DATA";
break;
case STATE_DONE:
result = "DONE";
break;
}
return result;
}
int32_t mDownCounter = 500;
int32_t mLoopCounter = 0;
echo_state mState = STATE_MEASURE_BACKGROUND;
static constexpr int32_t kFramesPerEncodedBit = 8; // multiple of 2
static constexpr int32_t kPulseLengthMillis = 500;
AudioRecording mPulse;
int32_t mPulseCursor = 0;
float mBackgroundSumSquare = 0.0f;
int32_t mBackgroundSumCount = 0;
float mBackgroundRMS = 0.0f;
float mSignalRMS = 0.0f;
int32_t mFramesToRecord = 0;
AudioRecording mAudioRecording; // contains only the input after starting the pulse
LatencyReport mLatencyReport;
};
#endif // ANALYZER_LATENCY_ANALYZER_H
@@ -0,0 +1,96 @@
/*
* Copyright 2019 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef ANALYZER_MANCHESTER_ENCODER_H
#define ANALYZER_MANCHESTER_ENCODER_H
#include <cstdint>
/**
* Encode bytes using Manchester Coding scheme.
*
* Manchester Code is self clocking.
* There is a transition in the middle of every bit.
* Zero is high then low.
* One is low then high.
*
* This avoids having long DC sections that would droop when
* passed though analog circuits with AC coupling.
*
* IEEE 802.3 compatible.
*/
class ManchesterEncoder {
public:
ManchesterEncoder(int samplesPerPulse)
: mSamplesPerPulse(samplesPerPulse)
, mSamplesPerPulseHalf(samplesPerPulse / 2)
, mCursor(samplesPerPulse) {
}
/**
* This will be called when the next byte is needed.
* @return
*/
virtual uint8_t onNextByte() = 0;
/**
* Generate the next floating point sample.
* @return
*/
virtual float nextFloat() {
advanceSample();
if (mCurrentBit) {
return (mCursor < mSamplesPerPulseHalf) ? -1.0f : 1.0f; // one
} else {
return (mCursor < mSamplesPerPulseHalf) ? 1.0f : -1.0f; // zero
}
}
protected:
/**
* This will be called when a new bit is ready to be encoded.
* It can be used to prepare the encoded samples.
* @param current
*/
virtual void onNextBit(bool current) {};
void advanceSample() {
// Are we ready for a new bit?
if (++mCursor >= mSamplesPerPulse) {
mCursor = 0;
if (mBitsLeft == 0) {
mCurrentByte = onNextByte();
mBitsLeft = 8;
}
--mBitsLeft;
mCurrentBit = (mCurrentByte >> mBitsLeft) & 1;
onNextBit(mCurrentBit);
}
}
bool getCurrentBit() {
return mCurrentBit;
}
const int mSamplesPerPulse;
const int mSamplesPerPulseHalf;
int mCursor;
int mBitsLeft = 0;
uint8_t mCurrentByte = 0;
bool mCurrentBit = false;
};
#endif //ANALYZER_MANCHESTER_ENCODER_H
@@ -0,0 +1,48 @@
/*
* Copyright 2015 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef ANALYZER_PEAK_DETECTOR_H
#define ANALYZER_PEAK_DETECTOR_H
#include <math.h>
class PeakDetector {
public:
void reset() {
mLevel = 0.0;
}
double process(double input) {
mLevel *= mDecay;
input = fabs(input);
if (input > mLevel) {
mLevel = input;
}
return mLevel;
}
double getLevel() {
return mLevel;
}
private:
static constexpr float kDefaultDecay = 0.99f;
double mLevel = 0.0;
double mDecay = kDefaultDecay;
};
#endif //ANALYZER_PEAK_DETECTOR_H
@@ -0,0 +1,57 @@
/*
* Copyright (C) 2017 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef ANALYZER_PSEUDORANDOM_H
#define ANALYZER_PSEUDORANDOM_H
#include <cctype>
class PseudoRandom {
public:
PseudoRandom() {}
PseudoRandom(int64_t seed)
: mSeed(seed)
{}
/**
* Returns the next random double from -1.0 to 1.0
*
* @return value from -1.0 to 1.0
*/
double nextRandomDouble() {
return nextRandomInteger() * (0.5 / (((int32_t)1) << 30));
}
/** Calculate random 32 bit number using linear-congruential method.
*/
int32_t nextRandomInteger() {
#if __has_builtin(__builtin_mul_overflow) && __has_builtin(__builtin_add_overflow)
int64_t prod;
// Use values for 64-bit sequence from MMIX by Donald Knuth.
__builtin_mul_overflow(mSeed, (int64_t)6364136223846793005, &prod);
__builtin_add_overflow(prod, (int64_t)1442695040888963407, &mSeed);
#else
mSeed = (mSeed * (int64_t)6364136223846793005) + (int64_t)1442695040888963407;
#endif
return (int32_t) (mSeed >> 32); // The higher bits have a longer sequence.
}
private:
int64_t mSeed = 99887766;
};
#endif //ANALYZER_PSEUDORANDOM_H
@@ -0,0 +1,41 @@
/*
* Copyright 2015 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef ANALYZER_RANDOM_PULSE_GENERATOR_H
#define ANALYZER_RANDOM_PULSE_GENERATOR_H
#include <stdlib.h>
#include "RoundedManchesterEncoder.h"
/**
* Encode random ones and zeros using Manchester Code per IEEE 802.3.
*/
class RandomPulseGenerator : public RoundedManchesterEncoder {
public:
RandomPulseGenerator(int samplesPerPulse)
: RoundedManchesterEncoder(samplesPerPulse) {
}
/**
* This will be called when the next byte is needed.
* @return random byte
*/
uint8_t onNextByte() override {
return static_cast<uint8_t>(rand() & 0x00FF);
}
};
#endif //ANALYZER_RANDOM_PULSE_GENERATOR_H
@@ -0,0 +1,89 @@
/*
* Copyright 2019 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef ANALYZER_ROUNDED_MANCHESTER_ENCODER_H
#define ANALYZER_ROUNDED_MANCHESTER_ENCODER_H
#include <math.h>
#include <memory.h>
#include <stdlib.h>
#include "ManchesterEncoder.h"
/**
* Encode bytes using Manchester Code.
* Round the edges using a half cosine to reduce ringing caused by a hard edge.
*/
class RoundedManchesterEncoder : public ManchesterEncoder {
public:
RoundedManchesterEncoder(int samplesPerPulse)
: ManchesterEncoder(samplesPerPulse) {
int rampSize = samplesPerPulse / 4;
mZeroAfterZero = std::make_unique<float[]>(samplesPerPulse);
mZeroAfterOne = std::make_unique<float[]>(samplesPerPulse);
int i = 0;
for (int j = 0; j < rampSize; j++) {
float phase = (j + 1) * M_PI / rampSize;
float sample = -cosf(phase);
mZeroAfterZero[i] = sample;
mZeroAfterOne[i] = 1.0f;
i++;
}
for (int j = 0; j < rampSize; j++) {
mZeroAfterZero[i] = 1.0f;
mZeroAfterOne[i] = 1.0f;
i++;
}
for (int j = 0; j < rampSize; j++) {
float phase = (j + 1) * M_PI / rampSize;
float sample = cosf(phase);
mZeroAfterZero[i] = sample;
mZeroAfterOne[i] = sample;
i++;
}
for (int j = 0; j < rampSize; j++) {
mZeroAfterZero[i] = -1.0f;
mZeroAfterOne[i] = -1.0f;
i++;
}
}
void onNextBit(bool current) override {
// Do we need to use the rounded edge?
mCurrentSamples = (current ^ mPreviousBit)
? mZeroAfterOne.get()
: mZeroAfterZero.get();
mPreviousBit = current;
}
float nextFloat() override {
advanceSample();
float output = mCurrentSamples[mCursor];
if (getCurrentBit()) output = -output;
return output;
}
private:
bool mPreviousBit = false;
float *mCurrentSamples = nullptr;
std::unique_ptr<float[]> mZeroAfterZero;
std::unique_ptr<float[]> mZeroAfterOne;
};
#endif //ANALYZER_ROUNDED_MANCHESTER_ENCODER_H
@@ -0,0 +1,41 @@
/*
* Copyright (C) 2015 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
#ifndef NATIVE_AUDIO_ANDROID_DEBUG_H_H
#define NATIVE_AUDIO_ANDROID_DEBUG_H_H
#include <android/log.h>
#if 1
#define MODULE_NAME "OboeAudio"
#define LOGV(...) __android_log_print(ANDROID_LOG_VERBOSE, MODULE_NAME, __VA_ARGS__)
#define LOGD(...) __android_log_print(ANDROID_LOG_DEBUG, MODULE_NAME, __VA_ARGS__)
#define LOGI(...) __android_log_print(ANDROID_LOG_INFO, MODULE_NAME, __VA_ARGS__)
#define LOGW(...) __android_log_print(ANDROID_LOG_WARN, MODULE_NAME, __VA_ARGS__)
#define LOGE(...) __android_log_print(ANDROID_LOG_ERROR, MODULE_NAME, __VA_ARGS__)
#define LOGF(...) __android_log_print(ANDROID_LOG_FATAL, MODULE_NAME, __VA_ARGS__)
#else
#define LOGV(...)
#define LOGD(...)
#define LOGI(...)
#define LOGW(...)
#define LOGE(...)
#define LOGF(...)
#endif
#endif //NATIVE_AUDIO_ANDROID_DEBUG_H_H
@@ -0,0 +1,35 @@
/*
* Copyright 2019 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <math.h>
#include "ExponentialShape.h"
ExponentialShape::ExponentialShape()
: FlowGraphFilter(1) {
}
int32_t ExponentialShape::onProcess(int32_t numFrames) {
float *inputs = input.getBuffer();
float *outputs = output.getBuffer();
for (int i = 0; i < numFrames; i++) {
float normalizedPhase = (inputs[i] * 0.5) + 0.5;
outputs[i] = mMinimum * powf(mRatio, normalizedPhase);
}
return numFrames;
}
@@ -0,0 +1,70 @@
/*
* Copyright 2019 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef OBOETESTER_EXPONENTIAL_SHAPE_H
#define OBOETESTER_EXPONENTIAL_SHAPE_H
#include "flowgraph/FlowGraphNode.h"
/**
* Generate a exponential sweep between min and max.
*
* The waveform is not band-limited so it will have aliasing artifacts at higher frequencies.
*/
class ExponentialShape : public flowgraph::FlowGraphFilter {
public:
ExponentialShape();
int32_t onProcess(int32_t numFrames) override;
float getMinimum() const {
return mMinimum;
}
/**
* The minimum and maximum should not span zero.
* They should both be positive or both negative.
*
* @param minimum
*/
void setMinimum(float minimum) {
mMinimum = minimum;
mRatio = mMaximum / mMinimum;
}
float getMaximum() const {
return mMaximum;
}
/**
* The minimum and maximum should not span zero.
* They should both be positive or both negative.
*
* @param maximum
*/
void setMaximum(float maximum) {
mMaximum = maximum;
mRatio = mMaximum / mMinimum;
}
private:
float mMinimum = 0.0;
float mMaximum = 1.0;
float mRatio = 1.0;
};
#endif //OBOETESTER_EXPONENTIAL_SHAPE_H
@@ -0,0 +1,42 @@
/*
* Copyright 2018 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <math.h>
#include <unistd.h>
#include "ImpulseOscillator.h"
ImpulseOscillator::ImpulseOscillator()
: OscillatorBase() {
}
int32_t ImpulseOscillator::onProcess(int32_t numFrames) {
const float *frequencies = frequency.getBuffer();
const float *amplitudes = amplitude.getBuffer();
float *buffer = output.getBuffer();
for (int i = 0; i < numFrames; i++) {
float value = 0.0f;
mPhase += mFrequencyToPhaseIncrement * frequencies[i];
if (mPhase >= 1.0f) {
value = amplitudes[i]; // spike
mPhase -= 2.0f;
}
*buffer++ = value;
}
return numFrames;
}
@@ -0,0 +1,39 @@
/*
* Copyright 2018 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef NATIVEOBOE_IMPULSE_GENERATOR_H
#define NATIVEOBOE_IMPULSE_GENERATOR_H
#include <unistd.h>
#include <sys/types.h>
#include "flowgraph/FlowGraphNode.h"
#include "OscillatorBase.h"
/**
* Generate a raw impulse equal to the amplitude.
* The output baseline is zero.
*
* The waveform is not band-limited so it will have aliasing artifacts at higher frequencies.
*/
class ImpulseOscillator : public OscillatorBase {
public:
ImpulseOscillator();
int32_t onProcess(int32_t numFrames) override;
};
#endif //NATIVEOBOE_IMPULSE_GENERATOR_H
@@ -0,0 +1,36 @@
/*
* Copyright 2019 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "LinearShape.h"
using namespace flowgraph;
LinearShape::LinearShape()
: FlowGraphFilter(1) {
}
int32_t LinearShape::onProcess(int numFrames) {
float *inputs = input.getBuffer();
float *outputs = output.getBuffer();
for (int i = 0; i < numFrames; i++) {
float normalizedPhase = (inputs[i] * 0.5f) + 0.5f; // from 0.0 to 1.0
outputs[i] = mMinimum + (normalizedPhase * (mMaximum - mMinimum));
}
return numFrames;
}
@@ -0,0 +1,53 @@
/*
* Copyright 2019 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef OBOETESTER_LINEAR_SHAPE_H
#define OBOETESTER_LINEAR_SHAPE_H
#include "flowgraph/FlowGraphNode.h"
/**
* Convert an input between -1.0 and +1.0 to a linear region between min and max.
*/
class LinearShape : public flowgraph::FlowGraphFilter {
public:
LinearShape();
int32_t onProcess(int numFrames) override;
float getMinimum() const {
return mMinimum;
}
void setMinimum(float minimum) {
mMinimum = minimum;
}
float getMaximum() const {
return mMaximum;
}
void setMaximum(float maximum) {
mMaximum = maximum;
}
private:
float mMinimum = 0.0;
float mMaximum = 1.0;
};
#endif //OBOETESTER_LINEAR_SHAPE_H
@@ -0,0 +1,26 @@
/*
* Copyright 2018 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "OscillatorBase.h"
using namespace flowgraph;
OscillatorBase::OscillatorBase()
: frequency(*this, 1)
, amplitude(*this, 1)
, output(*this, 1) {
setSampleRate(48000);
}
@@ -0,0 +1,100 @@
/*
* Copyright 2018 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef NATIVEOBOE_OSCILLATORBASE_H
#define NATIVEOBOE_OSCILLATORBASE_H
#include "flowgraph/FlowGraphNode.h"
/**
* Base class for various oscillators.
* The oscillator has a phase that ranges from -1.0 to +1.0.
* That makes it easier to implement simple algebraic waveforms.
*
* Subclasses must implement onProcess().
*
* This module has "frequency" and "amplitude" ports for control.
*/
class OscillatorBase : public flowgraph::FlowGraphNode {
public:
OscillatorBase();
virtual ~OscillatorBase() = default;
void setSampleRate(float sampleRate) {
mSampleRate = sampleRate;
mFrequencyToPhaseIncrement = 2.0f / sampleRate; // -1 to +1 is a range of 2
}
float getSampleRate() {
return mSampleRate;
}
/**
* This can be used to set the initial phase of an oscillator before starting.
* This is mostly used with an LFO.
* Calling this while the oscillator is running will cause sharp pops.
* @param phase between -1.0 and +1.0
*/
void setPhase(float phase) {
mPhase = phase;
}
float getPhase() {
return mPhase;
}
/**
* Control the frequency of the oscillator in Hz.
*/
flowgraph::FlowGraphPortFloatInput frequency;
/**
* Control the linear amplitude of the oscillator.
* Silence is 0.0.
* A typical full amplitude would be 1.0.
*/
flowgraph::FlowGraphPortFloatInput amplitude;
flowgraph::FlowGraphPortFloatOutput output;
protected:
/**
* Increment phase based on frequency in Hz.
* Frequency may be positive or negative.
*
* Frequency should not exceed +/- Nyquist Rate.
* Nyquist Rate is sampleRate/2.
*/
float incrementPhase(float frequency) {
mPhase += frequency * mFrequencyToPhaseIncrement;
// Wrap phase in the range of -1 to +1
if (mPhase >= 1.0f) {
mPhase -= 2.0f;
} else if (mPhase < -1.0f) {
mPhase += 2.0f;
}
return mPhase;
}
float mPhase = 0.0f; // phase that ranges from -1.0 to +1.0
float mSampleRate = 0.0f;
float mFrequencyToPhaseIncrement = 0.0f; // scaler for converting frequency to phase increment
};
#endif //NATIVEOBOE_OSCILLATORBASE_H
@@ -0,0 +1,39 @@
/*
* Copyright 2015 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <math.h>
#include <unistd.h>
#include "SawtoothOscillator.h"
SawtoothOscillator::SawtoothOscillator()
: OscillatorBase() {
}
int32_t SawtoothOscillator::onProcess(int32_t numFrames) {
const float *frequencies = frequency.getBuffer();
const float *amplitudes = amplitude.getBuffer();
float *buffer = output.getBuffer();
// Use the phase directly as a non-band-limited "sawtooth".
// WARNING: This will generate unpleasant aliasing artifacts at higher frequencies.
for (int i = 0; i < numFrames; i++) {
float phase = incrementPhase(frequencies[i]); // phase ranges from -1 to +1
*buffer++ = phase * amplitudes[i];
}
return numFrames;
}
@@ -0,0 +1,36 @@
/*
* Copyright 2015 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef FLOWGRAPH_SAWTOOTH_OSCILLATOR_H
#define FLOWGRAPH_SAWTOOTH_OSCILLATOR_H
#include <unistd.h>
#include "OscillatorBase.h"
/**
* Oscillator that generates a sawtooth wave at the specified frequency and amplitude.
*
* The waveform is not band-limited so it will have aliasing artifacts at higher frequencies.
*/
class SawtoothOscillator : public OscillatorBase {
public:
SawtoothOscillator();
int32_t onProcess(int32_t numFrames) override;
};
#endif //FLOWGRAPH_SAWTOOTH_OSCILLATOR_H
@@ -0,0 +1,42 @@
/*
* Copyright 2015 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <math.h>
#include <unistd.h>
#include "SineOscillator.h"
/*
* This calls sinf() so it is not very efficient.
* A more efficient implementation might use a wave-table or a polynomial.
*/
SineOscillator::SineOscillator()
: OscillatorBase() {
}
int32_t SineOscillator::onProcess(int32_t numFrames) {
const float *frequencies = frequency.getBuffer();
const float *amplitudes = amplitude.getBuffer();
float *buffer = output.getBuffer();
// Generate sine wave.
for (int i = 0; i < numFrames; i++) {
float phase = incrementPhase(frequencies[i]); // phase ranges from -1 to +1
*buffer++ = sinf(phase * M_PI) * amplitudes[i];
}
return numFrames;
}
@@ -0,0 +1,34 @@
/*
* Copyright 2015 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef FLOWGRAPH_SINE_OSCILLATOR_H
#define FLOWGRAPH_SINE_OSCILLATOR_H
#include <unistd.h>
#include "OscillatorBase.h"
/**
* Oscillator that generates a sine wave at the specified frequency and amplitude.
*/
class SineOscillator : public OscillatorBase {
public:
SineOscillator();
int32_t onProcess(int32_t numFrames) override;
};
#endif //FLOWGRAPH_SINE_OSCILLATOR_H
@@ -0,0 +1,40 @@
/*
* Copyright 2015 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <math.h>
#include <unistd.h>
#include "TriangleOscillator.h"
TriangleOscillator::TriangleOscillator()
: OscillatorBase() {
}
int32_t TriangleOscillator::onProcess(int32_t numFrames) {
const float *frequencies = frequency.getBuffer();
const float *amplitudes = amplitude.getBuffer();
float *buffer = output.getBuffer();
// Use the phase directly as a non-band-limited "triangle".
// WARNING: This will generate unpleasant aliasing artifacts at higher frequencies.
for (int i = 0; i < numFrames; i++) {
float phase = incrementPhase(frequencies[i]); // phase ranges from -1 to +1
float triangle = 2.0f * ((phase < 0.0f) ? (0.5f + phase): (0.5f - phase));
*buffer++ = triangle * amplitudes[i];
}
return numFrames;
}
@@ -0,0 +1,39 @@
/*
* Copyright 2019 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef FLOWGRAPH_TRIANGLE_OSCILLATOR_H
#define FLOWGRAPH_TRIANGLE_OSCILLATOR_H
#include <unistd.h>
#include "OscillatorBase.h"
/**
* Oscillator that generates a triangle wave at the specified frequency and amplitude.
*
* The triangle output rises from -1 to +1 when the phase is between -1 and 0.
* The triangle output falls from +1 to 11 when the phase is between 0 and +1.
*
* The waveform is not band-limited so it will have aliasing artifacts at higher frequencies.
*/
class TriangleOscillator : public OscillatorBase {
public:
TriangleOscillator();
int32_t onProcess(int32_t numFrames) override;
};
#endif //FLOWGRAPH_TRIANGLE_OSCILLATOR_H
@@ -0,0 +1,625 @@
/*
* Copyright 2015 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#define MODULE_NAME "OboeTester"
#include <cassert>
#include <cstring>
#include <jni.h>
#include <stdint.h>
#include <thread>
#include "common/OboeDebug.h"
#include "oboe/Oboe.h"
#include "NativeAudioContext.h"
NativeAudioContext engine;
/*********************************************************************************/
/********************** JNI Prototypes *****************************************/
/*********************************************************************************/
extern "C" {
JNIEXPORT jint JNICALL
Java_com_google_sample_oboe_manualtest_OboeAudioStream_openNative(JNIEnv *env, jobject,
jint nativeApi,
jint sampleRate,
jint channelCount,
jint format,
jint sharingMode,
jint performanceMode,
jint inputPreset,
jint deviceId,
jint sessionId,
jint framesPerBurst,
jboolean channelConversionAllowed,
jboolean formatConversionAllowed,
jint rateConversionQuality,
jboolean isMMap,
jboolean isInput);
JNIEXPORT void JNICALL
Java_com_google_sample_oboe_manualtest_OboeAudioStream_close(JNIEnv *env, jobject, jint);
JNIEXPORT jint JNICALL
Java_com_google_sample_oboe_manualtest_OboeAudioStream_setThresholdInFrames(JNIEnv *env, jobject, jint, jint);
JNIEXPORT jint JNICALL
Java_com_google_sample_oboe_manualtest_OboeAudioStream_getThresholdInFrames(JNIEnv *env, jobject, jint);
JNIEXPORT jint JNICALL
Java_com_google_sample_oboe_manualtest_OboeAudioStream_getBufferCapacityInFrames(JNIEnv *env, jobject, jint);
JNIEXPORT jint JNICALL
Java_com_google_sample_oboe_manualtest_OboeAudioStream_setNativeApi(JNIEnv *env, jobject, jint, jint);
JNIEXPORT void JNICALL
Java_com_google_sample_oboe_manualtest_OboeAudioStream_setUseCallback(JNIEnv *env, jclass type,
jboolean useCallback);
JNIEXPORT void JNICALL
Java_com_google_sample_oboe_manualtest_OboeAudioStream_setCallbackReturnStop(JNIEnv *env,
jclass type,
jboolean b);
JNIEXPORT void JNICALL
Java_com_google_sample_oboe_manualtest_OboeAudioStream_setCallbackSize(JNIEnv *env, jclass type,
jint callbackSize);
// ================= OboeAudioOutputStream ================================
JNIEXPORT void JNICALL
Java_com_google_sample_oboe_manualtest_OboeAudioOutputStream_setToneEnabled(JNIEnv *env, jobject, jboolean);
JNIEXPORT void JNICALL
Java_com_google_sample_oboe_manualtest_OboeAudioOutputStream_setToneType(JNIEnv *env, jobject, jint);
JNIEXPORT void JNICALL
Java_com_google_sample_oboe_manualtest_OboeAudioOutputStream_setAmplitude(JNIEnv *env, jobject, jdouble);
/*********************************************************************************/
/********************** JNI Implementations *************************************/
/*********************************************************************************/
JNIEXPORT jboolean JNICALL
Java_com_google_sample_oboe_manualtest_NativeEngine_isMMapSupported(JNIEnv *env, jclass type) {
return AAudioExtensions::getInstance().isMMapSupported();
}
JNIEXPORT jboolean JNICALL
Java_com_google_sample_oboe_manualtest_NativeEngine_isMMapExclusiveSupported(JNIEnv *env, jclass type) {
return AAudioExtensions::getInstance().isMMapExclusiveSupported();
}
JNIEXPORT void JNICALL
Java_com_google_sample_oboe_manualtest_NativeEngine_setWorkaroundsEnabled(JNIEnv *env, jclass type,
jboolean enabled) {
oboe::OboeGlobals::setWorkaroundsEnabled(enabled);
}
JNIEXPORT jint JNICALL
Java_com_google_sample_oboe_manualtest_OboeAudioStream_openNative(
JNIEnv *env, jobject synth,
jint nativeApi,
jint sampleRate,
jint channelCount,
jint format,
jint sharingMode,
jint performanceMode,
jint inputPreset,
jint deviceId,
jint sessionId,
jint framesPerBurst,
jboolean channelConversionAllowed,
jboolean formatConversionAllowed,
jint rateConversionQuality,
jboolean isMMap,
jboolean isInput) {
LOGD("OboeAudioStream_openNative: sampleRate = %d, framesPerBurst = %d", sampleRate, framesPerBurst);
return (jint) engine.getCurrentActivity()->open(nativeApi,
sampleRate,
channelCount,
format,
sharingMode,
performanceMode,
inputPreset,
deviceId,
sessionId,
framesPerBurst,
channelConversionAllowed,
formatConversionAllowed,
rateConversionQuality,
isMMap,
isInput);
}
JNIEXPORT jint JNICALL
Java_com_google_sample_oboe_manualtest_TestAudioActivity_startNative(JNIEnv *env, jobject) {
return (jint) engine.getCurrentActivity()->start();
}
JNIEXPORT jint JNICALL
Java_com_google_sample_oboe_manualtest_TestAudioActivity_pauseNative(JNIEnv *env, jobject) {
return (jint) engine.getCurrentActivity()->pause();
}
JNIEXPORT jint JNICALL
Java_com_google_sample_oboe_manualtest_TestAudioActivity_stopNative(JNIEnv *env, jobject) {
return (jint) engine.getCurrentActivity()->stop();
}
JNIEXPORT jint JNICALL
Java_com_google_sample_oboe_manualtest_TestAudioActivity_getFramesPerCallback(JNIEnv *env, jobject) {
return (jint) engine.getCurrentActivity()->getFramesPerCallback();
}
JNIEXPORT jint JNICALL
Java_com_google_sample_oboe_manualtest_OboeAudioStream_startPlaybackNative(JNIEnv *env, jobject) {
return (jint) engine.getCurrentActivity()->startPlayback();
}
JNIEXPORT void JNICALL
Java_com_google_sample_oboe_manualtest_OboeAudioStream_close(JNIEnv *env, jobject, jint streamIndex) {
engine.getCurrentActivity()->close(streamIndex);
}
JNIEXPORT jint JNICALL
Java_com_google_sample_oboe_manualtest_OboeAudioStream_setBufferSizeInFrames(
JNIEnv *env, jobject, jint streamIndex, jint threshold) {
oboe::AudioStream *oboeStream = engine.getCurrentActivity()->getStream(streamIndex);
if (oboeStream != nullptr) {
auto result = oboeStream->setBufferSizeInFrames(threshold);
return (!result)
? (jint) result.error()
: (jint) result.value();
}
return (jint) oboe::Result::ErrorNull;
}
JNIEXPORT jint JNICALL
Java_com_google_sample_oboe_manualtest_OboeAudioStream_getBufferSizeInFrames(
JNIEnv *env, jobject, jint streamIndex) {
jint result = (jint) oboe::Result::ErrorNull;
oboe::AudioStream *oboeStream = engine.getCurrentActivity()->getStream(streamIndex);
if (oboeStream != nullptr) {
result = oboeStream->getBufferSizeInFrames();
}
return result;
}
JNIEXPORT jint JNICALL
Java_com_google_sample_oboe_manualtest_OboeAudioStream_getBufferCapacityInFrames(
JNIEnv *env, jobject, jint streamIndex) {
jint result = (jint) oboe::Result::ErrorNull;
oboe::AudioStream *oboeStream = engine.getCurrentActivity()->getStream(streamIndex);
if (oboeStream != nullptr) {
result = oboeStream->getBufferCapacityInFrames();
}
return result;
}
static int convertAudioApiToNativeApi(oboe::AudioApi audioApi) {
switch(audioApi) {
case oboe::AudioApi::Unspecified:
return NATIVE_MODE_UNSPECIFIED;
case oboe::AudioApi::OpenSLES:
return NATIVE_MODE_OPENSLES;
case oboe::AudioApi::AAudio:
return NATIVE_MODE_AAUDIO;
default:
return -1;
}
}
JNIEXPORT jint JNICALL
Java_com_google_sample_oboe_manualtest_OboeAudioStream_getNativeApi(
JNIEnv *env, jobject, jint streamIndex) {
jint result = (jint) oboe::Result::ErrorNull;
oboe::AudioStream *oboeStream = engine.getCurrentActivity()->getStream(streamIndex);
if (oboeStream != nullptr) {
oboe::AudioApi audioApi = oboeStream->getAudioApi();
result = convertAudioApiToNativeApi(audioApi);
LOGD("OboeAudioStream_getNativeApi got %d", result);
}
return result;
}
JNIEXPORT jint JNICALL
Java_com_google_sample_oboe_manualtest_OboeAudioStream_getSampleRate(
JNIEnv *env, jobject, jint streamIndex) {
jint result = (jint) oboe::Result::ErrorNull;
oboe::AudioStream *oboeStream = engine.getCurrentActivity()->getStream(streamIndex);
if (oboeStream != nullptr) {
result = oboeStream->getSampleRate();
}
return result;
}
JNIEXPORT jint JNICALL
Java_com_google_sample_oboe_manualtest_OboeAudioStream_getSharingMode(
JNIEnv *env, jobject, jint streamIndex) {
jint result = (jint) oboe::Result::ErrorNull;
oboe::AudioStream *oboeStream = engine.getCurrentActivity()->getStream(streamIndex);
if (oboeStream != nullptr) {
result = (jint) oboeStream->getSharingMode();
}
return result;
}
JNIEXPORT jint JNICALL
Java_com_google_sample_oboe_manualtest_OboeAudioStream_getPerformanceMode(
JNIEnv *env, jobject, jint streamIndex) {
jint result = (jint) oboe::Result::ErrorNull;
oboe::AudioStream *oboeStream = engine.getCurrentActivity()->getStream(streamIndex);
if (oboeStream != nullptr) {
result = (jint) oboeStream->getPerformanceMode();
}
return result;
}
JNIEXPORT jint JNICALL
Java_com_google_sample_oboe_manualtest_OboeAudioStream_getInputPreset(
JNIEnv *env, jobject, jint streamIndex) {
jint result = (jint) oboe::Result::ErrorNull;
oboe::AudioStream *oboeStream = engine.getCurrentActivity()->getStream(streamIndex);
if (oboeStream != nullptr) {
result = (jint) oboeStream->getInputPreset();
}
return result;
}
JNIEXPORT jint JNICALL
Java_com_google_sample_oboe_manualtest_OboeAudioStream_getFramesPerBurst(
JNIEnv *env, jobject, jint streamIndex) {
jint result = (jint) oboe::Result::ErrorNull;
oboe::AudioStream *oboeStream = engine.getCurrentActivity()->getStream(streamIndex);
if (oboeStream != nullptr) {
result = oboeStream->getFramesPerBurst();
}
return result;
}
JNIEXPORT jint JNICALL
Java_com_google_sample_oboe_manualtest_OboeAudioStream_getChannelCount(
JNIEnv *env, jobject, jint streamIndex) {
jint result = (jint) oboe::Result::ErrorNull;
oboe::AudioStream *oboeStream = engine.getCurrentActivity()->getStream(streamIndex);
if (oboeStream != nullptr) {
result = oboeStream->getChannelCount();
}
return result;
}
JNIEXPORT jint JNICALL
Java_com_google_sample_oboe_manualtest_OboeAudioStream_getFormat(JNIEnv *env, jobject instance, jint streamIndex) {
jint result = (jint) oboe::Result::ErrorNull;
oboe::AudioStream *oboeStream = engine.getCurrentActivity()->getStream(streamIndex);
if (oboeStream != nullptr) {
result = (jint) oboeStream->getFormat();
}
return result;
}
JNIEXPORT jint JNICALL
Java_com_google_sample_oboe_manualtest_OboeAudioStream_getDeviceId(
JNIEnv *env, jobject, jint streamIndex) {
jint result = (jint) oboe::Result::ErrorNull;
oboe::AudioStream *oboeStream = engine.getCurrentActivity()->getStream(streamIndex);
if (oboeStream != nullptr) {
result = oboeStream->getDeviceId();
}
return result;
}
JNIEXPORT jint JNICALL
Java_com_google_sample_oboe_manualtest_OboeAudioStream_getSessionId(
JNIEnv *env, jobject, jint streamIndex) {
jint result = (jint) oboe::Result::ErrorNull;
oboe::AudioStream *oboeStream = engine.getCurrentActivity()->getStream(streamIndex);
if (oboeStream != nullptr) {
result = oboeStream->getSessionId();
}
return result;
}
JNIEXPORT jlong JNICALL
Java_com_google_sample_oboe_manualtest_OboeAudioStream_getFramesWritten(
JNIEnv *env, jobject, jint streamIndex) {
jlong result = (jint) oboe::Result::ErrorNull;
oboe::AudioStream *oboeStream = engine.getCurrentActivity()->getStream(streamIndex);
if (oboeStream != nullptr) {
result = oboeStream->getFramesWritten();
}
return result;
}
JNIEXPORT jlong JNICALL
Java_com_google_sample_oboe_manualtest_OboeAudioStream_getFramesRead(
JNIEnv *env, jobject, jint streamIndex) {
jlong result = (jlong) oboe::Result::ErrorNull;
oboe::AudioStream *oboeStream = engine.getCurrentActivity()->getStream(streamIndex);
if (oboeStream != nullptr) {
result = oboeStream->getFramesRead();
}
return result;
}
JNIEXPORT jint JNICALL
Java_com_google_sample_oboe_manualtest_OboeAudioStream_getXRunCount(
JNIEnv *env, jobject, jint streamIndex) {
jint result = (jlong) oboe::Result::ErrorNull;
oboe::AudioStream *oboeStream = engine.getCurrentActivity()->getStream(streamIndex);
if (oboeStream != nullptr) {
auto oboeResult = oboeStream->getXRunCount();
if (!oboeResult) {
result = (jint) oboeResult.error();
} else {
result = oboeResult.value();
}
}
return result;
}
JNIEXPORT jlong JNICALL
Java_com_google_sample_oboe_manualtest_OboeAudioStream_getCallbackCount(
JNIEnv *env, jobject) {
return engine.getCurrentActivity()->getCallbackCount();
}
JNIEXPORT jdouble JNICALL
Java_com_google_sample_oboe_manualtest_OboeAudioStream_getLatency(JNIEnv *env, jobject instance, jint streamIndex) {
oboe::AudioStream *oboeStream = engine.getCurrentActivity()->getStream(streamIndex);
if (oboeStream != nullptr) {
auto result = oboeStream->calculateLatencyMillis();
return (!result) ? -1.0 : result.value();
}
return -1.0;
}
JNIEXPORT jdouble JNICALL
Java_com_google_sample_oboe_manualtest_OboeAudioStream_getCpuLoad(JNIEnv *env, jobject instance, jint streamIndex) {
return engine.getCurrentActivity()->getCpuLoad();
}
JNIEXPORT void JNICALL
Java_com_google_sample_oboe_manualtest_OboeAudioStream_setWorkload(
JNIEnv *env, jobject, jdouble workload) {
engine.getCurrentActivity()->setWorkload(workload);
}
JNIEXPORT jint JNICALL
Java_com_google_sample_oboe_manualtest_OboeAudioStream_getState(JNIEnv *env, jobject instance, jint streamIndex) {
oboe::AudioStream *oboeStream = engine.getCurrentActivity()->getStream(streamIndex);
if (oboeStream != nullptr) {
auto state = oboeStream->getState();
if (state != oboe::StreamState::Starting && state != oboe::StreamState::Started) {
oboe::Result result = oboeStream->waitForStateChange(
oboe::StreamState::Uninitialized,
&state, 0);
if (result != oboe::Result::OK){
if (result == oboe::Result::ErrorClosed) {
state = oboe::StreamState::Closed;
} else if (result == oboe::Result::ErrorDisconnected){
state = oboe::StreamState::Disconnected;
} else {
state = oboe::StreamState::Unknown;
}
}
}
return (jint) state;
}
return -1;
}
JNIEXPORT jdouble JNICALL
Java_com_google_sample_oboe_manualtest_AudioInputTester_getPeakLevel(JNIEnv *env,
jobject instance,
jint index) {
return engine.getCurrentActivity()->getPeakLevel(index);
}
JNIEXPORT void JNICALL
Java_com_google_sample_oboe_manualtest_OboeAudioStream_setUseCallback(JNIEnv *env, jclass type,
jboolean useCallback) {
ActivityContext::mUseCallback = useCallback;
}
JNIEXPORT void JNICALL
Java_com_google_sample_oboe_manualtest_OboeAudioStream_setCallbackReturnStop(JNIEnv *env, jclass type,
jboolean b) {
OboeStreamCallbackProxy::setCallbackReturnStop(b);
}
JNIEXPORT void JNICALL
Java_com_google_sample_oboe_manualtest_OboeAudioStream_setCallbackSize(JNIEnv *env, jclass type,
jint callbackSize) {
ActivityContext::callbackSize = callbackSize;
}
JNIEXPORT jboolean JNICALL
Java_com_google_sample_oboe_manualtest_OboeAudioStream_isMMap(JNIEnv *env, jobject instance, jint streamIndex) {
return engine.getCurrentActivity()->isMMapUsed(streamIndex);
}
// ================= OboeAudioOutputStream ================================
JNIEXPORT void JNICALL
Java_com_google_sample_oboe_manualtest_OboeAudioOutputStream_setToneEnabled(
JNIEnv *env, jobject, jboolean enabled) {
engine.getCurrentActivity()->setEnabled(enabled);
}
JNIEXPORT void JNICALL
Java_com_google_sample_oboe_manualtest_OboeAudioOutputStream_setToneType(
JNIEnv *env, jobject, jint toneType) {
// FIXME engine.getCurrentActivity()->setToneType(toneType);
}
JNIEXPORT void JNICALL
Java_com_google_sample_oboe_manualtest_OboeAudioOutputStream_setChannelEnabled(
JNIEnv *env, jobject, jint channelIndex, jboolean enabled) {
engine.getCurrentActivity()->setChannelEnabled(channelIndex, enabled);
}
JNIEXPORT void JNICALL
Java_com_google_sample_oboe_manualtest_OboeAudioOutputStream_setSignalType(
JNIEnv *env, jobject, jint signalType) {
engine.getCurrentActivity()->setSignalType(signalType);
}
JNIEXPORT jint JNICALL
Java_com_google_sample_oboe_manualtest_OboeAudioStream_getOboeVersionNumber(JNIEnv *env,
jclass type) {
return OBOE_VERSION_NUMBER;
}
// ==========================================================================
JNIEXPORT void JNICALL
Java_com_google_sample_oboe_manualtest_TestAudioActivity_setActivityType(JNIEnv *env,
jobject instance,
jint activityType) {
engine.setActivityType(activityType);
}
// ==========================================================================
JNIEXPORT jint JNICALL
Java_com_google_sample_oboe_manualtest_TestInputActivity_saveWaveFile(JNIEnv *env,
jobject instance,
jstring fileName) {
const char *str = env->GetStringUTFChars(fileName, nullptr);
LOGD("nativeSaveFile(%s)", str);
jint result = engine.getCurrentActivity()->saveWaveFile(str);
env->ReleaseStringUTFChars(fileName, str);
return result;
}
// ==========================================================================
JNIEXPORT void JNICALL
Java_com_google_sample_oboe_manualtest_TestInputActivity_setMinimumFramesBeforeRead(JNIEnv *env,
jobject instance,
jint numFrames) {
engine.getCurrentActivity()->setMinimumFramesBeforeRead(numFrames);
}
// ==========================================================================
JNIEXPORT void JNICALL
Java_com_google_sample_oboe_manualtest_EchoActivity_setDelayTime(JNIEnv *env,
jobject instance,
jdouble delayTimeSeconds) {
engine.setDelayTime(delayTimeSeconds);
}
// ==========================================================================
JNIEXPORT jint JNICALL
Java_com_google_sample_oboe_manualtest_RoundTripLatencyActivity_getAnalyzerProgress(JNIEnv *env,
jobject instance) {
return engine.mActivityRoundTripLatency.getLatencyAnalyzer()->getProgress();
}
JNIEXPORT jint JNICALL
Java_com_google_sample_oboe_manualtest_RoundTripLatencyActivity_getMeasuredLatency(JNIEnv *env,
jobject instance) {
return engine.mActivityRoundTripLatency.getLatencyAnalyzer()->getMeasuredLatency();
}
JNIEXPORT jdouble JNICALL
Java_com_google_sample_oboe_manualtest_RoundTripLatencyActivity_getMeasuredConfidence(JNIEnv *env,
jobject instance) {
return engine.mActivityRoundTripLatency.getLatencyAnalyzer()->getMeasuredConfidence();
}
JNIEXPORT jdouble JNICALL
Java_com_google_sample_oboe_manualtest_RoundTripLatencyActivity_getBackgroundRMS(JNIEnv *env,
jobject instance) {
return engine.mActivityRoundTripLatency.getLatencyAnalyzer()->getBackgroundRMS();
}
JNIEXPORT jdouble JNICALL
Java_com_google_sample_oboe_manualtest_RoundTripLatencyActivity_getSignalRMS(JNIEnv *env,
jobject instance) {
return engine.mActivityRoundTripLatency.getLatencyAnalyzer()->getSignalRMS();
}
JNIEXPORT jint JNICALL
Java_com_google_sample_oboe_manualtest_AnalyzerActivity_getMeasuredResult(JNIEnv *env,
jobject instance) {
return engine.mActivityRoundTripLatency.getLatencyAnalyzer()->getResult();
}
// ==========================================================================
JNIEXPORT jint JNICALL
Java_com_google_sample_oboe_manualtest_AnalyzerActivity_getAnalyzerState(JNIEnv *env,
jobject instance) {
return ((ActivityFullDuplex *)engine.getCurrentActivity())->getState();
}
JNIEXPORT jboolean JNICALL
Java_com_google_sample_oboe_manualtest_AnalyzerActivity_isAnalyzerDone(JNIEnv *env,
jobject instance) {
return ((ActivityFullDuplex *)engine.getCurrentActivity())->isAnalyzerDone();
}
JNIEXPORT jint JNICALL
Java_com_google_sample_oboe_manualtest_AnalyzerActivity_getResetCount(JNIEnv *env,
jobject instance) {
return ((ActivityFullDuplex *)engine.getCurrentActivity())->getResetCount();
}
// ==========================================================================
JNIEXPORT jint JNICALL
Java_com_google_sample_oboe_manualtest_GlitchActivity_getGlitchCount(JNIEnv *env,
jobject instance) {
return engine.mActivityGlitches.getGlitchAnalyzer()->getGlitchCount();
}
JNIEXPORT jint JNICALL
Java_com_google_sample_oboe_manualtest_GlitchActivity_getStateFrameCount(JNIEnv *env,
jobject instance,
jint state) {
return engine.mActivityGlitches.getGlitchAnalyzer()->getStateFrameCount(state);
}
JNIEXPORT jdouble JNICALL
Java_com_google_sample_oboe_manualtest_GlitchActivity_getSignalToNoiseDB(JNIEnv *env,
jobject instance) {
return engine.mActivityGlitches.getGlitchAnalyzer()->getSignalToNoiseDB();
}
JNIEXPORT jdouble JNICALL
Java_com_google_sample_oboe_manualtest_GlitchActivity_getPeakAmplitude(JNIEnv *env,
jobject instance) {
return engine.mActivityGlitches.getGlitchAnalyzer()->getPeakAmplitude();
}
JNIEXPORT void JNICALL
Java_com_google_sample_oboe_manualtest_GlitchActivity_setTolerance(JNIEnv *env,
jobject instance,
jfloat tolerance) {
if (engine.mActivityGlitches.getGlitchAnalyzer()) {
engine.mActivityGlitches.getGlitchAnalyzer()->setTolerance(tolerance);
}
}
JNIEXPORT jint JNICALL
Java_com_google_sample_oboe_manualtest_ManualGlitchActivity_getGlitch(JNIEnv *env, jobject instance,
jfloatArray waveform_) {
float *waveform = env->GetFloatArrayElements(waveform_, nullptr);
jsize length = env->GetArrayLength(waveform_);
jsize numSamples = 0;
auto *analyzer = engine.mActivityGlitches.getGlitchAnalyzer();
if (analyzer) {
numSamples = analyzer->getLastGlitch(waveform, length);
}
env->ReleaseFloatArrayElements(waveform_, waveform, 0);
return numSamples;
}
}
@@ -0,0 +1,145 @@
/*
* Copyright 2017 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef OBOETESTER_UNUSED_H
#define OBOETESTER_UNUSED_H
// Store this code for later use.
#if 0
/*
FIR filter designed with
http://t-filter.appspot.com
sampling frequency: 48000 Hz
* 0 Hz - 8000 Hz
gain = 1.2
desired ripple = 5 dB
actual ripple = 5.595266169703693 dB
* 12000 Hz - 20000 Hz
gain = 0
desired attenuation = -40 dB
actual attenuation = -37.58691566571914 dB
*/
#define FILTER_TAP_NUM 11
static const float sFilterTaps8000[FILTER_TAP_NUM] = {
-0.05944219353343189f,
-0.07303434839503208f,
-0.037690487672689066f,
0.1870480506596512f,
0.3910337357836833f,
0.5333672385425637f,
0.3910337357836833f,
0.1870480506596512f,
-0.037690487672689066f,
-0.07303434839503208f,
-0.05944219353343189f
};
class LowPassFilter {
public:
/*
* Filter one input sample.
* @return filtered output
*/
float filter(float input) {
float output = 0.0f;
mX[mCursor] = input;
// Index backwards over x.
int xIndex = mCursor + FILTER_TAP_NUM;
// Write twice so we avoid having to wrap in the middle of the convolution.
mX[xIndex] = input;
for (int i = 0; i < FILTER_TAP_NUM; i++) {
output += sFilterTaps8000[i] * mX[xIndex--];
}
if (++mCursor >= FILTER_TAP_NUM) {
mCursor = 0;
}
return output;
}
/**
* @return true if PASSED
*/
bool test() {
// Measure the impulse of the filter at different phases so we exercise
// all the wraparound cases in the FIR.
for (int offset = 0; offset < (FILTER_TAP_NUM * 2); offset++ ) {
// LOGD("LowPassFilter: cursor = %d\n", mCursor);
// Offset by one each time.
if (filter(0.0f) != 0.0f) {
LOGD("ERROR: filter should return 0.0 before impulse response\n");
return false;
}
for (int i = 0; i < FILTER_TAP_NUM; i++) {
float output = filter((i == 0) ? 1.0f : 0.0f); // impulse
if (output != sFilterTaps8000[i]) {
LOGD("ERROR: filter should return impulse response\n");
return false;
}
}
for (int i = 0; i < FILTER_TAP_NUM; i++) {
if (filter(0.0f) != 0.0f) {
LOGD("ERROR: filter should return 0.0 after impulse response\n");
return false;
}
}
}
return true;
}
private:
float mX[FILTER_TAP_NUM * 2]{}; // twice as big as needed to avoid wrapping
int32_t mCursor = 0;
};
/**
* Low pass filter the recording using a simple FIR filter.
* Note that the lowpass filter cutoff tracks the sample rate.
* That is OK because the impulse width is a fixed number of samples.
*/
void lowPassFilter() {
for (int i = 0; i < mFrameCounter; i++) {
mData[i] = mLowPassFilter.filter(mData[i]);
}
}
/**
* Remove DC offset using a one-pole one-zero IIR filter.
*/
void dcBlocker() {
const float R = 0.996; // narrow notch at zero Hz
float x1 = 0.0;
float y1 = 0.0;
for (int i = 0; i < mFrameCounter; i++) {
const float x = mData[i];
const float y = x - x1 + (R * y1);
mData[i] = y;
y1 = y;
x1 = x;
}
}
#endif
#endif //OBOETESTER_UNUSED_H
@@ -0,0 +1,132 @@
/*
* Copyright 2019 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "WaveFileWriter.h"
void WaveFileWriter::WaveFileWriter::write(float value) {
if (!headerWritten) {
writeHeader();
}
if (bitsPerSample == 24) {
writePCM24(value);
} else {
writePCM16(value);
}
}
void WaveFileWriter::write(float *buffer, int32_t startSample, int32_t numSamples) {
for (int32_t i = 0; i < numSamples; i++) {
write(buffer[startSample + i]);
}
}
void WaveFileWriter::writeIntLittle(int32_t n) {
writeByte(n);
writeByte(n >> 8);
writeByte(n >> 16);
writeByte(n >> 24);
}
void WaveFileWriter::writeShortLittle(int16_t n) {
writeByte(n);
writeByte(n >> 8);
}
void WaveFileWriter::writeFormatChunk() {
int32_t bytesPerSample = (bitsPerSample + 7) / 8;
writeByte('f');
writeByte('m');
writeByte('t');
writeByte(' ');
writeIntLittle(16); // chunk size
writeShortLittle(WAVE_FORMAT_PCM);
writeShortLittle((int16_t) mSamplesPerFrame);
writeIntLittle(mFrameRate);
// bytes/second
writeIntLittle(mFrameRate * mSamplesPerFrame * bytesPerSample);
// block align
writeShortLittle((int16_t) (mSamplesPerFrame * bytesPerSample));
writeShortLittle((int16_t) bitsPerSample);
}
void WaveFileWriter::writeDataChunkHeader() {
writeByte('d');
writeByte('a');
writeByte('t');
writeByte('a');
// Maximum size is not strictly correct but is commonly used
// when we do not know the final size.
writeIntLittle(INT32_MAX);
}
void WaveFileWriter::writeHeader() {
writeRiffHeader();
writeFormatChunk();
writeDataChunkHeader();
headerWritten = true;
}
// Write lower 8 bits. Upper bits ignored.
void WaveFileWriter::writeByte(uint8_t b) {
mOutputStream->write(b);
bytesWritten += 1;
}
void WaveFileWriter::writePCM24(float value) {
// Offset before casting so that we can avoid using floor().
// Also round by adding 0.5 so that very small signals go to zero.
float temp = (PCM24_MAX * value) + 0.5 - PCM24_MIN;
int32_t sample = ((int) temp) + PCM24_MIN;
// clip to 24-bit range
if (sample > PCM24_MAX) {
sample = PCM24_MAX;
} else if (sample < PCM24_MIN) {
sample = PCM24_MIN;
}
// encode as little-endian
writeByte(sample); // little end
writeByte(sample >> 8); // middle
writeByte(sample >> 16); // big end
}
void WaveFileWriter::writePCM16(float value) {
// Offset before casting so that we can avoid using floor().
// Also round by adding 0.5 so that very small signals go to zero.
float temp = (INT16_MAX * value) + 0.5 - INT16_MIN;
int32_t sample = ((int) temp) + INT16_MIN;
if (sample > INT16_MAX) {
sample = INT16_MAX;
} else if (sample < INT16_MIN) {
sample = INT16_MIN;
}
writeByte(sample); // little end
writeByte(sample >> 8); // big end
}
void WaveFileWriter::writeRiffHeader() {
writeByte('R');
writeByte('I');
writeByte('F');
writeByte('F');
// Maximum size is not strictly correct but is commonly used
// when we do not know the final size.
writeIntLittle(INT32_MAX);
writeByte('W');
writeByte('A');
writeByte('V');
writeByte('E');
}
@@ -0,0 +1,154 @@
/*
* Copyright 2019 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
// Based on the WaveFileWriter in Java from the open source JSyn library by Phil Burk
// https://github.com/philburk/jsyn/blob/master/src/com/jsyn/util/WaveFileWriter.java
#ifndef UTIL_WAVE_FILE_WRITER
#define UTIL_WAVE_FILE_WRITER
#include <cassert>
#include <stdio.h>
class WaveFileOutputStream {
public:
virtual void write(uint8_t b) = 0;
};
/**
* Write audio data to a WAV file.
*
* <pre>
* <code>
* WaveFileWriter writer = new WaveFileWriter(waveFileOutputStream);
* writer.setFrameRate(48000);
* writer.setBitsPerSample(24);
* writer.write(floatArray, 0, numSamples);
* writer.close();
* </code>
* </pre>
*
*/
class WaveFileWriter {
public:
/**
* Create an object that will write a WAV file image to the specified stream.
*
* @param outputStream stream to receive the bytes
* @throws FileNotFoundException
*/
WaveFileWriter(WaveFileOutputStream *outputStream) {
mOutputStream = outputStream;
}
/**
* @param frameRate default is 44100
*/
void setFrameRate(int32_t frameRate) {
mFrameRate = frameRate;
}
int32_t getFrameRate() const {
return mFrameRate;
}
/**
* For stereo, set this to 2. Default is mono = 1.
* Also known as ChannelCount
*/
void setSamplesPerFrame(int32_t samplesPerFrame) {
mSamplesPerFrame = samplesPerFrame;
}
int32_t getSamplesPerFrame() const {
return mSamplesPerFrame;
}
/** Only 16 or 24 bit samples supported at the moment. Default is 16. */
void setBitsPerSample(int32_t bits) {
assert((bits == 16) || (bits == 24));
bitsPerSample = bits;
}
int32_t getBitsPerSample() const {
return bitsPerSample;
}
void close() {
}
/** Write single audio data value to the WAV file. */
void write(float value);
/**
* Write a buffer to the WAV file.
*/
void write(float *buffer, int32_t startSample, int32_t numSamples);
private:
/**
* Write a 32 bit integer to the stream in Little Endian format.
*/
void writeIntLittle(int32_t n);
/**
* Write a 16 bit integer to the stream in Little Endian format.
*/
void writeShortLittle(int16_t n);
/**
* Write an 'fmt ' chunk to the WAV file containing the given information.
*/
void writeFormatChunk();
/**
* Write a 'data' chunk header to the WAV file. This should be followed by call to
* writeShortLittle() to write the data to the chunk.
*/
void writeDataChunkHeader();
/**
* Write a simple WAV header for PCM data.
*/
void writeHeader();
// Write lower 8 bits. Upper bits ignored.
void writeByte(uint8_t b);
void writePCM24(float value);
void writePCM16(float value);
/**
* Write a 'RIFF' file header and a 'WAVE' ID to the WAV file.
*/
void writeRiffHeader();
static constexpr int WAVE_FORMAT_PCM = 1;
WaveFileOutputStream *mOutputStream = nullptr;
int32_t mFrameRate = 48000;
int32_t mSamplesPerFrame = 1;
int32_t bitsPerSample = 16;
int32_t bytesWritten = 0;
bool headerWritten = false;
static constexpr int32_t PCM24_MIN = -(1 << 23);
static constexpr int32_t PCM24_MAX = (1 << 23) - 1;
};
#endif /* UTIL_WAVE_FILE_WRITER */
@@ -0,0 +1,58 @@
package com.google.sample.audio_device;
/*
* Copyright 2017 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import android.content.Context;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.TextView;
import com.google.sample.oboe.manualtest.R;
/**
* Provides views for a list of audio devices. Usually used as an Adapter for a Spinner or ListView.
*/
public class AudioDeviceAdapter extends ArrayAdapter<AudioDeviceListEntry> {
public AudioDeviceAdapter(Context context) {
super(context, R.layout.audio_devices);
}
@NonNull
@Override
public View getView(int position, @Nullable View convertView, @NonNull ViewGroup parent) {
return getDropDownView(position, convertView, parent);
}
@Override
public View getDropDownView(int position, @Nullable View convertView, @NonNull ViewGroup parent) {
View rowView = convertView;
if (rowView == null) {
LayoutInflater inflater = LayoutInflater.from(parent.getContext());
rowView = inflater.inflate(R.layout.audio_devices, parent, false);
}
TextView deviceName = (TextView) rowView.findViewById(R.id.device_name);
AudioDeviceListEntry deviceInfo = getItem(position);
deviceName.setText(deviceInfo.getName());
return rowView;
}
}
@@ -0,0 +1,140 @@
package com.google.sample.audio_device;
/*
* Copyright 2017 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import android.media.AudioDeviceInfo;
class AudioDeviceInfoConverter {
/**
* Converts an {@link AudioDeviceInfo} object into a human readable representation
*
* @param adi The AudioDeviceInfo object to be converted to a String
* @return String containing all the information from the AudioDeviceInfo object
*/
static String toString(AudioDeviceInfo adi){
StringBuilder sb = new StringBuilder();
sb.append("Id: ");
sb.append(adi.getId());
sb.append("\nProduct name: ");
sb.append(adi.getProductName());
sb.append("\nType: ");
sb.append(typeToString(adi.getType()));
sb.append("\nIs source: ");
sb.append((adi.isSource() ? "Yes" : "No"));
sb.append("\nIs sink: ");
sb.append((adi.isSink() ? "Yes" : "No"));
sb.append("\nChannel counts: ");
int[] channelCounts = adi.getChannelCounts();
sb.append(intArrayToString(channelCounts));
sb.append("\nChannel masks: ");
int[] channelMasks = adi.getChannelMasks();
sb.append(intArrayToString(channelMasks));
sb.append("\nChannel index masks: ");
int[] channelIndexMasks = adi.getChannelIndexMasks();
sb.append(intArrayToString(channelIndexMasks));
sb.append("\nEncodings: ");
int[] encodings = adi.getEncodings();
sb.append(intArrayToString(encodings));
sb.append("\nSample Rates: ");
int[] sampleRates = adi.getSampleRates();
sb.append(intArrayToString(sampleRates));
return sb.toString();
}
/**
* Converts an integer array into a string where each int is separated by a space
*
* @param integerArray the integer array to convert to a string
* @return string containing all the integer values separated by spaces
*/
private static String intArrayToString(int[] integerArray){
StringBuilder sb = new StringBuilder();
for (int i = 0; i < integerArray.length; i++){
sb.append(integerArray[i]);
if (i != integerArray.length -1) sb.append(" ");
}
return sb.toString();
}
/**
* Converts the value from {@link AudioDeviceInfo#getType()} into a human
* readable string
* @param type One of the {@link AudioDeviceInfo}.TYPE_* values
* e.g. AudioDeviceInfo.TYPE_BUILT_IN_SPEAKER
* @return string which describes the type of audio device
*/
static String typeToString(int type){
switch (type) {
case AudioDeviceInfo.TYPE_AUX_LINE:
return "auxiliary line-level connectors";
case AudioDeviceInfo.TYPE_BLUETOOTH_A2DP:
return "Bluetooth device supporting the A2DP profile";
case AudioDeviceInfo.TYPE_BLUETOOTH_SCO:
return "Bluetooth device typically used for telephony";
case AudioDeviceInfo.TYPE_BUILTIN_EARPIECE:
return "built-in earphone speaker";
case AudioDeviceInfo.TYPE_BUILTIN_MIC:
return "built-in microphone";
case AudioDeviceInfo.TYPE_BUILTIN_SPEAKER:
return "built-in speaker";
case AudioDeviceInfo.TYPE_BUS:
return "BUS";
case AudioDeviceInfo.TYPE_DOCK:
return "DOCK";
case AudioDeviceInfo.TYPE_FM:
return "FM";
case AudioDeviceInfo.TYPE_FM_TUNER:
return "FM tuner";
case AudioDeviceInfo.TYPE_HDMI:
return "HDMI";
case AudioDeviceInfo.TYPE_HDMI_ARC:
return "HDMI audio return channel";
case AudioDeviceInfo.TYPE_IP:
return "IP";
case AudioDeviceInfo.TYPE_LINE_ANALOG:
return "line analog";
case AudioDeviceInfo.TYPE_LINE_DIGITAL:
return "line digital";
case AudioDeviceInfo.TYPE_TELEPHONY:
return "telephony";
case AudioDeviceInfo.TYPE_TV_TUNER:
return "TV tuner";
case AudioDeviceInfo.TYPE_USB_ACCESSORY:
return "USB accessory";
case AudioDeviceInfo.TYPE_USB_DEVICE:
return "USB device";
case AudioDeviceInfo.TYPE_WIRED_HEADPHONES:
return "wired headphones";
case AudioDeviceInfo.TYPE_WIRED_HEADSET:
return "wired headset";
default:
case AudioDeviceInfo.TYPE_UNKNOWN:
return "unknown";
}
}
}
@@ -0,0 +1,93 @@
package com.google.sample.audio_device;
/*
* Copyright 2017 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import android.annotation.TargetApi;
import android.media.AudioDeviceInfo;
import android.media.AudioManager;
import java.util.List;
import java.util.Vector;
/**
* POJO which represents basic information for an audio device.
*
* Example: id: 8, deviceName: "built-in speaker"
*/
public class AudioDeviceListEntry {
private int mId;
private String mName;
public AudioDeviceListEntry(int deviceId, String deviceName){
mId = deviceId;
mName = deviceName;
}
public int getId() {
return mId;
}
public String getName(){
return mName;
}
public String toString(){
return getName();
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
AudioDeviceListEntry that = (AudioDeviceListEntry) o;
if (mId != that.mId) return false;
return mName != null ? mName.equals(that.mName) : that.mName == null;
}
@Override
public int hashCode() {
int result = mId;
result = 31 * result + (mName != null ? mName.hashCode() : 0);
return result;
}
/**
* Create a list of AudioDeviceListEntry objects from a list of AudioDeviceInfo objects.
*
* @param devices A list of {@Link AudioDeviceInfo} objects
* @param directionType Only audio devices with this direction will be included in the list.
* Valid values are GET_DEVICES_ALL, GET_DEVICES_OUTPUTS and
* GET_DEVICES_INPUTS.
* @return A list of AudioDeviceListEntry objects
*/
@TargetApi(23)
static List<AudioDeviceListEntry> createListFrom(AudioDeviceInfo[] devices, int directionType){
List<AudioDeviceListEntry> listEntries = new Vector<>();
for (AudioDeviceInfo info : devices) {
if (directionType == AudioManager.GET_DEVICES_ALL ||
(directionType == AudioManager.GET_DEVICES_OUTPUTS && info.isSink()) ||
(directionType == AudioManager.GET_DEVICES_INPUTS && info.isSource())) {
listEntries.add(new AudioDeviceListEntry(info.getId(), info.getProductName() + " " +
AudioDeviceInfoConverter.typeToString(info.getType())));
}
}
return listEntries;
}
}
@@ -0,0 +1,127 @@
package com.google.sample.audio_device;
/*
* Copyright 2017 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import android.annotation.TargetApi;
import android.content.Context;
import android.content.res.Resources.Theme;
import android.media.AudioDeviceCallback;
import android.media.AudioDeviceInfo;
import android.media.AudioManager;
import android.util.AttributeSet;
import android.widget.Spinner;
import com.google.sample.oboe.manualtest.R;
import java.util.List;
public class AudioDeviceSpinner extends Spinner {
private static final int AUTO_SELECT_DEVICE_ID = 0;
private static final String TAG = AudioDeviceSpinner.class.getName();
private int mDirectionType;
private AudioDeviceAdapter mDeviceAdapter;
private AudioManager mAudioManager;
private Context mContext;
public AudioDeviceSpinner(Context context){
super(context);
setup(context);
}
public AudioDeviceSpinner(Context context, int mode){
super(context, mode);
setup(context);
}
public AudioDeviceSpinner(Context context, AttributeSet attrs){
super(context, attrs);
setup(context);
}
public AudioDeviceSpinner(Context context, AttributeSet attrs, int defStyleAttr){
super(context, attrs, defStyleAttr);
setup(context);
}
public AudioDeviceSpinner(Context context, AttributeSet attrs, int defStyleAttr, int mode){
super(context, attrs, defStyleAttr, mode);
setup(context);
}
public AudioDeviceSpinner(Context context, AttributeSet attrs, int defStyleAttr,
int defStyleRes, int mode){
super(context, attrs, defStyleAttr, defStyleRes, mode);
setup(context);
}
public AudioDeviceSpinner(Context context, AttributeSet attrs, int defStyleAttr,
int defStyleRes, int mode, Theme popupTheme){
super(context, attrs, defStyleAttr, defStyleRes, mode, popupTheme);
setup(context);
}
private void setup(Context context){
mContext = context;
mAudioManager = (AudioManager) context.getSystemService(Context.AUDIO_SERVICE);
mDeviceAdapter = new AudioDeviceAdapter(context);
setAdapter(mDeviceAdapter);
// Add a default entry to the list and select it
mDeviceAdapter.add(new AudioDeviceListEntry(AUTO_SELECT_DEVICE_ID,
mContext.getString(R.string.auto_select)));
setSelection(0);
}
@TargetApi(23)
public void setDirectionType(int directionType){
this.mDirectionType = directionType;
setupAudioDeviceCallback();
}
@TargetApi(23)
private void setupAudioDeviceCallback(){
// Note that we will immediately receive a call to onDevicesAdded with the list of
// devices which are currently connected.
mAudioManager.registerAudioDeviceCallback(new AudioDeviceCallback() {
@Override
public void onAudioDevicesAdded(AudioDeviceInfo[] addedDevices) {
List<AudioDeviceListEntry> deviceList =
AudioDeviceListEntry.createListFrom(addedDevices, mDirectionType);
if (deviceList.size() > 0){
// Prevent duplicate entries caused by b/80138804
for (AudioDeviceListEntry entry : deviceList){
mDeviceAdapter.remove(entry);
}
mDeviceAdapter.addAll(deviceList);
}
}
public void onAudioDevicesRemoved(AudioDeviceInfo[] removedDevices) {
List<AudioDeviceListEntry> deviceList =
AudioDeviceListEntry.createListFrom(removedDevices, mDirectionType);
for (AudioDeviceListEntry entry : deviceList){
mDeviceAdapter.remove(entry);
}
setSelection(0);
}
}, null);
}
}
@@ -0,0 +1,236 @@
/*
* Copyright 2018 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.sample.oboe.manualtest;
import android.Manifest;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.Writer;
/**
* Activity to measure latency on a full duplex stream.
*/
public class AnalyzerActivity extends TestInputActivity {
private static final int MY_PERMISSIONS_REQUEST_EXTERNAL_STORAGE = 1001;
protected static final String KEY_FILE_NAME = "file";
protected static final String KEY_BUFFER_BURSTS = "buffer_bursts";
AudioOutputTester mAudioOutTester;
protected BufferSizeView mBufferSizeView;
protected String mResultFileName;
private String mTestResults;
// Note that these string must match the enum result_code in LatencyAnalyzer.h
String resultCodeToString(int resultCode) {
switch (resultCode) {
case 0:
return "OK";
case -99:
return "ERROR_NOISY";
case -98:
return "ERROR_VOLUME_TOO_LOW";
case -97:
return "ERROR_VOLUME_TOO_HIGH";
case -96:
return "ERROR_CONFIDENCE";
case -95:
return "ERROR_INVALID_STATE";
case -94:
return "ERROR_GLITCHES";
case -93:
return "ERROR_NO_LOCK";
default:
return "UNKNOWN";
}
}
public native int getAnalyzerState();
public native boolean isAnalyzerDone();
public native int getMeasuredResult();
public native int getResetCount();
@NonNull
protected String getCommonTestReport() {
StringBuffer report = new StringBuffer();
// Add some extra information for the remote tester.
report.append("build.fingerprint = " + Build.FINGERPRINT + "\n");
try {
PackageInfo pinfo = getPackageManager().getPackageInfo(getPackageName(), 0);
report.append(String.format("test.version = %s\n", pinfo.versionName));
report.append(String.format("test.version.code = %d\n", pinfo.versionCode));
} catch (PackageManager.NameNotFoundException e) {
}
report.append("time.millis = " + System.currentTimeMillis() + "\n");
// INPUT
report.append(mAudioInputTester.actualConfiguration.dump());
AudioStreamBase inStream = mAudioInputTester.getCurrentAudioStream();
report.append(String.format("in.burst.frames = %d\n", inStream.getFramesPerBurst()));
report.append(String.format("in.xruns = %d\n", inStream.getXRunCount()));
// OUTPUT
report.append(mAudioOutTester.actualConfiguration.dump());
AudioStreamBase outStream = mAudioOutTester.getCurrentAudioStream();
report.append(String.format("out.burst.frames = %d\n", outStream.getFramesPerBurst()));
int bufferSize = outStream.getBufferSizeInFrames();
report.append(String.format("out.buffer.size.frames = %d\n", bufferSize));
int bufferCapacity = outStream.getBufferCapacityInFrames();
report.append(String.format("out.buffer.capacity.frames = %d\n", bufferCapacity));
report.append(String.format("out.xruns = %d\n", outStream.getXRunCount()));
return report.toString();
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mAudioOutTester = addAudioOutputTester();
mBufferSizeView = (BufferSizeView) findViewById(R.id.buffer_size_view);
if (mBufferSizeView != null) {
mBufferSizeView.setAudioOutTester(mAudioOutTester);
}
}
@Override
protected void resetConfiguration() {
super.resetConfiguration();
mAudioOutTester.reset();
StreamContext streamContext = getFirstInputStreamContext();
if (streamContext != null) {
if (streamContext.configurationView != null) {
streamContext.configurationView.setFormat(StreamConfiguration.AUDIO_FORMAT_PCM_FLOAT);
streamContext.configurationView.setFormatConversionAllowed(true);
}
}
streamContext = getFirstOutputStreamContext();
if (streamContext != null) {
if (streamContext.configurationView != null) {
streamContext.configurationView.setFormat(StreamConfiguration.AUDIO_FORMAT_PCM_FLOAT);
streamContext.configurationView.setFormatConversionAllowed(true);
}
}
}
public void startAudio() {
if (mBufferSizeView != null && mBufferSizeView.isEnabled()) {
mBufferSizeView.updateBufferSize();
}
super.startAudio();
}
public void onStreamClosed() {
Toast.makeText(getApplicationContext(),
"Stream was closed or disconnected!",
Toast.LENGTH_SHORT)
.show();
stopAudioTest();
}
public void stopAudioTest() {
}
void writeTestResultIfPermitted(String resultString) {
// Here, thisActivity is the current activity
if (ContextCompat.checkSelfPermission(this,
Manifest.permission.WRITE_EXTERNAL_STORAGE)
!= PackageManager.PERMISSION_GRANTED) {
mTestResults = resultString;
ActivityCompat.requestPermissions(this,
new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},
MY_PERMISSIONS_REQUEST_EXTERNAL_STORAGE);
} else {
// Permission has already been granted
writeTestResult(resultString);
}
}
void maybeWriteTestResult(String resultString) {
if (mResultFileName == null) return;
writeTestResultIfPermitted(resultString);
}
@Override
public void onRequestPermissionsResult(int requestCode,
String[] permissions,
int[] grantResults) {
switch (requestCode) {
case MY_PERMISSIONS_REQUEST_EXTERNAL_STORAGE: {
// If request is cancelled, the result arrays are empty.
if (grantResults.length > 0
&& grantResults[0] == PackageManager.PERMISSION_GRANTED) {
writeTestResult(mTestResults);
} else {
showToast("Writing external storage needed for test results.");
}
return;
}
}
}
private void writeTestInBackground(final String resultString) {
new Thread() {
public void run() {
writeTestResult(resultString);
}
}.start();
}
// Run this in a background thread.
private void writeTestResult(String resultString) {
File resultFile = new File(mResultFileName);
Writer writer = null;
try {
writer = new OutputStreamWriter(new FileOutputStream(resultFile));
writer.write(resultString);
} catch (
IOException e) {
e.printStackTrace();
showErrorToast(" writing result file. " + e.getMessage());
} finally {
if (writer != null) {
try {
writer.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
mResultFileName = null;
}
}
@@ -0,0 +1,40 @@
/*
* Copyright 2017 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.sample.oboe.manualtest;
import android.util.Log;
class AudioInputTester extends AudioStreamTester{
private static AudioInputTester mInstance;
private AudioInputTester() {
super();
Log.i(TapToToneActivity.TAG, "create OboeAudioStream ---------");
mCurrentAudioStream = new OboeAudioInputStream();
requestedConfiguration.setDirection(StreamConfiguration.DIRECTION_INPUT);
}
public static synchronized AudioInputTester getInstance() {
if (mInstance == null) {
mInstance = new AudioInputTester();
}
return mInstance;
}
public native double getPeakLevel(int i);
}
@@ -0,0 +1,203 @@
/*
* Copyright 2015 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.sample.oboe.manualtest;
import android.media.midi.MidiDeviceService;
import android.media.midi.MidiReceiver;
import android.util.Log;
import com.mobileer.miditools.MidiConstants;
import com.mobileer.miditools.MidiFramer;
import java.io.IOException;
import java.util.ArrayList;
/**
* Measure the latency of various output paths by playing a blip.
* Report the results back to the TestListeners.
*/
public class AudioMidiTester extends MidiDeviceService {
// Sometimes the service can be run without the MainActivity being run!
static {
// Must match name in CMakeLists.txt
System.loadLibrary("oboetester");
}
private static final float MAX_TOUCH_LATENCY = 0.200f;
private static final float MAX_OUTPUT_LATENCY = 0.600f;
private static final float ANALYSIS_TIME_MARGIN = 0.250f;
private static final float ANALYSIS_TIME_DELAY = MAX_OUTPUT_LATENCY;
private static final float ANALYSIS_TIME_TOTAL = MAX_TOUCH_LATENCY + MAX_OUTPUT_LATENCY;
private static final float ANALYSIS_TIME_MAX = ANALYSIS_TIME_TOTAL + ANALYSIS_TIME_MARGIN;
private static final int ANALYSIS_SAMPLE_RATE = 48000; // need not match output rate
private ArrayList<TestListener> mListeners = new ArrayList<TestListener>();
private MyMidiReceiver mReceiver = new MyMidiReceiver();
private MidiFramer mMidiFramer = new MidiFramer(mReceiver);
private boolean mRecordEnabled = true;
private static AudioMidiTester mInstance;
private AudioRecordThread mRecorder;
private TapLatencyAnalyser mTapLatencyAnalyser;
private AudioOutputTester mAudioOutputTester;
public static class TestResult {
public float[] samples;
public float[] filtered;
public int frameRate;
public TapLatencyAnalyser.TapLatencyEvent[] events;
}
public static interface TestListener {
public void onTestFinished(TestResult result);
public void onNoteOn(int pitch);
}
/**
* This is a Service so it is only created when a client requests the service.
*/
public AudioMidiTester() {
mInstance = this;
}
public void addTestListener(TestListener listener) {
mListeners.add(listener);
}
public void removeTestListener(TestListener listener) {
mListeners.remove(listener);
}
@Override
public void onCreate() {
super.onCreate();
if (mRecordEnabled) {
mRecorder = new AudioRecordThread(ANALYSIS_SAMPLE_RATE,
1,
(int) (ANALYSIS_TIME_MAX * ANALYSIS_SAMPLE_RATE));
}
mAudioOutputTester = AudioOutputTester.getInstance();
mTapLatencyAnalyser = new TapLatencyAnalyser();
}
@Override
public void onDestroy() {
// do stuff here
super.onDestroy();
}
public static AudioMidiTester getInstance() {
return mInstance;
}
class MyMidiReceiver extends MidiReceiver {
public void onSend(byte[] data, int offset,
int count, long timestamp) throws IOException {
// parse MIDI
byte command = (byte) (data[0] & 0x0F0);
if (command == MidiConstants.STATUS_NOTE_ON) {
if (data[2] == 0) {
noteOff(data[1]);
} else {
noteOn(data[1]);
}
} else if (command == MidiConstants.STATUS_NOTE_OFF) {
noteOff(data[1]);
}
Log.i(TapToToneActivity.TAG, "MIDI command = " + command);
}
}
private void noteOn(byte b) {
setEnabled(true);
fireNoteOn(b);
}
private void fireNoteOn(byte pitch) {
for (TestListener listener : mListeners) {
listener.onNoteOn(pitch);
}
}
private void noteOff(byte b) {
setEnabled(false);
}
@Override
public MidiReceiver[] onGetInputPortReceivers() {
return new MidiReceiver[]{mMidiFramer};
}
public void start() throws IOException {
if (mRecordEnabled) {
mRecorder.startAudio();
}
}
public void setEnabled(boolean checked) {
mAudioOutputTester.setEnabled(checked);
if (checked && mRecordEnabled) {
// schedule an analysis to start in the near future
int numSamples = (int) (mRecorder.getSampleRate() * ANALYSIS_TIME_DELAY);
Runnable task = new Runnable() {
public void run() {
new Thread() {
public void run() {
analyzeCapturedAudio();
}
}.start();
}
};
mRecorder.scheduleTask(numSamples, task);
}
}
private void analyzeCapturedAudio() {
if (!mRecordEnabled) return;
int numSamples = (int) (mRecorder.getSampleRate() * ANALYSIS_TIME_TOTAL);
float[] buffer = new float[numSamples];
mRecorder.setCaptureEnabled(false); // TODO wait for it to settle
int numRead = mRecorder.readMostRecent(buffer);
TestResult result = new TestResult();
result.samples = buffer;
result.frameRate = mRecorder.getSampleRate();
result.events = mTapLatencyAnalyser.analyze(buffer, 0, numRead);
result.filtered = mTapLatencyAnalyser.getFilteredBuffer();
mRecorder.setCaptureEnabled(true);
// notify listeners
for (TestListener listener : mListeners) {
listener.onTestFinished(result);
}
}
public void stop() {
if (mRecordEnabled) {
mRecorder.stopAudio();
}
}
}
@@ -0,0 +1,60 @@
/*
* Copyright 2017 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.sample.oboe.manualtest;
import android.util.Log;
public class AudioOutputTester extends AudioStreamTester {
protected OboeAudioOutputStream mOboeAudioOutputStream;
private static AudioOutputTester mInstance;
public static synchronized AudioOutputTester getInstance() {
if (mInstance == null) {
mInstance = new AudioOutputTester();
}
return mInstance;
}
private AudioOutputTester() {
super();
Log.i(TapToToneActivity.TAG, "create OboeAudioOutputStream ---------");
mOboeAudioOutputStream = new OboeAudioOutputStream();
mCurrentAudioStream = mOboeAudioOutputStream;
setToneType(OboeAudioOutputStream.TONE_TYPE_SINE);
setEnabled(false);
requestedConfiguration.setDirection(StreamConfiguration.DIRECTION_OUTPUT);
}
public void setToneType(int index) {
Log.i(TapToToneActivity.TAG, "setToneType(" + index + ")");
mOboeAudioOutputStream.setToneType(index);
}
public void setEnabled(boolean flag) {
mOboeAudioOutputStream.setToneEnabled(flag);
}
public void setChannelEnabled(int channelIndex, boolean enabled) {
mOboeAudioOutputStream.setChannelEnabled(channelIndex, enabled);
}
public void setSignalType(int type) {
mOboeAudioOutputStream.setSignalType(type);
}
}
@@ -0,0 +1,156 @@
/*
* Copyright (C) 2013 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.sample.oboe.manualtest;
import android.media.AudioFormat;
import android.media.AudioRecord;
import android.media.MediaRecorder;
/**
* Abstract class for recording.
* Call processBuffer(buffer) when data is read.
*/
class AudioRecordThread implements Runnable {
private static final String TAG = "AudioRecordThread";
private final int mSampleRate;
private final int mChannelCount;
private Thread mThread;
protected boolean mGo;
private AudioRecord mRecorder;
private CircularCaptureBuffer mCaptureBuffer;
protected float[] mBuffer = new float[256];
private static int AUDIO_FORMAT = AudioFormat.ENCODING_PCM_FLOAT;
private Runnable mTask;
private int mTaskCountdown;
private boolean mCaptureEnabled = true;
public AudioRecordThread(int frameRate, int channelCount, int maxFrames) {
mSampleRate = frameRate;
mChannelCount = channelCount;
mCaptureBuffer = new CircularCaptureBuffer(maxFrames);
}
private void createRecorder() {
int channelConfig = (mChannelCount == 1)
? AudioFormat.CHANNEL_IN_MONO : AudioFormat.CHANNEL_IN_STEREO;
int audioFormat = AudioFormat.ENCODING_PCM_FLOAT;
int minRecordBuffSizeInBytes = AudioRecord.getMinBufferSize(mSampleRate,
channelConfig,
audioFormat);
mRecorder = new AudioRecord(
MediaRecorder.AudioSource.VOICE_RECOGNITION,
mSampleRate,
channelConfig,
audioFormat,
2 * minRecordBuffSizeInBytes);
if (mRecorder.getState() == AudioRecord.STATE_UNINITIALIZED) {
throw new RuntimeException("Could not make the AudioRecord - UNINITIALIZED");
}
}
@Override
public void run() {
startAudioRecording();
while (mGo) {
int result = handleAudioPeriod();
if (result < 0) {
mGo = false;
}
}
stopAudioRecording();
}
public void startAudio() {
if (mThread == null) {
mGo = true;
mThread = new Thread(this);
mThread.start();
}
}
public void stopAudio() {
mGo = false;
if (mThread != null) {
try {
mThread.join(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
mThread = null;
}
}
public int getSampleRate() {
return mSampleRate;
}
/**
* @return number of samples read or negative error
*/
private int handleAudioPeriod() {
int numSamplesRead = mRecorder.read(mBuffer, 0, mBuffer.length,
AudioRecord.READ_BLOCKING);
if (numSamplesRead <= 0) {
return numSamplesRead;
} else {
if (mTaskCountdown > 0) {
mTaskCountdown -= numSamplesRead;
if (mTaskCountdown <= 0) {
mTaskCountdown = 0;
new Thread(mTask).start(); // run asynchronously with audio thread
}
}
if (mCaptureEnabled) {
return mCaptureBuffer.write(mBuffer, 0, numSamplesRead);
} else {
return numSamplesRead;
}
}
}
private void startAudioRecording() {
stopAudioRecording();
createRecorder();
mRecorder.startRecording();
}
private void stopAudioRecording() {
if (mRecorder != null) {
mRecorder.stop();
mRecorder.release();
mRecorder = null;
}
}
public void scheduleTask(int numSamples, Runnable task) {
mTask = task;
mTaskCountdown = numSamples;
}
public void setCaptureEnabled(boolean captureEnabled) {
mCaptureEnabled = captureEnabled;
}
public int readMostRecent(float[] buffer) {
return mCaptureBuffer.readMostRecent(buffer);
}
}
@@ -0,0 +1,176 @@
/*
* Copyright 2015 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.sample.oboe.manualtest;
import java.io.IOException;
/**
* Base class for any audio input or output.
*/
public abstract class AudioStreamBase {
private StreamConfiguration mRequestedStreamConfiguration;
private StreamConfiguration mActualStreamConfiguration;
private int mBufferSizeInFrames;
public StreamStatus getStreamStatus() {
StreamStatus status = new StreamStatus();
status.bufferSize = getBufferSizeInFrames();
status.xRunCount = getXRunCount();
status.framesRead = getFramesRead();
status.framesWritten = getFramesWritten();
status.callbackCount = getCallbackCount();
status.latency = getLatency();
status.cpuLoad = getCpuLoad();
status.state = getState();
return status;
}
/**
* Changes dynamic at run-time.
*/
public static class StreamStatus {
public int bufferSize;
public int xRunCount;
public long framesWritten;
public long framesRead;
public double latency; // msec
public int state;
public long callbackCount;
public int framesPerCallback;
public double cpuLoad;
// These are constantly changing.
String dump(int framesPerBurst) {
if (bufferSize < 0 || framesWritten < 0) {
return "idle";
}
StringBuffer buffer = new StringBuffer();
buffer.append("frames written " + framesWritten + " - read " + framesRead
+ " = " + (framesWritten - framesRead) + "\n");
String latencyText = (latency < 0.0)
? "?"
: String.format("%6.1f ms", latency);
String cpuLoadText = String.format("%2d%c", (int)(cpuLoad * 100), '%');
buffer.append(
convertStateToString(state)
+ ", #cb=" + callbackCount
+ ", f/cb=" + String.format("%3d", framesPerCallback)
+ ", latnc = " + latencyText
+ ", " + cpuLoadText + " cpu"
+ "\n");
buffer.append("buffer size = ");
if (bufferSize < 0) {
buffer.append("?");
} else {
int numBuffers = bufferSize / framesPerBurst;
int remainder = bufferSize - (numBuffers * framesPerBurst);
buffer.append(bufferSize + " = (" + numBuffers + " * " + framesPerBurst + ") + " + remainder);
}
buffer.append(", xRun# = " + ((xRunCount < 0) ? "?" : xRunCount) + "\n");
return buffer.toString();
}
/**
* Converts ints from Oboe index to human-readable stream state
*/
private String convertStateToString(int stateId) {
final String[] STATE_ARRAY = {"Uninit.", "Unknown", "Open", "Starting", "Started",
"Pausing", "Paused", "Flushing", "Flushed",
"Stopping", "Stopped", "Closing", "Closed", "Disconn."};
if (stateId < 0 || stateId >= STATE_ARRAY.length) {
return "Invalid - " + stateId;
}
return STATE_ARRAY[stateId];
}
}
/**
*
* @param requestedConfiguration
* @param actualConfiguration
* @param bufferSizeInFrames
* @throws IOException
*/
public void open(StreamConfiguration requestedConfiguration,
StreamConfiguration actualConfiguration,
int bufferSizeInFrames) throws IOException {
mRequestedStreamConfiguration = requestedConfiguration;
mActualStreamConfiguration = actualConfiguration;
mBufferSizeInFrames = bufferSizeInFrames;
}
public abstract boolean isInput();
public void startPlayback() throws IOException {}
public void stopPlayback() throws IOException {}
public abstract int write(float[] buffer, int offset, int length);
public abstract void close();
public int getChannelCount() {
return mActualStreamConfiguration.getChannelCount();
}
public int getSampleRate() {
return mActualStreamConfiguration.getSampleRate();
}
public int getFramesPerBurst() {
return mActualStreamConfiguration.getFramesPerBurst();
}
public int getBufferCapacityInFrames() {
return mBufferSizeInFrames;
}
public int getBufferSizeInFrames() {
return mBufferSizeInFrames;
}
public int setBufferSizeInFrames(int bufferSize) {
throw new UnsupportedOperationException("bufferSize cannot be changed");
}
public long getCallbackCount() { return -1; }
public long getFramesWritten() { return -1; }
public long getFramesRead() { return -1; }
public double getLatency() { return -1.0; }
public double getCpuLoad() { return 0.0; }
public int getState() { return -1; }
public boolean isThresholdSupported() {
return false;
}
public void setWorkload(double workload) {}
public abstract int getXRunCount();
}
@@ -0,0 +1,51 @@
/*
* Copyright 2017 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.sample.oboe.manualtest;
import java.io.IOException;
class AudioStreamTester {
protected AudioStreamBase mCurrentAudioStream;
StreamConfiguration requestedConfiguration = new StreamConfiguration();
StreamConfiguration actualConfiguration = new StreamConfiguration();
AudioStreamBase getCurrentAudioStream() {
return mCurrentAudioStream;
}
public void open() throws IOException {
mCurrentAudioStream.open(requestedConfiguration, actualConfiguration,
-1);
}
public void reset() {
requestedConfiguration.reset(); // TODO consider making new ones
actualConfiguration.reset();
}
public void close() {
mCurrentAudioStream.close();
}
public void startPlayback() throws IOException {
mCurrentAudioStream.startPlayback();
}
public void setWorkload(double workload) {
mCurrentAudioStream.setWorkload(workload);
}
}
@@ -0,0 +1,328 @@
/*
* Copyright 2019 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.sample.oboe.manualtest;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.text.method.ScrollingMovementMethod;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Spinner;
import android.widget.TextView;
import java.io.IOException;
import java.util.Date;
public class AutoGlitchActivity extends GlitchActivity implements Runnable {
private static final int SETUP_TIME_SECONDS = 4; // Time for the stream to settle.
private static final int DEFAULT_DURATION_SECONDS = 8; // Run time for each test.
private static final int DEFAULT_GAP_MILLIS = 400; // Run time for each test.
private static final String TEXT_SKIP = "SKIP";
public static final String TEXT_PASS = "PASS";
public static final String TEXT_FAIL = "FAIL !!!!";
private TextView mAutoTextView;
private Thread mAutoThread;
private volatile boolean mThreadEnabled = false;
int mTestCount = 0;
private int mDurationSeconds = DEFAULT_DURATION_SECONDS;
private int mGapMillis = DEFAULT_GAP_MILLIS;
private StringBuffer mFailedSummary;
private int mPassCount = 0;
private int mFailCount = 0;
private Spinner mDurationSpinner;
// Test with these configurations.
private static final int[] PERFORMANCE_MODES = {
StreamConfiguration.PERFORMANCE_MODE_LOW_LATENCY,
StreamConfiguration.PERFORMANCE_MODE_NONE
};
private static final int[] SAMPLE_RATES = { 48000, 44100, 16000 };
private class DurationSpinnerListener implements android.widget.AdapterView.OnItemSelectedListener {
@Override
public void onItemSelected(AdapterView<?> parent, View view, int pos, long id) {
String text = parent.getItemAtPosition(pos).toString();
mDurationSeconds = Integer.parseInt(text);
}
@Override
public void onNothingSelected(AdapterView<?> parent) {
mDurationSeconds = DEFAULT_DURATION_SECONDS;
}
}
@Override
protected void inflateActivity() {
setContentView(R.layout.activity_auto_glitches);
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mAutoTextView = (TextView) findViewById(R.id.text_log);
mAutoTextView.setMovementMethod(new ScrollingMovementMethod());
mDurationSpinner = (Spinner) findViewById(R.id.spinner_glitch_duration);
mDurationSpinner.setOnItemSelectedListener(new DurationSpinnerListener());
}
// Write to scrollable TextView
private void log(final String text) {
runOnUiThread(new Runnable() {
@Override
public void run() {
mAutoTextView.append(text);
mAutoTextView.append("\n");
}
});
}
private void logClear() {
runOnUiThread(new Runnable() {
@Override
public void run() {
mAutoTextView.setText("");
}
});
}
public void startAudioTest() {
mThreadEnabled = true;
mAutoThread = new Thread(this);
mAutoThread.start();
}
// Only call from UI thread.
@Override
public void onTestFinished() {
super.onTestFinished();
}
public void stopAudioTest() {
try {
if (mAutoThread != null) {
mThreadEnabled = false;
mAutoThread.interrupt();
mAutoThread.join(100);
mAutoThread = null;
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
// Share text from log via GMail, Drive or other method.
public void onShareResult(View view) {
Intent sharingIntent = new Intent(android.content.Intent.ACTION_SEND);
sharingIntent.setType("text/plain");
String subjectText = "OboeTester AutoGlitch result " + getTimestampString();
sharingIntent.putExtra(android.content.Intent.EXTRA_SUBJECT, subjectText);
String shareBody = mAutoTextView.getText().toString();
sharingIntent.putExtra(android.content.Intent.EXTRA_TEXT, shareBody);
startActivity(Intent.createChooser(sharingIntent, "Share using:"));
}
private String getConfigText(StreamConfiguration config) {
return ((config.getDirection() == StreamConfiguration.DIRECTION_OUTPUT) ? "OUT" : "IN")
+ ", SR = " + config.getSampleRate()
+ ", Perf = " + StreamConfiguration.convertPerformanceModeToText(
config.getPerformanceMode())
+ ", " + StreamConfiguration.convertSharingModeToText(config.getSharingMode())
+ ", ch = " + config.getChannelCount();
}
private void testConfiguration(int perfMode,
int sharingMode,
int sampleRate,
int inChannels,
int outChannels) throws InterruptedException {
// Configure settings
StreamConfiguration requestedInConfig = mAudioInputTester.requestedConfiguration;
StreamConfiguration actualInConfig = mAudioInputTester.actualConfiguration;
StreamConfiguration requestedOutConfig = mAudioOutTester.requestedConfiguration;
StreamConfiguration actualOutConfig = mAudioOutTester.actualConfiguration;
requestedInConfig.reset();
requestedOutConfig.reset();
requestedInConfig.setPerformanceMode(perfMode);
requestedOutConfig.setPerformanceMode(perfMode);
requestedInConfig.setSharingMode(sharingMode);
requestedOutConfig.setSharingMode(sharingMode);
requestedInConfig.setSampleRate(sampleRate);
requestedOutConfig.setSampleRate(sampleRate);
requestedInConfig.setChannelCount(inChannels);
requestedOutConfig.setChannelCount(outChannels);
log("========================== #" + mTestCount);
log("Requested:");
log(getConfigText(requestedInConfig));
log(getConfigText(requestedOutConfig));
// Give previous stream time to close and release resources. Avoid race conditions.
Thread.sleep(1000);
boolean openFailed = false;
try {
super.startAudioTest(); // this will fill in actualConfig
log("Actual:");
log(getConfigText(actualInConfig));
log(getConfigText(actualOutConfig));
// Set output size to a level that will avoid glitches.
AudioStreamBase stream = mAudioOutTester.getCurrentAudioStream();
int sizeFrames = stream.getBufferCapacityInFrames() / 2;
stream.setBufferSizeInFrames(sizeFrames);
} catch (IOException e) {
openFailed = true;
log(e.getMessage());
}
// The test would only be worth running if we got the configuration we requested on input or output.
boolean valid = true;
// No point running the test if we don't get the sharing mode we requested.
if (!openFailed && actualInConfig.getSharingMode() != sharingMode
&& actualOutConfig.getSharingMode() != sharingMode) {
log("did not get requested sharing mode");
valid = false;
}
// We don't skip based on performance mode because if you request LOW_LATENCY you might
// get a smaller burst than if you request NONE.
if (!openFailed && valid) {
Thread.sleep(mDurationSeconds * 1000);
}
int inXRuns = 0;
int outXRuns = 0;
if (!openFailed) {
// get xRuns before closing the streams.
inXRuns = mAudioInputTester.getCurrentAudioStream().getXRunCount();
outXRuns = mAudioOutTester.getCurrentAudioStream().getXRunCount();
super.stopAudioTest();
}
if (valid) {
if (openFailed) {
mFailedSummary.append("------ #" + mTestCount);
mFailedSummary.append("\n");
mFailedSummary.append(getConfigText(requestedInConfig));
mFailedSummary.append("\n");
mFailedSummary.append(getConfigText(requestedOutConfig));
mFailedSummary.append("\n");
mFailedSummary.append("Open failed!\n");
mFailCount++;
} else {
log("Result:");
boolean passed = (getMaxSecondsWithNoGlitch()
> (mDurationSeconds - SETUP_TIME_SECONDS));
String resultText = getShortReport();
resultText += ", xruns = " + inXRuns + "/" + outXRuns;
resultText += ", " + (passed ? TEXT_PASS : TEXT_FAIL);
log(resultText);
if (!passed) {
mFailedSummary.append("------ #" + mTestCount);
mFailedSummary.append("\n");
mFailedSummary.append(" ");
mFailedSummary.append(getConfigText(actualInConfig));
mFailedSummary.append("\n");
mFailedSummary.append(" ");
mFailedSummary.append(resultText);
mFailedSummary.append("\n");
mFailCount++;
} else {
mPassCount++;
}
}
} else {
log(TEXT_SKIP);
}
// Give hardware time to settle between tests.
Thread.sleep(mGapMillis);
mTestCount++;
}
private void testConfiguration(int performanceMode,
int sharingMode,
int sampleRate) throws InterruptedException {
testConfiguration(performanceMode,
sharingMode,
sampleRate, 1, 2);
testConfiguration(performanceMode,
sharingMode,
sampleRate, 2, 1);
}
@Override
public void run() {
logClear();
log("=== STARTED at " + new Date());
log(Build.MANUFACTURER + " " + Build.PRODUCT);
log(Build.DISPLAY);
mFailedSummary = new StringBuffer();
mTestCount = 0;
mPassCount = 0;
mFailCount = 0;
try {
testConfiguration(StreamConfiguration.PERFORMANCE_MODE_LOW_LATENCY,
StreamConfiguration.SHARING_MODE_EXCLUSIVE,
0);
testConfiguration(StreamConfiguration.PERFORMANCE_MODE_LOW_LATENCY,
StreamConfiguration.SHARING_MODE_SHARED,
0);
for (int perfMode : PERFORMANCE_MODES) {
for (int sampleRate : SAMPLE_RATES) {
testConfiguration(perfMode,
StreamConfiguration.SHARING_MODE_SHARED,
sampleRate);
}
}
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
super.stopAudioTest();
log("\n==== SUMMARY ========");
if (mFailCount > 0) {
log(mPassCount + " passed. " + mFailCount + " failed.");
log("These tests FAILED:");
log(mFailedSummary.toString());
} else {
log("All tests PASSED.");
}
log("== FINISHED at " + new Date());
runOnUiThread(new Runnable() {
@Override
public void run() {
onTestFinished();
}
});
}
}
}
@@ -0,0 +1,143 @@
/*
* Copyright 2019 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.sample.oboe.manualtest;
import android.content.Context;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.widget.SeekBar;
import android.widget.TextView;
import android.widget.LinearLayout;
public class BufferSizeView extends LinearLayout {
AudioOutputTester mAudioOutTester;
protected static final int FADER_THRESHOLD_MAX = 1000; // must match layout
protected TextView mTextThreshold;
protected SeekBar mFaderThreshold;
protected ExponentialTaper mTaperThreshold;
private int mCachedCapacity;
private SeekBar.OnSeekBarChangeListener mThresholdListener = new SeekBar.OnSeekBarChangeListener() {
@Override
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
setBufferSizeByPosition(progress);
}
@Override
public void onStartTrackingTouch(SeekBar seekBar) {
}
@Override
public void onStopTrackingTouch(SeekBar seekBar) {
}
};
public BufferSizeView(Context context) {
super(context);
initializeViews(context);
}
public BufferSizeView(Context context, AttributeSet attrs) {
super(context, attrs);
initializeViews(context);
}
public BufferSizeView(Context context,
AttributeSet attrs,
int defStyle) {
super(context, attrs, defStyle);
initializeViews(context);
}
public AudioOutputTester getAudioOutTester() {
return mAudioOutTester;
}
public void setAudioOutTester(AudioOutputTester audioOutTester) {
mAudioOutTester = audioOutTester;
}
void setFaderNormalizedProgress(double fraction) {
mFaderThreshold.setProgress((int)(fraction * FADER_THRESHOLD_MAX));
}
/**
* Inflates the views in the layout.
*
* @param context
* the current context for the view.
*/
private void initializeViews(Context context) {
LayoutInflater inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
inflater.inflate(R.layout.buffer_size_view, this);
mTextThreshold = (TextView) findViewById(R.id.textThreshold);
mFaderThreshold = (SeekBar) findViewById(R.id.faderThreshold);
mFaderThreshold.setOnSeekBarChangeListener(mThresholdListener);
mTaperThreshold = new ExponentialTaper(0.0, 1.0, 10.0);
mFaderThreshold.setProgress(0);
}
private void setBufferSizeByPosition(int progress) {
StringBuffer message = new StringBuffer();
double normalizedThreshold = mTaperThreshold.linearToExponential(
((double)progress)/FADER_THRESHOLD_MAX);
if (normalizedThreshold < 0.0) normalizedThreshold = 0.0;
else if (normalizedThreshold > 1.0) normalizedThreshold = 1.0;
int percent = (int) (normalizedThreshold * 100);
message.append("bufferSize = " + percent + "%");
OboeAudioStream stream = null;
int sizeFrames = 0;
if (getAudioOutTester() != null) {
stream = (OboeAudioStream) getAudioOutTester().getCurrentAudioStream();
if (stream != null) {
int capacity = stream.getBufferCapacityInFrames();
if (capacity > 0) mCachedCapacity = capacity;
}
}
if (mCachedCapacity > 0) {
sizeFrames = (int) (normalizedThreshold * mCachedCapacity);
message.append(" = " + sizeFrames);
if (stream != null) {
stream.setBufferSizeInFrames(sizeFrames);
}
int bufferSize = getAudioOutTester().getCurrentAudioStream().getBufferSizeInFrames();
if (bufferSize >= 0) {
message.append(" / " + bufferSize);
}
message.append(" / " + mCachedCapacity);
}
mTextThreshold.setText(message.toString());
}
public void updateBufferSize() {
int progress = mFaderThreshold.getProgress();
setBufferSizeByPosition(progress);
}
@Override
public void setEnabled(boolean enabled) {
super.setEnabled(enabled);
mFaderThreshold.setEnabled(enabled);
}
}
@@ -0,0 +1,104 @@
/*
* Copyright (C) 2013 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.sample.oboe.manualtest;
/**
* Circular buffer for continuously capturing audio then reading the previous N samples.
* Can hold from zero to max frames.
*/
public class CircularCaptureBuffer {
private float[] mData;
private int mCursor;
private int mNumValidSamples;
public CircularCaptureBuffer(int maxSamples) {
mData = new float[maxSamples];
}
public int write(float[] buffer) {
return write(buffer, 0, buffer.length);
}
public int write(float[] buffer, int offset, int numSamples) {
if (numSamples > mData.length) {
throw new IllegalArgumentException("Tried to write more than maxSamples.");
}
if ((mCursor + numSamples) > mData.length) {
// Wraps so write in two parts.
int numWrite1 = mData.length - mCursor;
System.arraycopy(buffer, offset, mData, mCursor, numWrite1);
offset += numWrite1;
int numWrite2 = numSamples - numWrite1;
System.arraycopy(buffer, offset, mData, 0, numWrite2);
mCursor = numWrite2;
} else {
System.arraycopy(buffer, offset, mData, mCursor, numSamples);
mCursor += numSamples;
if (mCursor == mData.length) {
mCursor = 0;
}
}
mNumValidSamples += numSamples;
if (mNumValidSamples > mData.length) {
mNumValidSamples = mData.length;
}
return numSamples;
}
public int readMostRecent(float[] buffer) {
return readMostRecent(buffer, 0, buffer.length);
}
/**
* Read the most recently written samples.
* @param buffer
* @param offset
* @param numSamples
* @return number of samples read
*/
public int readMostRecent(float[] buffer, int offset, int numSamples) {
if (numSamples > mNumValidSamples) {
numSamples = mNumValidSamples;
}
int cursor = mCursor; // read once in case it gets updated by another thread
// Read in two parts.
if ((cursor - numSamples) < 0) {
int numRead1 = numSamples - cursor;
System.arraycopy(mData, mData.length - numRead1, buffer, offset, numRead1);
offset += numRead1;
int numRead2 = cursor;
System.arraycopy(mData, 0, buffer, offset, numRead2);
} else {
System.arraycopy(mData, cursor - numSamples, buffer, offset, numSamples);
}
return numSamples;
}
public void erase() {
mNumValidSamples = 0;
mCursor = 0;
}
public int getSize() {
return mData.length;
}
}
@@ -0,0 +1,140 @@
/*
* Copyright 2018 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.sample.oboe.manualtest;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.SeekBar;
import android.widget.TextView;
import java.io.IOException;
/**
* Activity to capture audio and then send a delayed copy to output.
* There is a fader for setting delay time
*/
public class EchoActivity extends TestInputActivity {
AudioOutputTester mAudioOutTester;
protected TextView mTextDelayTime;
protected SeekBar mFaderDelayTime;
protected ExponentialTaper mTaperDelayTime;
private static final double MIN_DELAY_TIME_SECONDS = 0.0;
private static final double MAX_DELAY_TIME_SECONDS = 3.0;
private double mDelayTime;
private Button mStartButton;
private Button mStopButton;
protected static final int MAX_DELAY_TIME_PROGRESS = 1000;
private SeekBar.OnSeekBarChangeListener mDelayListener = new SeekBar.OnSeekBarChangeListener() {
@Override
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
setDelayTimeByPosition(progress);
}
@Override
public void onStartTrackingTouch(SeekBar seekBar) {
}
@Override
public void onStopTrackingTouch(SeekBar seekBar) {
}
};
@Override
protected void inflateActivity() {
setContentView(R.layout.activity_echo);
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
updateEnabledWidgets();
mAudioOutTester = addAudioOutputTester();
mStartButton = (Button) findViewById(R.id.button_start_echo);
mStopButton = (Button) findViewById(R.id.button_stop_echo);
mStopButton.setEnabled(false);
mTextDelayTime = (TextView) findViewById(R.id.text_delay_time);
mFaderDelayTime = (SeekBar) findViewById(R.id.fader_delay_time);
mFaderDelayTime.setOnSeekBarChangeListener(mDelayListener);
mTaperDelayTime = new ExponentialTaper(
MIN_DELAY_TIME_SECONDS,
MAX_DELAY_TIME_SECONDS,
100.0);
mFaderDelayTime.setProgress(MAX_DELAY_TIME_PROGRESS / 2);
hideSettingsViews();
}
private void setDelayTimeByPosition(int progress) {
mDelayTime = mTaperDelayTime.linearToExponential(
((double)progress)/MAX_DELAY_TIME_PROGRESS);
setDelayTime(mDelayTime);
mTextDelayTime.setText("DelayLine: " + (int)(mDelayTime * 1000) + " (msec)");
}
private native void setDelayTime(double delayTimeSeconds);
@Override
protected void onStart() {
super.onStart();
setActivityType(ACTIVITY_ECHO);
}
@Override
protected void resetConfiguration() {
super.resetConfiguration();
mAudioOutTester.reset();
}
public void onStartEcho(View view) {
try {
openAudio();
startAudio();
setDelayTime(mDelayTime);
mStartButton.setEnabled(false);
mStopButton.setEnabled(true);
keepScreenOn(true);
} catch (IOException e) {
showErrorToast(e.getMessage());
}
}
public void onStopEcho(View view) {
stopAudio();
closeAudio();
mStartButton.setEnabled(true);
mStopButton.setEnabled(false);
keepScreenOn(false);
}
@Override
boolean isOutput() {
return false;
}
@Override
public void setupEffects(int sessionId) {
}
}
@@ -0,0 +1,67 @@
/*
* Copyright 2017 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.sample.oboe.manualtest;
/**
* Maps integer range info to a double value along an exponential scale.
*
* <pre>
*
* x = ival / mResolution
* f(x) = a*(root**bx)
* f(0.0) = dmin
* f(1.0) = dmax
*
* f(0.0) = a * 1.0 => a = dmin
* f(1.0) = dmin * root**b = dmax
* b = log(dmax / dmin) / log(root)
*
* </pre>
*/
public class ExponentialTaper {
private double offset = 0.0;
private double a = 1.0;
private double b = 2.0;
private static final double ROOT = 10.0; // because we are using log10
public ExponentialTaper(double dmin, double dmax) {
this(dmin, dmax, 10000.0);
}
public ExponentialTaper(double dmin, double dmax, double maxRatio) {
a = dmax;
double curvature;
if (dmax > dmin * maxRatio) {
offset = dmax / maxRatio;
a = offset;
curvature = (dmax + offset) / offset;
} else {
curvature = dmax / dmin;
a = dmin;
}
b = Math.log10(curvature);
}
public double linearToExponential(double linear) {
return a * Math.pow(ROOT, b * linear) - offset;
}
public double exponentialToLinear(double exponential) {
return Math.log((exponential + offset) / a) / (b * Math.log(ROOT));
}
}
@@ -0,0 +1,112 @@
/*
* Copyright 2015 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.sample.oboe.manualtest;
import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.drawable.Drawable;
import android.text.TextPaint;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;
import android.widget.TextView;
import java.util.ArrayList;
/**
* Button-like View that responds quickly to touch events.
*/
public class FastButton extends TextView {
public FastButton(Context context) {
super(context);
}
public FastButton(Context context, AttributeSet attrs) {
super(context, attrs);
}
public FastButton(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
}
private ArrayList<FastButtonListener> mListeners = new ArrayList<FastButtonListener>();
/**
* Implement this to receive keyboard events.
*/
public interface FastButtonListener {
/**
* This will be called when a key is pressed.
*/
public void onKeyDown(int id);
/**
* This will be called when a key is pressed.
*/
public void onKeyUp(int id);
}
@Override
public boolean onTouchEvent(MotionEvent event) {
super.onTouchEvent(event);
int action = event.getActionMasked();
// Track individual fingers.
int pointerIndex = event.getActionIndex();
int id = event.getPointerId(pointerIndex);
switch (action) {
case MotionEvent.ACTION_DOWN:
case MotionEvent.ACTION_POINTER_DOWN:
fireKeyDown(id);
break;
case MotionEvent.ACTION_MOVE:
break;
case MotionEvent.ACTION_UP:
case MotionEvent.ACTION_POINTER_UP:
fireKeyUp(id);
break;
}
// Must return true or we do not get the ACTION_MOVE and
// ACTION_UP events.
return true;
}
private void fireKeyDown(int id) {
for (FastButtonListener listener : mListeners) {
listener.onKeyDown(id);
}
invalidate();
}
private void fireKeyUp(int id) {
for (FastButtonListener listener : mListeners) {
listener.onKeyUp(id);
}
invalidate();
}
public void addFastButtonListener(FastButtonListener listener) {
mListeners.add(listener);
}
public void removeFastButtonListener(FastButtonListener listener) {
mListeners.remove(listener);
}
}
@@ -0,0 +1,337 @@
/*
* Copyright 2018 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.sample.oboe.manualtest;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import java.io.IOException;
/**
* Activity to measure the number of glitches.
*/
public class GlitchActivity extends AnalyzerActivity {
private TextView mAnalyzerTextView;
private Button mStartButton;
private Button mStopButton;
private Button mShareButton;
// These must match the values in LatencyAnalyzer.h
final static int STATE_IDLE = 0;
final static int STATE_IMMUNE = 1;
final static int STATE_WAITING_FOR_SIGNAL = 2;
final static int STATE_WAITING_FOR_LOCK = 3;
final static int STATE_LOCKED = 4;
final static int STATE_GLITCHING = 5;
String mLastGlitchReport;
native int getStateFrameCount(int state);
native int getGlitchCount();
native double getSignalToNoiseDB();
native double getPeakAmplitude();
// Note that these strings must match the enum result_code in LatencyAnalyzer.h
String stateToString(int resultCode) {
switch (resultCode) {
case STATE_IDLE:
return "IDLE";
case STATE_IMMUNE:
return "IMMUNE";
case STATE_WAITING_FOR_SIGNAL:
return "WAITING_FOR_SIGNAL";
case STATE_WAITING_FOR_LOCK:
return "WAITING_FOR_LOCK";
case STATE_LOCKED:
return "LOCKED";
case STATE_GLITCHING:
return "GLITCHING";
default:
return "UNKNOWN";
}
}
// Periodically query for glitches from the native detector.
protected class GlitchSniffer {
public static final int SNIFFER_UPDATE_PERIOD_MSEC = 100;
public static final int SNIFFER_UPDATE_DELAY_MSEC = 200;
private long mTimeAtStart;
private long mTimeOfLastGlitch;
private double mSecondsWithoutGlitches;
private double mMaxSecondsWithoutGlitches;
private int mLastGlitchCount;
private int mLastUnlockedFrames;
private int mLastLockedFrames;
private int mLastGlitchFrames;
private int mStartResetCount;
private int mLastResetCount;
private int mPreviousState;
private double mSignalToNoiseDB;
private double mPeakAmplitude;
private Handler mHandler = new Handler(Looper.getMainLooper()); // UI thread
private volatile boolean mEnabled = true;
private void startSniffer() {
long now = System.currentTimeMillis();
mTimeAtStart = now;
mTimeOfLastGlitch = now;
mLastUnlockedFrames = 0;
mLastLockedFrames = 0;
mLastGlitchFrames = 0;
mSecondsWithoutGlitches = 0.0;
mMaxSecondsWithoutGlitches = 0.0;
mLastGlitchCount = 0;
mStartResetCount = mLastResetCount;
// Start the initial runnable task by posting through the handler
mEnabled = true;
mHandler.postDelayed(runnableCode, SNIFFER_UPDATE_DELAY_MSEC);
}
private void stopSniffer() {
mEnabled = false;
if (mHandler != null) {
mHandler.removeCallbacks(runnableCode);
}
runOnUiThread(new Runnable() {
@Override
public void run() {
updateStatusText();
}
});
}
private Runnable runnableCode = new Runnable() {
@Override
public void run() {
int state = getAnalyzerState();
mSignalToNoiseDB = getSignalToNoiseDB();
mPeakAmplitude = getPeakAmplitude();
mPreviousState = state;
long now = System.currentTimeMillis();
int glitchCount = getGlitchCount();
int resetCount = getResetCount();
mLastUnlockedFrames = getStateFrameCount(STATE_WAITING_FOR_LOCK);
int lockedFrames = getStateFrameCount(STATE_LOCKED);
int glitchFrames = getStateFrameCount(STATE_GLITCHING);
if (glitchFrames > mLastGlitchFrames || glitchCount > mLastGlitchCount) {
mTimeOfLastGlitch = now;
mSecondsWithoutGlitches = 0.0;
onGlitchDetected();
} else if (lockedFrames > mLastLockedFrames) {
mSecondsWithoutGlitches = (now - mTimeOfLastGlitch) / 1000.0;
}
if (resetCount > mLastResetCount) {
mLastResetCount = resetCount;
}
if (mSecondsWithoutGlitches > mMaxSecondsWithoutGlitches) {
mMaxSecondsWithoutGlitches = mSecondsWithoutGlitches;
}
mLastGlitchCount = glitchCount;
mLastGlitchFrames = glitchFrames;
mLastLockedFrames = lockedFrames;
mLastResetCount = resetCount;
updateStatusText();
// Reschedule so this task repeats
if (mEnabled) {
mHandler.postDelayed(runnableCode, SNIFFER_UPDATE_PERIOD_MSEC);
}
}
};
String getCurrentStatusReport() {
long now = System.currentTimeMillis();
double totalSeconds = (now - mTimeAtStart) / 1000.0;
StringBuffer message = new StringBuffer();
message.append("state = " + stateToString(mPreviousState) + "\n");
message.append(String.format("unlocked.frames = %d\n", mLastUnlockedFrames));
message.append(String.format("locked.frames = %d\n", mLastLockedFrames));
message.append(String.format("glitch.frames = %d\n", mLastGlitchFrames));
message.append(String.format("reset.count = %d\n", mLastResetCount - mStartResetCount));
message.append(String.format("peak.amplitude = %8.6f\n", mPeakAmplitude));
if (mLastLockedFrames > 0) {
message.append(String.format("signal.noise.ratio.db = %5.1f\n", mSignalToNoiseDB));
}
message.append(String.format("time.total = %8.2f seconds\n", totalSeconds));
if (mLastLockedFrames > 0) {
message.append(String.format("time.no.glitches = %8.2f\n", mSecondsWithoutGlitches));
message.append(String.format("max.time.no.glitches = %8.2f\n",
mMaxSecondsWithoutGlitches));
message.append(String.format("glitch.count = %d\n", mLastGlitchCount));
}
return message.toString();
}
public String getShortReport() {
String resultText = "#glitches = " + getLastGlitchCount()
+ ", #resets = " + getLastResetCount()
+ ", max no glitch = " + getMaxSecondsWithNoGlitch() + " secs\n";
resultText += String.format("SNR = %5.1f db", mSignalToNoiseDB);
resultText += ", #locked = " + mLastLockedFrames;
return resultText;
}
private void updateStatusText() {
mLastGlitchReport = getCurrentStatusReport();
setAnalyzerText(mLastGlitchReport);
}
public double getMaxSecondsWithNoGlitch() {
return mMaxSecondsWithoutGlitches;
}
public int getLastGlitchCount() {
return mLastGlitchCount;
}
public int getLastResetCount() {
return mLastResetCount;
}
}
// Called on UI thread
protected void onGlitchDetected() {
}
private GlitchSniffer mGlitchSniffer = new GlitchSniffer();
private void setAnalyzerText(String s) {
mAnalyzerTextView.setText(s);
}
/**
* Set tolerance to deviations from expected value.
* The normalized value will be converted in the native code.
* @param tolerance normalized between 0.0 and 1.0
*/
public native void setTolerance(float tolerance);
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mStartButton = (Button) findViewById(R.id.button_start);
mStopButton = (Button) findViewById(R.id.button_stop);
mStopButton.setEnabled(false);
mShareButton = (Button) findViewById(R.id.button_share);
mShareButton.setEnabled(false);
mAnalyzerTextView = (TextView) findViewById(R.id.text_status);
updateEnabledWidgets();
hideSettingsViews();
// TODO hide sample rate menu
StreamContext streamContext = getFirstInputStreamContext();
if (streamContext != null) {
if (streamContext.configurationView != null) {
streamContext.configurationView.hideSampleRateMenu();
}
}
}
@Override
protected void onStart() {
super.onStart();
setActivityType(ACTIVITY_GLITCHES);
mStartButton.setEnabled(true);
mStopButton.setEnabled(false);
mShareButton.setEnabled(false);
}
@Override
protected void onStop() {
stopAudioTest();
super.onStop();
}
// Called on UI thread
public void onStartAudioTest(View view) throws IOException {
startAudioTest();
mStartButton.setEnabled(false);
mStopButton.setEnabled(true);
mShareButton.setEnabled(false);
keepScreenOn(true);
}
public void startAudioTest() throws IOException {
openAudio();
startAudio();
mGlitchSniffer.startSniffer();
onTestBegan();
}
public void onCancel(View view) {
stopAudioTest();
onTestFinished();
}
// Called on UI thread
public void onStopAudioTest(View view) {
stopAudioTest();
onTestFinished();
keepScreenOn(false);
}
// Must be called on UI thread.
public void onTestBegan() {
}
// Must be called on UI thread.
public void onTestFinished() {
mStartButton.setEnabled(true);
mStopButton.setEnabled(false);
mShareButton.setEnabled(true);
}
public void stopAudioTest() {
mGlitchSniffer.stopSniffer();
stopAudio();
closeAudio();
}
@Override
boolean isOutput() {
return false;
}
@Override
public void setupEffects(int sessionId) {
}
public double getMaxSecondsWithNoGlitch() {
return mGlitchSniffer.getMaxSecondsWithNoGlitch();
}
public String getShortReport() {
return mGlitchSniffer.getShortReport();
}
@Override
String getWaveTag() {
return "glitches";
}
}
@@ -0,0 +1,64 @@
/*
* Copyright 2019 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.sample.oboe.manualtest;
import android.content.Context;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.CheckBox;
import android.widget.LinearLayout;
import java.util.ArrayList;
/**
* View for editing an input stream margin to avoid glitches.
*
* TODO: Is this class actually needed?
*/
public class InputMarginView extends LinearLayout {
public InputMarginView(Context context) {
super(context);
initializeViews(context);
}
public InputMarginView(Context context, AttributeSet attrs) {
super(context, attrs);
initializeViews(context);
}
public InputMarginView(Context context,
AttributeSet attrs,
int defStyle) {
super(context, attrs, defStyle);
initializeViews(context);
}
/**
* Inflates the views in the layout.
*
* @param context
* the current context for the view.
*/
private void initializeViews(Context context) {
LayoutInflater inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
inflater.inflate(R.layout.input_margin_view, this);
}
}
@@ -0,0 +1,260 @@
/*
* Copyright 2017 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.sample.oboe.manualtest;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.graphics.Point;
import android.media.AudioManager;
import android.os.Build;
import android.os.Bundle;
import android.util.Log;
import android.view.Display;
import android.view.View;
import android.widget.AdapterView;
import android.widget.CheckBox;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
/**
* Select various Audio tests.
*/
public class MainActivity extends Activity {
private static final String KEY_TEST_NAME = "test";
public static final String VALUE_TEST_NAME_LATENCY = "latency";
public static final String VALUE_TEST_NAME_GLITCH = "glitch";
static {
// Must match name in CMakeLists.txt
System.loadLibrary("oboetester");
}
private Spinner mModeSpinner;
private TextView mCallbackSizeTextView;
protected TextView mDeviceView;
private TextView mVersionTextView;
private TextView mBuildTextView;
private Bundle mBundleFromIntent;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
logScreenSize();
mVersionTextView = (TextView) findViewById(R.id.versionText);
mCallbackSizeTextView = (TextView) findViewById(R.id.callbackSize);
mDeviceView = (TextView) findViewById(R.id.deviceView);
updateNativeAudioUI();
// Set mode, eg. MODE_IN_COMMUNICATION
mModeSpinner = (Spinner) findViewById(R.id.spinnerAudioMode);
mModeSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
long mode = mModeSpinner.getSelectedItemId();
AudioManager myAudioMgr = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
myAudioMgr.setMode((int)mode);
}
@Override
public void onNothingSelected(AdapterView<?> adapterView) {
}
});
try {
PackageInfo pinfo = getPackageManager().getPackageInfo(getPackageName(), 0);
int oboeVersion = OboeAudioStream.getOboeVersionNumber();
int oboeMajor = (oboeVersion >> 24) & 0xFF;
int oboeMinor = (oboeVersion >> 16) & 0xFF;
int oboePatch = oboeVersion & 0xFF;
mVersionTextView.setText("Test v (" + pinfo.versionCode + ") " + pinfo.versionName
+ ", Oboe v " + oboeMajor + "." + oboeMinor + "." + oboePatch);
} catch (PackageManager.NameNotFoundException e) {
mVersionTextView.setText(e.getMessage());
}
mBuildTextView = (TextView) findViewById(R.id.text_build_info);
mBuildTextView.setText(Build.DISPLAY);
saveIntentBundleForLaterProcessing(getIntent());
}
private void logScreenSize() {
Display display = getWindowManager().getDefaultDisplay();
Point size = new Point();
display.getSize(size);
int width = size.x;
int height = size.y;
Log.i(TestAudioActivity.TAG, "Screen size = " + size.x + " * " + size.y);
}
@Override
public void onNewIntent(Intent intent) {
saveIntentBundleForLaterProcessing(intent);
}
// This will get processed during onResume.
private void saveIntentBundleForLaterProcessing(Intent intent) {
mBundleFromIntent = intent.getExtras();
}
private void processBundleFromIntent() {
if (mBundleFromIntent == null) {
return;
}
if (mBundleFromIntent.containsKey(KEY_TEST_NAME)) {
String testName = mBundleFromIntent.getString(KEY_TEST_NAME);
if (VALUE_TEST_NAME_LATENCY.equals(testName)) {
Intent intent = new Intent(this, RoundTripLatencyActivity.class);
intent.putExtras(mBundleFromIntent);
startActivity(intent);
} else if (VALUE_TEST_NAME_GLITCH.equals(testName)) {
Intent intent = new Intent(this, ManualGlitchActivity.class);
intent.putExtras(mBundleFromIntent);
startActivity(intent);
}
}
mBundleFromIntent = null;
}
@Override
public void onResume(){
super.onResume();
NativeEngine.setWorkaroundsEnabled(false);
processBundleFromIntent();
}
private void updateNativeAudioUI() {
AudioManager myAudioMgr = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
String audioManagerSampleRate = myAudioMgr.getProperty(AudioManager.PROPERTY_OUTPUT_SAMPLE_RATE);
String audioManagerFramesPerBurst = myAudioMgr.getProperty(AudioManager.PROPERTY_OUTPUT_FRAMES_PER_BUFFER);
mDeviceView.setText("Java AudioManager: rate = " + audioManagerSampleRate +
", burst = " + audioManagerFramesPerBurst);
}
public void onLaunchTestOutput(View view) {
updateCallbackSize();
Intent intent = new Intent(this, TestOutputActivity.class);
startActivity(intent);
}
public void onLaunchTestInput(View view) {
updateCallbackSize();
Intent intent = new Intent(this, TestInputActivity.class);
startActivity(intent);
}
public void onLaunchTapToTone(View view) {
updateCallbackSize();
Intent intent = new Intent(this, TapToToneActivity.class);
startActivity(intent);
}
public void onLaunchRecorder(View view) {
updateCallbackSize();
Intent intent = new Intent(this, RecorderActivity.class);
startActivity(intent);
}
public void onLaunchEcho(View view) {
updateCallbackSize();
Intent intent = new Intent(this, EchoActivity.class);
startActivity(intent);
}
public void onLaunchRoundTripLatency(View view) {
updateCallbackSize();
Intent intent = new Intent(this, RoundTripLatencyActivity.class);
startActivity(intent);
}
public void onLaunchManualGlitchTest(View view) {
updateCallbackSize();
Intent intent = new Intent(this, ManualGlitchActivity.class);
startActivity(intent);
}
public void onLaunchAutoGlitchTest(View view) {
updateCallbackSize();
Intent intent = new Intent(this, AutoGlitchActivity.class);
startActivity(intent);
}
public void onLaunchTestDisconnect(View view) {
updateCallbackSize();
Intent intent = new Intent(this, TestDisconnectActivity.class);
startActivity(intent);
}
public void onUseCallbackClicked(View view) {
CheckBox checkBox = (CheckBox) view;
OboeAudioStream.setUseCallback(checkBox.isChecked());
}
protected void showErrorToast(String message) {
showToast("Error: " + message);
}
protected void showToast(final String message) {
runOnUiThread(new Runnable() {
@Override
public void run() {
Toast.makeText(MainActivity.this,
message,
Toast.LENGTH_SHORT).show();
}
});
}
private void updateCallbackSize() {
CharSequence chars = mCallbackSizeTextView.getText();
String text = chars.toString();
int callbackSize = 0;
try {
callbackSize = Integer.parseInt(text);
} catch (NumberFormatException e) {
showErrorToast("Badly formated callback size: " + text);
mCallbackSizeTextView.setText("0");
}
OboeAudioStream.setCallbackSize(callbackSize);
}
public void onSetSpeakerphoneOn(View view) {
CheckBox checkBox = (CheckBox) view;
boolean enabled = checkBox.isChecked();
AudioManager myAudioMgr = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
myAudioMgr.setSpeakerphoneOn(enabled);
}
public void onEnableWorkarounds(View view) {
CheckBox checkBox = (CheckBox) view;
boolean enabled = checkBox.isChecked();
NativeEngine.setWorkaroundsEnabled(enabled);
}
}
@@ -0,0 +1,286 @@
/*
* Copyright 2019 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.sample.oboe.manualtest;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.widget.SeekBar;
import android.widget.TextView;
import java.io.IOException;
import java.util.stream.Stream;
public class ManualGlitchActivity extends GlitchActivity {
public static final String KEY_IN_PERF = "in_perf";
public static final String KEY_OUT_PERF = "out_perf";
public static final String VALUE_PERF_LOW_LATENCY = "lowlat";
public static final String VALUE_PERF_POWERSAVE = "powersave";
public static final String VALUE_PERF_NONE = "none";
public static final String KEY_IN_SHARING = "in_sharing";
public static final String KEY_OUT_SHARING = "out_sharing";
public static final String VALUE_SHARING_EXCLUSIVE = "exclusive";
public static final String VALUE_SHARING_SHARED = "shared";
public static final String KEY_SAMPLE_RATE = "sample_rate";
public static final int VALUE_DEFAULT_SAMPLE_RATE = 48000;
public static final String KEY_IN_PRESET = "in_preset";
public static final String KEY_IN_CHANNELS = "in_channels";
public static final String KEY_OUT_CHANNELS = "out_channels";
public static final int VALUE_DEFAULT_CHANNELS = 2;
public static final String KEY_DURATION = "duration";
public static final int VALUE_DEFAULT_DURATION = 10;
public static final String KEY_BUFFER_BURSTS = "buffer_bursts";
public static final int VALUE_DEFAULT_BUFFER_BURSTS = 2;
public static final String KEY_TOLERANCE = "tolerance";
private static final float DEFAULT_TOLERANCE = 0.1f;
private TextView mTextTolerance;
private SeekBar mFaderTolerance;
protected ExponentialTaper mTaperTolerance;
private WaveformView mWaveformView;
private float[] mWaveform = new float[256];
private boolean mTestRunningByIntent;
private Bundle mBundleFromIntent;
private float mTolerance = DEFAULT_TOLERANCE;
private SeekBar.OnSeekBarChangeListener mToleranceListener = new SeekBar.OnSeekBarChangeListener() {
@Override
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
setToleranceProgress(progress);
}
@Override
public void onStartTrackingTouch(SeekBar seekBar) {
}
@Override
public void onStopTrackingTouch(SeekBar seekBar) {
}
};
protected void setToleranceProgress(int progress) {
float tolerance = (float) mTaperTolerance.linearToExponential(
((double)progress) / FADER_PROGRESS_MAX);
setTolerance(tolerance);
mTextTolerance.setText("Tolerance = " + String.format("%5.3f", tolerance));
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mBundleFromIntent = getIntent().getExtras();
mTextTolerance = (TextView) findViewById(R.id.textTolerance);
mFaderTolerance = (SeekBar) findViewById(R.id.faderTolerance);
mTaperTolerance = new ExponentialTaper(0.0, 0.5, 100.0);
mFaderTolerance.setOnSeekBarChangeListener(mToleranceListener);
setToleranceFader(DEFAULT_TOLERANCE);
mWaveformView = (WaveformView) findViewById(R.id.waveview_audio);
}
private void setToleranceFader(float tolerance) {
int progress = (int) Math.round((mTaperTolerance.exponentialToLinear(
tolerance) * FADER_PROGRESS_MAX));
mFaderTolerance.setProgress(progress);
}
@Override
protected void inflateActivity() {
setContentView(R.layout.activity_manual_glitches);
}
@Override
public void onResume(){
super.onResume();
processBundleFromIntent();
}
@Override
public void onNewIntent(Intent intent) {
mBundleFromIntent = intent.getExtras();
}
private void processBundleFromIntent() {
if (mBundleFromIntent == null) {
return;
}
if (mTestRunningByIntent) {
return;
}
mResultFileName = null;
if (mBundleFromIntent.containsKey(KEY_FILE_NAME)) {
mTestRunningByIntent = true;
mResultFileName = mBundleFromIntent.getString(KEY_FILE_NAME);
// Delay the test start to avoid race conditions.
Handler handler = new Handler(Looper.getMainLooper()); // UI thread
handler.postDelayed(new Runnable() {
@Override
public void run() {
startAutomaticTest();
}
}, 500); // TODO where is the race, close->open?
}
}
private int getPerfFromText(String text) {
if (VALUE_PERF_NONE.equals(text)) {
return StreamConfiguration.PERFORMANCE_MODE_NONE;
} else if (VALUE_PERF_POWERSAVE.equals(text)) {
return StreamConfiguration.PERFORMANCE_MODE_POWER_SAVING;
} else {
return StreamConfiguration.PERFORMANCE_MODE_LOW_LATENCY;
}
}
private int getSharingFromText(String text) {
if (VALUE_SHARING_SHARED.equals(text)) {
return StreamConfiguration.SHARING_MODE_SHARED;
} else {
return StreamConfiguration.SHARING_MODE_EXCLUSIVE;
}
}
void configureStreamsFromBundle(Bundle bundle) {
// Configure settings
StreamConfiguration requestedInConfig = mAudioInputTester.requestedConfiguration;
StreamConfiguration requestedOutConfig = mAudioOutTester.requestedConfiguration;
requestedInConfig.reset();
requestedOutConfig.reset();
// Extract parameters from the bundle.
String text = bundle.getString(KEY_IN_PERF, VALUE_PERF_LOW_LATENCY);
int perfMode = getPerfFromText(text);
requestedInConfig.setPerformanceMode(perfMode);
text = bundle.getString(KEY_OUT_PERF, VALUE_PERF_LOW_LATENCY);
perfMode = getPerfFromText(text);
requestedOutConfig.setPerformanceMode(perfMode);
text = bundle.getString(KEY_IN_SHARING, VALUE_SHARING_EXCLUSIVE);
int sharingMode = getSharingFromText(text);
requestedInConfig.setSharingMode(sharingMode);
text = bundle.getString(KEY_OUT_SHARING, VALUE_SHARING_EXCLUSIVE);
sharingMode = getSharingFromText(text);
requestedOutConfig.setSharingMode(sharingMode);
int sampleRate = bundle.getInt(KEY_SAMPLE_RATE, VALUE_DEFAULT_SAMPLE_RATE);
requestedInConfig.setSampleRate(sampleRate);
requestedOutConfig.setSampleRate(sampleRate);
float tolerance = bundle.getFloat(KEY_TOLERANCE, DEFAULT_TOLERANCE);
setToleranceFader(tolerance);
setTolerance(tolerance);
mTolerance = tolerance;
int inChannels = bundle.getInt(KEY_IN_CHANNELS, VALUE_DEFAULT_CHANNELS);
requestedInConfig.setChannelCount(inChannels);
int outChannels = bundle.getInt(KEY_OUT_CHANNELS, VALUE_DEFAULT_CHANNELS);
requestedOutConfig.setChannelCount(outChannels);
String defaultText = StreamConfiguration.convertInputPresetToText(
StreamConfiguration.INPUT_PRESET_VOICE_RECOGNITION);
text = bundle.getString(KEY_IN_PRESET, defaultText);
int inputPreset = StreamConfiguration.convertTextToInputPreset(text);
requestedInConfig.setInputPreset(inputPreset);
}
public void startAudioTest() throws IOException {
super.startAudioTest();
setToleranceProgress(mFaderTolerance.getProgress());
}
void startAutomaticTest() {
configureStreamsFromBundle(mBundleFromIntent);
int durationSeconds = mBundleFromIntent.getInt(KEY_DURATION, VALUE_DEFAULT_DURATION);
int numBursts = mBundleFromIntent.getInt(KEY_BUFFER_BURSTS, VALUE_DEFAULT_BUFFER_BURSTS);
mBundleFromIntent = null;
try {
onStartAudioTest(null);
int sizeFrames = mAudioOutTester.getCurrentAudioStream().getFramesPerBurst() * numBursts;
mAudioOutTester.getCurrentAudioStream().setBufferSizeInFrames(sizeFrames);
// Schedule the end of the test.
Handler handler = new Handler(Looper.getMainLooper()); // UI thread
handler.postDelayed(new Runnable() {
@Override
public void run() {
stopAutomaticTest();
}
}, durationSeconds * 1000);
} catch (IOException e) {
String report = "Open failed: " + e.getMessage();
maybeWriteTestResult(report);
mTestRunningByIntent = false;
}
}
void stopAutomaticTest() {
String report = getCommonTestReport()
+ String.format("tolerance = %5.3f\n", mTolerance)
+ mLastGlitchReport;
onStopAudioTest(null);
maybeWriteTestResult(report);
mTestRunningByIntent = false;
}
// Only call from UI thread.
@Override
public void onTestFinished() {
super.onTestFinished();
}
// Only call from UI thread.
@Override
public void onTestBegan() {
mWaveformView.clearSampleData();
mWaveformView.postInvalidate();
super.onTestBegan();
}
// Called on UI thread
@Override
protected void onGlitchDetected() {
int numSamples = getGlitch(mWaveform);
mWaveformView.setSampleData(mWaveform, 0, numSamples);
mWaveformView.postInvalidate();
}
private float[] getGlitchWaveform() {
return mWaveform;
}
private native int getGlitch(float[] mWaveform);
}
@@ -0,0 +1,10 @@
package com.google.sample.oboe.manualtest;
public class NativeEngine {
static native boolean isMMapSupported();
static native boolean isMMapExclusiveSupported();
static native void setWorkaroundsEnabled(boolean enabled);
}
@@ -0,0 +1,26 @@
/*
* Copyright 2017 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.sample.oboe.manualtest;
class OboeAudioInputStream extends OboeAudioStream {
@Override
public boolean isInput() {
return true;
}
}
@@ -0,0 +1,42 @@
/*
* Copyright 2015 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.sample.oboe.manualtest;
/**
* Native synthesizer and audio output.
*/
public class OboeAudioOutputStream extends OboeAudioStream {
// WARNING - must match order in strings.xml
public static final int TONE_TYPE_SAW_PING = 0;
public static final int TONE_TYPE_SINE = 1;
public static final int TONE_TYPE_IMPULSE = 2;
public static final int TONE_TYPE_SAWTOOTH = 3;
@Override
public boolean isInput() {
return false;
}
public native void setToneEnabled(boolean enabled);
public native void setToneType(int index);
public native void setChannelEnabled(int channelIndex, boolean enabled);
public native void setSignalType(int type);
}
@@ -0,0 +1,255 @@
/*
* Copyright 2017 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.sample.oboe.manualtest;
import java.io.IOException;
/**
* Implementation of an AudioStreamBase using Oboe.
*/
abstract class OboeAudioStream extends AudioStreamBase {
private static final int INVALID_STREAM_INDEX = -1;
int streamIndex = INVALID_STREAM_INDEX;
@Override
public void stopPlayback() throws IOException {
int result = stopPlaybackNative();
if (result < 0) {
throw new IOException("Stop Playback failed! result = " + result);
}
}
public native int stopPlaybackNative();
@Override
public void startPlayback() throws IOException {
int result = startPlaybackNative();
if (result < 0) {
throw new IOException("Start Playback failed! result = " + result);
}
}
public native int startPlaybackNative();
// Write disabled because the synth is in native code.
@Override
public int write(float[] buffer, int offset, int length) {
return 0;
}
@Override
public void open(StreamConfiguration requestedConfiguration,
StreamConfiguration actualConfiguration, int bufferSizeInFrames) throws IOException {
super.open(requestedConfiguration, actualConfiguration, bufferSizeInFrames);
int result = openNative(requestedConfiguration.getNativeApi(),
requestedConfiguration.getSampleRate(),
requestedConfiguration.getChannelCount(),
requestedConfiguration.getFormat(),
requestedConfiguration.getSharingMode(),
requestedConfiguration.getPerformanceMode(),
requestedConfiguration.getInputPreset(),
requestedConfiguration.getDeviceId(),
requestedConfiguration.getSessionId(),
requestedConfiguration.getFramesPerBurst(),
requestedConfiguration.getChannelConversionAllowed(),
requestedConfiguration.getFormatConversionAllowed(),
requestedConfiguration.getRateConversionQuality(),
requestedConfiguration.isMMap(),
isInput()
);
if (result < 0) {
streamIndex = INVALID_STREAM_INDEX;
throw new IOException("Open failed! result = " + result);
} else {
streamIndex = result;
}
actualConfiguration.setNativeApi(getNativeApi());
actualConfiguration.setSampleRate(getSampleRate());
actualConfiguration.setSharingMode(getSharingMode());
actualConfiguration.setPerformanceMode(getPerformanceMode());
actualConfiguration.setInputPreset(getInputPreset());
actualConfiguration.setFramesPerBurst(getFramesPerBurst());
actualConfiguration.setBufferCapacityInFrames(getBufferCapacityInFrames());
actualConfiguration.setChannelCount(getChannelCount());
actualConfiguration.setDeviceId(getDeviceId());
actualConfiguration.setSessionId(getSessionId());
actualConfiguration.setFormat(getFormat());
actualConfiguration.setMMap(isMMap());
actualConfiguration.setDirection(isInput()
? StreamConfiguration.DIRECTION_INPUT
: StreamConfiguration.DIRECTION_OUTPUT);
}
private native int openNative(
int nativeApi,
int sampleRate,
int channelCount,
int format,
int sharingMode,
int performanceMode,
int inputPreset,
int deviceId,
int sessionId,
int framesPerRead,
boolean channelConversionAllowed,
boolean formatConversionAllowed,
int rateConversionQuality,
boolean isMMap,
boolean isInput);
@Override
public void close() {
if (streamIndex >= 0) {
close(streamIndex);
streamIndex = INVALID_STREAM_INDEX;
}
}
public native void close(int streamIndex);
@Override
public int getBufferCapacityInFrames() {
return getBufferCapacityInFrames(streamIndex);
}
private native int getBufferCapacityInFrames(int streamIndex);
@Override
public int getBufferSizeInFrames() {
return getBufferSizeInFrames(streamIndex);
}
private native int getBufferSizeInFrames(int streamIndex);
@Override
public boolean isThresholdSupported() {
return true;
}
@Override
public int setBufferSizeInFrames(int thresholdFrames) {
return setBufferSizeInFrames(streamIndex, thresholdFrames);
}
private native int setBufferSizeInFrames(int streamIndex, int thresholdFrames);
public int getNativeApi() {
return getNativeApi(streamIndex);
}
public native int getNativeApi(int streamIndex);
@Override
public int getFramesPerBurst() {
return getFramesPerBurst(streamIndex);
}
public native int getFramesPerBurst(int streamIndex);
public int getSharingMode() {
return getSharingMode(streamIndex);
}
public native int getSharingMode(int streamIndex);
public int getPerformanceMode() {
return getPerformanceMode(streamIndex);
}
public native int getPerformanceMode(int streamIndex);
public int getInputPreset() {
return getInputPreset(streamIndex);
}
public native int getInputPreset(int streamIndex);
public int getSampleRate() {
return getSampleRate(streamIndex);
}
public native int getSampleRate(int streamIndex);
public int getFormat() {
return getFormat(streamIndex);
}
public native int getFormat(int streamIndex);
public int getChannelCount() {
return getChannelCount(streamIndex);
}
public native int getChannelCount(int streamIndex);
public int getDeviceId() {
return getDeviceId(streamIndex);
}
public native int getDeviceId(int streamIndex);
public int getSessionId() {
return getSessionId(streamIndex);
}
public native int getSessionId(int streamIndex);
public boolean isMMap() {
return isMMap(streamIndex);
}
public native boolean isMMap(int streamIndex);
@Override
public long getCallbackCount() {
return getCallbackCount(streamIndex);
}
public native long getCallbackCount(int streamIndex);
@Override
public long getFramesWritten() {
return getFramesWritten(streamIndex);
}
public native long getFramesWritten(int streamIndex);
@Override
public long getFramesRead() {
return getFramesRead(streamIndex);
}
public native long getFramesRead(int streamIndex);
@Override
public int getXRunCount() {
return getXRunCount(streamIndex);
}
public native int getXRunCount(int streamIndex);
@Override
public double getLatency() {
return getLatency(streamIndex);
}
public native double getLatency(int streamIndex);
@Override
public double getCpuLoad() {
return getCpuLoad(streamIndex);
}
public native double getCpuLoad(int streamIndex);
@Override
public native void setWorkload(double workload);
@Override
public int getState() {
return getState(streamIndex);
}
public native int getState(int streamIndex);
public static native void setCallbackReturnStop(boolean b);
public static native void setUseCallback(boolean checked);
public static native void setCallbackSize(int callbackSize);
public static native int getOboeVersionNumber();
}

Some files were not shown because too many files have changed in this diff Show More