mirror of
https://github.com/love2d/love-android.git
synced 2026-08-19 12:14:49 +02:00
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:
@@ -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'
|
||||
}
|
||||
Binary file not shown.
+6
@@ -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
@@ -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" "$@"
|
||||
@@ -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
|
||||
+89
@@ -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 */
|
||||
|
||||
+58
@@ -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;
|
||||
}
|
||||
}
|
||||
+140
@@ -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";
|
||||
}
|
||||
}
|
||||
}
|
||||
+93
@@ -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;
|
||||
}
|
||||
}
|
||||
+127
@@ -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);
|
||||
}
|
||||
}
|
||||
+236
@@ -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;
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
+40
@@ -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);
|
||||
}
|
||||
+203
@@ -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();
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
+60
@@ -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);
|
||||
}
|
||||
}
|
||||
+156
@@ -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);
|
||||
}
|
||||
|
||||
}
|
||||
+176
@@ -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();
|
||||
|
||||
|
||||
}
|
||||
+51
@@ -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);
|
||||
}
|
||||
}
|
||||
+328
@@ -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();
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
+143
@@ -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);
|
||||
}
|
||||
}
|
||||
+104
@@ -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;
|
||||
}
|
||||
|
||||
}
|
||||
+140
@@ -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) {
|
||||
}
|
||||
}
|
||||
+67
@@ -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));
|
||||
}
|
||||
}
|
||||
+112
@@ -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);
|
||||
}
|
||||
}
|
||||
+337
@@ -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";
|
||||
}
|
||||
}
|
||||
+64
@@ -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);
|
||||
}
|
||||
}
|
||||
+260
@@ -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);
|
||||
}
|
||||
}
|
||||
+286
@@ -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);
|
||||
|
||||
}
|
||||
+10
@@ -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);
|
||||
}
|
||||
+26
@@ -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;
|
||||
}
|
||||
|
||||
}
|
||||
+42
@@ -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);
|
||||
}
|
||||
+255
@@ -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();
|
||||
}
|
||||
+111
@@ -0,0 +1,111 @@
|
||||
/*
|
||||
* 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 java.io.IOException;
|
||||
|
||||
/**
|
||||
* Activity to record and play back audio.
|
||||
*/
|
||||
public class RecorderActivity extends TestInputActivity {
|
||||
|
||||
private static final int STATE_RECORDING = 5;
|
||||
private static final int STATE_PLAYING = 6;
|
||||
private int mRecorderState = AUDIO_STATE_STOPPED;
|
||||
private Button mRecordButton;
|
||||
private Button mStopButton;
|
||||
private Button mPlayButton;
|
||||
private Button mShareButton;
|
||||
private boolean mGotRecording;
|
||||
|
||||
@Override
|
||||
protected void inflateActivity() {
|
||||
setContentView(R.layout.activity_recorder);
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void onCreate(Bundle savedInstanceState) {
|
||||
super.onCreate(savedInstanceState);
|
||||
|
||||
mRecordButton = (Button) findViewById(R.id.button_start_recording);
|
||||
mStopButton = (Button) findViewById(R.id.button_stop_record_play);
|
||||
mPlayButton = (Button) findViewById(R.id.button_start_playback);
|
||||
mShareButton = (Button) findViewById(R.id.button_share);
|
||||
mRecorderState = AUDIO_STATE_STOPPED;
|
||||
mGotRecording = false;
|
||||
updateButtons();
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void onStart() {
|
||||
super.onStart();
|
||||
setActivityType(ACTIVITY_RECORD_PLAY);
|
||||
}
|
||||
|
||||
public void onStartRecording(View view) {
|
||||
try {
|
||||
openAudio();
|
||||
startAudio();
|
||||
mRecorderState = STATE_RECORDING;
|
||||
mGotRecording = true;
|
||||
updateButtons();
|
||||
} catch (IOException e) {
|
||||
showErrorToast(e.getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
public void onStopRecordPlay(View view) {
|
||||
stopAudio();
|
||||
closeAudio();
|
||||
mRecorderState = AUDIO_STATE_STOPPED;
|
||||
updateButtons();
|
||||
}
|
||||
|
||||
public void onStartPlayback(View view) {
|
||||
startPlayback();
|
||||
mRecorderState = STATE_PLAYING;
|
||||
updateButtons();
|
||||
}
|
||||
|
||||
private void updateButtons() {
|
||||
mRecordButton.setEnabled(mRecorderState == AUDIO_STATE_STOPPED);
|
||||
mStopButton.setEnabled(mRecorderState != AUDIO_STATE_STOPPED);
|
||||
mPlayButton.setEnabled(mRecorderState == AUDIO_STATE_STOPPED && mGotRecording);
|
||||
mShareButton.setEnabled(mRecorderState == AUDIO_STATE_STOPPED && mGotRecording);
|
||||
}
|
||||
|
||||
public void startPlayback() {
|
||||
try {
|
||||
mAudioInputTester.startPlayback();
|
||||
updateStreamConfigurationViews();
|
||||
updateEnabledWidgets();
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
showErrorToast(e.getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
String getWaveTag() {
|
||||
return "recording";
|
||||
}
|
||||
|
||||
}
|
||||
+395
@@ -0,0 +1,395 @@
|
||||
/*
|
||||
* 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.content.Intent;
|
||||
import android.os.Bundle;
|
||||
import android.os.Handler;
|
||||
import android.os.Looper;
|
||||
import android.support.annotation.NonNull;
|
||||
import android.view.View;
|
||||
import android.widget.Button;
|
||||
import android.widget.TextView;
|
||||
|
||||
import java.io.IOException;
|
||||
|
||||
/**
|
||||
* Activity to measure latency on a full duplex stream.
|
||||
*/
|
||||
public class RoundTripLatencyActivity extends AnalyzerActivity {
|
||||
|
||||
private static final int STATE_GOT_DATA = 2; // Defined in LatencyAnalyzer.h
|
||||
private final static String LATENCY_FORMAT = "%4.2f";
|
||||
private final static String CONFIDENCE_FORMAT = "%5.3f";
|
||||
|
||||
private TextView mAnalyzerView;
|
||||
private Button mMeasureButton;
|
||||
private Button mAverageButton;
|
||||
private Button mCancelButton;
|
||||
private Button mShareButton;
|
||||
private boolean mHasRecording = false;
|
||||
|
||||
private boolean mTestRunningByIntent;
|
||||
private Bundle mBundleFromIntent;
|
||||
private int mBufferBursts = -1;
|
||||
private Handler mHandler = new Handler(Looper.getMainLooper()); // UI thread
|
||||
|
||||
// Run the test several times and report the acverage latency.
|
||||
protected class LatencyAverager {
|
||||
private final static int AVERAGE_TEST_DELAY_MSEC = 1000; // arbitrary
|
||||
private static final int AVERAGE_MAX_ITERATIONS = 10; // arbitrary
|
||||
private int mCount = 0;
|
||||
|
||||
private double mWeightedLatencySum;
|
||||
private double mLatencyMin;
|
||||
private double mLatencyMax;
|
||||
private double mConfidenceSum;
|
||||
private boolean mActive;
|
||||
private String mLastReport = "";
|
||||
|
||||
// Called on UI thread.
|
||||
String onAnalyserDone() {
|
||||
String message;
|
||||
if (!mActive) {
|
||||
message = "";
|
||||
} else if (getMeasuredResult() != 0) {
|
||||
cancel();
|
||||
updateButtons(false);
|
||||
message = "averaging cancelled due to error\n";
|
||||
} else {
|
||||
mCount++;
|
||||
double latency = getMeasuredLatencyMillis();
|
||||
double confidence = getMeasuredConfidence();
|
||||
mWeightedLatencySum += latency * confidence; // weighted average based on confidence
|
||||
mConfidenceSum += confidence;
|
||||
mLatencyMin = Math.min(mLatencyMin, latency);
|
||||
mLatencyMax = Math.max(mLatencyMax, latency);
|
||||
if (mCount < AVERAGE_MAX_ITERATIONS) {
|
||||
mHandler.postDelayed(new Runnable() {
|
||||
@Override
|
||||
public void run() {
|
||||
measureSingleLatency();
|
||||
}
|
||||
}, AVERAGE_TEST_DELAY_MSEC);
|
||||
} else {
|
||||
mActive = false;
|
||||
updateButtons(false);
|
||||
}
|
||||
message = reportAverage();
|
||||
}
|
||||
return message;
|
||||
}
|
||||
|
||||
private String reportAverage() {
|
||||
String message;
|
||||
if (mCount == 0 || mConfidenceSum == 0.0) {
|
||||
message = "num.iterations = " + mCount + "\n";
|
||||
} else {
|
||||
// When I use 5.3g I only get one digit after the decimal point!
|
||||
final double averageLatency = mWeightedLatencySum / mConfidenceSum;
|
||||
final double mAverageConfidence = mConfidenceSum / mCount;
|
||||
message =
|
||||
"average.latency.msec = " + String.format(LATENCY_FORMAT, averageLatency) + "\n"
|
||||
+ "average.confidence = " + String.format(CONFIDENCE_FORMAT, mAverageConfidence) + "\n"
|
||||
+ "min.latency.msec = " + String.format(LATENCY_FORMAT, mLatencyMin) + "\n"
|
||||
+ "max.latency.msec = " + String.format(LATENCY_FORMAT, mLatencyMax) + "\n"
|
||||
+ "num.iterations = " + mCount + "\n";
|
||||
}
|
||||
mLastReport = message;
|
||||
return message;
|
||||
}
|
||||
|
||||
// Called on UI thread.
|
||||
public void start() {
|
||||
mWeightedLatencySum = 0.0;
|
||||
mConfidenceSum = 0.0;
|
||||
mLatencyMax = Double.MIN_VALUE;
|
||||
mLatencyMin = Double.MAX_VALUE;
|
||||
mCount = 0;
|
||||
mActive = true;
|
||||
mLastReport = "";
|
||||
measureSingleLatency();
|
||||
}
|
||||
|
||||
public void clear() {
|
||||
mActive = false;
|
||||
mLastReport = "";
|
||||
}
|
||||
|
||||
public void cancel() {
|
||||
mActive = false;
|
||||
}
|
||||
|
||||
public boolean isActive() {
|
||||
return mActive;
|
||||
}
|
||||
|
||||
public String getLastReport() {
|
||||
return mLastReport;
|
||||
}
|
||||
}
|
||||
LatencyAverager mLatencyAverager = new LatencyAverager();
|
||||
|
||||
// Periodically query the status of the stream.
|
||||
protected class LatencySniffer {
|
||||
private int counter = 0;
|
||||
public static final int SNIFFER_UPDATE_PERIOD_MSEC = 150;
|
||||
public static final int SNIFFER_UPDATE_DELAY_MSEC = 300;
|
||||
|
||||
|
||||
// Display status info for the stream.
|
||||
private Runnable runnableCode = new Runnable() {
|
||||
@Override
|
||||
public void run() {
|
||||
String message;
|
||||
|
||||
if (isAnalyzerDone()) {
|
||||
message = onAnalyzerDone();
|
||||
message += mLatencyAverager.onAnalyserDone();
|
||||
} else {
|
||||
message = getProgressText();
|
||||
message += "please wait... " + counter + "\n";
|
||||
if (getAnalyzerState() == STATE_GOT_DATA) {
|
||||
message += "ANALYZING\n";
|
||||
}
|
||||
// Repeat this runnable code block again.
|
||||
mHandler.postDelayed(runnableCode, SNIFFER_UPDATE_PERIOD_MSEC);
|
||||
}
|
||||
setAnalyzerText(message);
|
||||
counter++;
|
||||
}
|
||||
};
|
||||
|
||||
private void startSniffer() {
|
||||
counter = 0;
|
||||
// Start the initial runnable task by posting through the handler
|
||||
mHandler.postDelayed(runnableCode, SNIFFER_UPDATE_DELAY_MSEC);
|
||||
}
|
||||
|
||||
private void stopSniffer() {
|
||||
if (mHandler != null) {
|
||||
mHandler.removeCallbacks(runnableCode);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private String getProgressText() {
|
||||
int progress = getAnalyzerProgress();
|
||||
int state = getAnalyzerState();
|
||||
int resetCount = getResetCount();
|
||||
String message = String.format("progress = %d, state = %d, #resets = %d\n",
|
||||
progress, state, resetCount);
|
||||
message += mLatencyAverager.getLastReport();
|
||||
return message;
|
||||
}
|
||||
|
||||
private String onAnalyzerDone() {
|
||||
String message = getResultString();
|
||||
if (mTestRunningByIntent) {
|
||||
String report = getCommonTestReport();
|
||||
report += message;
|
||||
maybeWriteTestResult(report);
|
||||
}
|
||||
mTestRunningByIntent = false;
|
||||
mHasRecording = true;
|
||||
stopAudioTest();
|
||||
return message;
|
||||
}
|
||||
|
||||
@NonNull
|
||||
private String getResultString() {
|
||||
String message = String.format("rms.signal = %7.5f\n", getSignalRMS());
|
||||
message += String.format("rms.noise = %7.5f\n", getBackgroundRMS());
|
||||
int resetCount = getResetCount();
|
||||
message += String.format("reset.count = %d\n", resetCount);
|
||||
|
||||
int result = getMeasuredResult();
|
||||
message += String.format("result = %d\n", result);
|
||||
message += String.format("result.text = %s\n", resultCodeToString(result));
|
||||
|
||||
// Only report valid latencies.
|
||||
if (result == 0) {
|
||||
int latencyFrames = getMeasuredLatency();
|
||||
double latencyMillis = getMeasuredLatencyMillis();
|
||||
int bufferSize = mAudioOutTester.getCurrentAudioStream().getBufferSizeInFrames();
|
||||
int latencyEmptyFrames = latencyFrames - bufferSize;
|
||||
double latencyEmptyMillis = latencyEmptyFrames * 1000.0 / getSampleRate();
|
||||
message += String.format("latency.empty.frames = %d\n", latencyEmptyFrames);
|
||||
message += String.format("latency.empty.msec = " + LATENCY_FORMAT + "\n", latencyEmptyMillis);
|
||||
message += String.format("latency.frames = %d\n", latencyFrames);
|
||||
message += String.format("latency.msec = " + LATENCY_FORMAT + "\n", latencyMillis);
|
||||
}
|
||||
double confidence = getMeasuredConfidence();
|
||||
message += String.format("confidence = " + CONFIDENCE_FORMAT + "\n", confidence);
|
||||
return message;
|
||||
}
|
||||
|
||||
private LatencySniffer mLatencySniffer = new LatencySniffer();
|
||||
|
||||
native int getAnalyzerProgress();
|
||||
native int getMeasuredLatency();
|
||||
double getMeasuredLatencyMillis() {
|
||||
return getMeasuredLatency() * 1000.0 / getSampleRate();
|
||||
}
|
||||
native double getMeasuredConfidence();
|
||||
native double getBackgroundRMS();
|
||||
native double getSignalRMS();
|
||||
|
||||
private void setAnalyzerText(String s) {
|
||||
mAnalyzerView.setText(s);
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void inflateActivity() {
|
||||
setContentView(R.layout.activity_rt_latency);
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void onCreate(Bundle savedInstanceState) {
|
||||
super.onCreate(savedInstanceState);
|
||||
mMeasureButton = (Button) findViewById(R.id.button_measure);
|
||||
mAverageButton = (Button) findViewById(R.id.button_average);
|
||||
mCancelButton = (Button) findViewById(R.id.button_cancel);
|
||||
mShareButton = (Button) findViewById(R.id.button_share);
|
||||
mShareButton.setEnabled(false);
|
||||
mAnalyzerView = (TextView) findViewById(R.id.text_status);
|
||||
updateEnabledWidgets();
|
||||
|
||||
hideSettingsViews();
|
||||
|
||||
mBufferSizeView.setFaderNormalizedProgress(0.0); // for lowest latency
|
||||
|
||||
mBundleFromIntent = getIntent().getExtras();
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onNewIntent(Intent intent) {
|
||||
mBundleFromIntent = intent.getExtras();
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void onStart() {
|
||||
super.onStart();
|
||||
setActivityType(ACTIVITY_RT_LATENCY);
|
||||
mHasRecording = false;
|
||||
updateButtons(false);
|
||||
}
|
||||
|
||||
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);
|
||||
getFirstInputStreamContext().configurationView.setExclusiveMode(true);
|
||||
getFirstOutputStreamContext().configurationView.setExclusiveMode(true);
|
||||
mBufferBursts = mBundleFromIntent.getInt(KEY_BUFFER_BURSTS, mBufferBursts);
|
||||
|
||||
// Delay the test start to avoid race conditions.
|
||||
Handler handler = new Handler(Looper.getMainLooper()); // UI thread
|
||||
handler.postDelayed(new Runnable() {
|
||||
@Override
|
||||
public void run() {
|
||||
onMeasure(null);
|
||||
}
|
||||
}, 500); // TODO where is the race, close->open?
|
||||
|
||||
}
|
||||
mBundleFromIntent = null;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onResume(){
|
||||
super.onResume();
|
||||
processBundleFromIntent();
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void onStop() {
|
||||
mLatencySniffer.stopSniffer();
|
||||
super.onStop();
|
||||
}
|
||||
|
||||
public void onMeasure(View view) {
|
||||
mLatencyAverager.clear();
|
||||
measureSingleLatency();
|
||||
}
|
||||
|
||||
void updateButtons(boolean running) {
|
||||
boolean busy = running || mLatencyAverager.isActive();
|
||||
mMeasureButton.setEnabled(!busy);
|
||||
mAverageButton.setEnabled(!busy);
|
||||
mCancelButton.setEnabled(running);
|
||||
mShareButton.setEnabled(!busy && mHasRecording);
|
||||
}
|
||||
|
||||
private void measureSingleLatency() {
|
||||
try {
|
||||
openAudio();
|
||||
if (mBufferBursts >= 0) {
|
||||
AudioStreamBase stream = mAudioOutTester.getCurrentAudioStream();
|
||||
int framesPerBurst = stream.getFramesPerBurst();
|
||||
stream.setBufferSizeInFrames(framesPerBurst * mBufferBursts);
|
||||
// override buffer size fader
|
||||
mBufferSizeView.setEnabled(false);
|
||||
mBufferBursts = -1;
|
||||
}
|
||||
startAudio();
|
||||
mLatencySniffer.startSniffer();
|
||||
updateButtons(true);
|
||||
} catch (IOException e) {
|
||||
showErrorToast(e.getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
public void onAverage(View view) {
|
||||
mLatencyAverager.start();
|
||||
}
|
||||
|
||||
public void onCancel(View view) {
|
||||
mLatencyAverager.cancel();
|
||||
stopAudioTest();
|
||||
}
|
||||
|
||||
// Call on UI thread
|
||||
public void stopAudioTest() {
|
||||
mLatencySniffer.stopSniffer();
|
||||
stopAudio();
|
||||
closeAudio();
|
||||
updateButtons(false);
|
||||
}
|
||||
|
||||
@Override
|
||||
String getWaveTag() {
|
||||
return "rtlatency";
|
||||
}
|
||||
|
||||
@Override
|
||||
boolean isOutput() {
|
||||
return false;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void setupEffects(int sessionId) {
|
||||
}
|
||||
}
|
||||
+355
@@ -0,0 +1,355 @@
|
||||
/*
|
||||
* 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;
|
||||
|
||||
/**
|
||||
* Container for the properties of a Stream.
|
||||
*
|
||||
* This can be used to build a stream, or as a base class for a Stream,
|
||||
* or as a way to report the properties of a Stream.
|
||||
*/
|
||||
|
||||
public class StreamConfiguration {
|
||||
public static final int UNSPECIFIED = 0;
|
||||
|
||||
// These must match order in Spinner and in native code and in AAudio.h
|
||||
public static final int NATIVE_API_UNSPECIFIED = 0;
|
||||
public static final int NATIVE_API_OPENSLES = 1;
|
||||
public static final int NATIVE_API_AAUDIO = 2;
|
||||
|
||||
public static final int SHARING_MODE_EXCLUSIVE = 0; // must match AAUDIO
|
||||
public static final int SHARING_MODE_SHARED = 1; // must match AAUDIO
|
||||
|
||||
public static final int AUDIO_FORMAT_PCM_16 = 1; // must match AAUDIO
|
||||
public static final int AUDIO_FORMAT_PCM_FLOAT = 2; // must match AAUDIO
|
||||
|
||||
public static final int DIRECTION_OUTPUT = 0; // must match AAUDIO
|
||||
public static final int DIRECTION_INPUT = 1; // must match AAUDIO
|
||||
|
||||
public static final int SESSION_ID_NONE = -1; // must match AAUDIO
|
||||
public static final int SESSION_ID_ALLOCATE = 0; // must match AAUDIO
|
||||
|
||||
public static final int PERFORMANCE_MODE_NONE = 10; // must match AAUDIO
|
||||
public static final int PERFORMANCE_MODE_POWER_SAVING = 11; // must match AAUDIO
|
||||
public static final int PERFORMANCE_MODE_LOW_LATENCY = 12; // must match AAUDIO
|
||||
|
||||
public static final int RATE_CONVERSION_QUALITY_NONE = 0; // must match Oboe
|
||||
public static final int RATE_CONVERSION_QUALITY_FASTEST = 1; // must match Oboe
|
||||
public static final int RATE_CONVERSION_QUALITY_LOW = 2; // must match Oboe
|
||||
public static final int RATE_CONVERSION_QUALITY_MEDIUM = 3; // must match Oboe
|
||||
public static final int RATE_CONVERSION_QUALITY_HIGH = 4; // must match Oboe
|
||||
public static final int RATE_CONVERSION_QUALITY_BEST = 5; // must match Oboe
|
||||
|
||||
public static final int STREAM_STATE_STARTING = 3; // must match Oboe
|
||||
public static final int STREAM_STATE_STARTED = 4; // must match Oboe
|
||||
|
||||
public static final int INPUT_PRESET_GENERIC = 1; // must match Oboe
|
||||
public static final int INPUT_PRESET_CAMCORDER = 5; // must match Oboe
|
||||
public static final int INPUT_PRESET_VOICE_RECOGNITION = 6; // must match Oboe
|
||||
public static final int INPUT_PRESET_VOICE_COMMUNICATION = 7; // must match Oboe
|
||||
public static final int INPUT_PRESET_UNPROCESSED = 9; // must match Oboe
|
||||
public static final int INPUT_PRESET_VOICE_PERFORMANCE = 10; // must match Oboe
|
||||
|
||||
private int mNativeApi;
|
||||
private int mBufferCapacityInFrames;
|
||||
private int mChannelCount;
|
||||
private int mDeviceId;
|
||||
private int mSessionId;
|
||||
private int mDirection; // does not get reset
|
||||
private int mFormat;
|
||||
private int mSampleRate;
|
||||
private int mSharingMode;
|
||||
private int mPerformanceMode;
|
||||
private boolean mFormatConversionAllowed;
|
||||
private boolean mChannelConversionAllowed;
|
||||
private int mRateConversionQuality;
|
||||
private int mInputPreset;
|
||||
|
||||
private int mFramesPerBurst = 0;
|
||||
|
||||
private boolean mMMap = false;
|
||||
|
||||
public StreamConfiguration() {
|
||||
reset();
|
||||
}
|
||||
|
||||
public void reset() {
|
||||
mNativeApi = NATIVE_API_UNSPECIFIED;
|
||||
mBufferCapacityInFrames = UNSPECIFIED;
|
||||
mChannelCount = UNSPECIFIED;
|
||||
mDeviceId = UNSPECIFIED;
|
||||
mSessionId = -1;
|
||||
mFormat = AUDIO_FORMAT_PCM_FLOAT;
|
||||
mSampleRate = UNSPECIFIED;
|
||||
mSharingMode = SHARING_MODE_EXCLUSIVE;
|
||||
mPerformanceMode = PERFORMANCE_MODE_LOW_LATENCY;
|
||||
mInputPreset = INPUT_PRESET_VOICE_RECOGNITION;
|
||||
mFormatConversionAllowed = false;
|
||||
mChannelConversionAllowed = false;
|
||||
mRateConversionQuality = RATE_CONVERSION_QUALITY_NONE;
|
||||
mMMap = NativeEngine.isMMapSupported();
|
||||
}
|
||||
|
||||
public int getFramesPerBurst() {
|
||||
return mFramesPerBurst;
|
||||
}
|
||||
|
||||
public void setFramesPerBurst(int framesPerBurst) {
|
||||
this.mFramesPerBurst = framesPerBurst;
|
||||
}
|
||||
|
||||
public int getBufferCapacityInFrames() {
|
||||
return mBufferCapacityInFrames;
|
||||
}
|
||||
|
||||
public void setBufferCapacityInFrames(int bufferCapacityInFrames) {
|
||||
this.mBufferCapacityInFrames = bufferCapacityInFrames;
|
||||
}
|
||||
|
||||
public int getFormat() {
|
||||
return mFormat;
|
||||
}
|
||||
|
||||
public void setFormat(int format) {
|
||||
this.mFormat = format;
|
||||
}
|
||||
|
||||
public int getDirection() {
|
||||
return mDirection;
|
||||
}
|
||||
|
||||
public void setDirection(int direction) {
|
||||
this.mDirection = direction;
|
||||
}
|
||||
|
||||
public int getPerformanceMode() {
|
||||
return mPerformanceMode;
|
||||
}
|
||||
|
||||
public void setPerformanceMode(int performanceMode) {
|
||||
this.mPerformanceMode = performanceMode;
|
||||
}
|
||||
|
||||
public int getInputPreset() {
|
||||
return mInputPreset;
|
||||
}
|
||||
public void setInputPreset(int inputPreset) {
|
||||
this.mInputPreset = inputPreset;
|
||||
}
|
||||
|
||||
static String convertPerformanceModeToText(int performanceMode) {
|
||||
switch(performanceMode) {
|
||||
case PERFORMANCE_MODE_NONE:
|
||||
return "NONE";
|
||||
case PERFORMANCE_MODE_POWER_SAVING:
|
||||
return "PWRSAV";
|
||||
case PERFORMANCE_MODE_LOW_LATENCY:
|
||||
return "LOWLAT";
|
||||
default:
|
||||
return "INVALID";
|
||||
}
|
||||
}
|
||||
|
||||
public int getSharingMode() {
|
||||
return mSharingMode;
|
||||
}
|
||||
|
||||
public void setSharingMode(int sharingMode) {
|
||||
this.mSharingMode = sharingMode;
|
||||
}
|
||||
|
||||
static String convertSharingModeToText(int sharingMode) {
|
||||
switch(sharingMode) {
|
||||
case SHARING_MODE_SHARED:
|
||||
return "SHARED";
|
||||
case SHARING_MODE_EXCLUSIVE:
|
||||
return "EXCLUSIVE";
|
||||
default:
|
||||
return "INVALID";
|
||||
}
|
||||
}
|
||||
|
||||
public static String convertFormatToText(int format) {
|
||||
switch(format) {
|
||||
case UNSPECIFIED:
|
||||
return "Unspecified";
|
||||
case AUDIO_FORMAT_PCM_16:
|
||||
return "I16";
|
||||
case AUDIO_FORMAT_PCM_FLOAT:
|
||||
return "Float";
|
||||
default:
|
||||
return "Invalid";
|
||||
}
|
||||
}
|
||||
|
||||
public static String convertNativeApiToText(int api) {
|
||||
switch(api) {
|
||||
case NATIVE_API_UNSPECIFIED:
|
||||
return "Unspec";
|
||||
case NATIVE_API_AAUDIO:
|
||||
return "AAudio";
|
||||
case NATIVE_API_OPENSLES:
|
||||
return "OpenSL";
|
||||
default:
|
||||
return "Invalid";
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
public String dump() {
|
||||
String prefix = (getDirection() == DIRECTION_INPUT) ? "in" : "out";
|
||||
StringBuffer message = new StringBuffer();
|
||||
message.append(String.format("%s.channels = %d\n", prefix, mChannelCount));
|
||||
message.append(String.format("%s.perf = %s\n", prefix,
|
||||
convertPerformanceModeToText(mPerformanceMode).toLowerCase()));
|
||||
if (getDirection() == DIRECTION_INPUT) {
|
||||
message.append(String.format("%s.preset = %s\n", prefix,
|
||||
convertInputPresetToText(mInputPreset).toLowerCase()));
|
||||
}
|
||||
message.append(String.format("%s.sharing = %s\n", prefix,
|
||||
convertSharingModeToText(mSharingMode).toLowerCase()));
|
||||
message.append(String.format("%s.api = %s\n", prefix,
|
||||
convertNativeApiToText(getNativeApi()).toLowerCase()));
|
||||
message.append(String.format("%s.rate = %d\n", prefix, mSampleRate));
|
||||
message.append(String.format("%s.device = %d\n", prefix, mDeviceId));
|
||||
message.append(String.format("%s.mmap = %s\n", prefix, isMMap() ? "yes" : "no"));
|
||||
message.append(String.format("%s.rate.conversion.quality = %d\n", prefix, mRateConversionQuality));
|
||||
return message.toString();
|
||||
}
|
||||
|
||||
// text must match menu values
|
||||
public static final String NAME_INPUT_PRESET_GENERIC = "Generic";
|
||||
public static final String NAME_INPUT_PRESET_CAMCORDER = "Camcorder";
|
||||
public static final String NAME_INPUT_PRESET_VOICE_RECOGNITION = "VoiceRec";
|
||||
public static final String NAME_INPUT_PRESET_VOICE_COMMUNICATION = "VoiceComm";
|
||||
public static final String NAME_INPUT_PRESET_UNPROCESSED = "Unprocessed";
|
||||
public static final String NAME_INPUT_PRESET_VOICE_PERFORMANCE = "Performance";
|
||||
|
||||
public static String convertInputPresetToText(int inputPreset) {
|
||||
switch(inputPreset) {
|
||||
case INPUT_PRESET_GENERIC:
|
||||
return NAME_INPUT_PRESET_GENERIC;
|
||||
case INPUT_PRESET_CAMCORDER:
|
||||
return NAME_INPUT_PRESET_CAMCORDER;
|
||||
case INPUT_PRESET_VOICE_RECOGNITION:
|
||||
return NAME_INPUT_PRESET_VOICE_RECOGNITION;
|
||||
case INPUT_PRESET_VOICE_COMMUNICATION:
|
||||
return NAME_INPUT_PRESET_VOICE_COMMUNICATION;
|
||||
case INPUT_PRESET_UNPROCESSED:
|
||||
return NAME_INPUT_PRESET_UNPROCESSED;
|
||||
case INPUT_PRESET_VOICE_PERFORMANCE:
|
||||
return NAME_INPUT_PRESET_VOICE_PERFORMANCE;
|
||||
default:
|
||||
return "Invalid";
|
||||
}
|
||||
}
|
||||
|
||||
private static boolean matchInputPreset(String text, int preset) {
|
||||
return convertInputPresetToText(preset).toLowerCase().equals(text);
|
||||
}
|
||||
|
||||
/**
|
||||
* Case insensitive.
|
||||
* @param text
|
||||
* @return inputPreset, eg. INPUT_PRESET_CAMCORDER
|
||||
*/
|
||||
public static int convertTextToInputPreset(String text) {
|
||||
text = text.toLowerCase();
|
||||
if (matchInputPreset(text, INPUT_PRESET_GENERIC)) {
|
||||
return INPUT_PRESET_GENERIC;
|
||||
} else if (matchInputPreset(text, INPUT_PRESET_CAMCORDER)) {
|
||||
return INPUT_PRESET_CAMCORDER;
|
||||
} else if (matchInputPreset(text, INPUT_PRESET_VOICE_RECOGNITION)) {
|
||||
return INPUT_PRESET_VOICE_RECOGNITION;
|
||||
} else if (matchInputPreset(text, INPUT_PRESET_VOICE_COMMUNICATION)) {
|
||||
return INPUT_PRESET_VOICE_COMMUNICATION;
|
||||
} else if (matchInputPreset(text, INPUT_PRESET_UNPROCESSED)) {
|
||||
return INPUT_PRESET_UNPROCESSED;
|
||||
} else if (matchInputPreset(text, INPUT_PRESET_VOICE_PERFORMANCE)) {
|
||||
return INPUT_PRESET_VOICE_PERFORMANCE;
|
||||
}
|
||||
return -1;
|
||||
}
|
||||
|
||||
public int getChannelCount() {
|
||||
return mChannelCount;
|
||||
}
|
||||
|
||||
public void setChannelCount(int channelCount) {
|
||||
this.mChannelCount = channelCount;
|
||||
}
|
||||
|
||||
public int getSampleRate() {
|
||||
return mSampleRate;
|
||||
}
|
||||
|
||||
public void setSampleRate(int sampleRate) {
|
||||
this.mSampleRate = sampleRate;
|
||||
}
|
||||
|
||||
public int getDeviceId() {
|
||||
return mDeviceId;
|
||||
}
|
||||
|
||||
public void setDeviceId(int deviceId) {
|
||||
this.mDeviceId = deviceId;
|
||||
}
|
||||
|
||||
public int getSessionId() {
|
||||
return mSessionId;
|
||||
}
|
||||
|
||||
public void setSessionId(int sessionId) {
|
||||
mSessionId = sessionId;
|
||||
}
|
||||
|
||||
public boolean isMMap() {
|
||||
return mMMap;
|
||||
}
|
||||
public void setMMap(boolean b) {
|
||||
mMMap = b;
|
||||
}
|
||||
|
||||
public int getNativeApi() {
|
||||
return mNativeApi;
|
||||
}
|
||||
|
||||
public void setNativeApi(int nativeApi) {
|
||||
mNativeApi = nativeApi;
|
||||
}
|
||||
|
||||
public void setChannelConversionAllowed(boolean b) { mChannelConversionAllowed = b; }
|
||||
|
||||
public boolean getChannelConversionAllowed() {
|
||||
return mChannelConversionAllowed;
|
||||
}
|
||||
|
||||
public void setFormatConversionAllowed(boolean b) {
|
||||
mFormatConversionAllowed = b;
|
||||
}
|
||||
|
||||
public boolean getFormatConversionAllowed() {
|
||||
return mFormatConversionAllowed;
|
||||
}
|
||||
|
||||
public void setRateConversionQuality(int quality) { mRateConversionQuality = quality; }
|
||||
|
||||
public int getRateConversionQuality() {
|
||||
return mRateConversionQuality;
|
||||
}
|
||||
|
||||
}
|
||||
+464
@@ -0,0 +1,464 @@
|
||||
/*
|
||||
* 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.content.Context;
|
||||
import android.media.AudioManager;
|
||||
import android.util.AttributeSet;
|
||||
import android.view.LayoutInflater;
|
||||
import android.view.View;
|
||||
import android.widget.AdapterView;
|
||||
import android.widget.CheckBox;
|
||||
import android.widget.Spinner;
|
||||
import android.widget.TableLayout;
|
||||
import android.widget.TableRow;
|
||||
import android.widget.TextView;
|
||||
import android.widget.LinearLayout;
|
||||
|
||||
import com.google.sample.audio_device.AudioDeviceListEntry;
|
||||
import com.google.sample.audio_device.AudioDeviceSpinner;
|
||||
|
||||
import java.text.BreakIterator;
|
||||
|
||||
/**
|
||||
* View for Editing a requested StreamConfiguration
|
||||
* and displaying the actual StreamConfiguration.
|
||||
*/
|
||||
|
||||
public class StreamConfigurationView extends LinearLayout {
|
||||
|
||||
private StreamConfiguration mRequestedConfiguration;
|
||||
private StreamConfiguration mActualConfiguration;
|
||||
|
||||
protected Spinner mNativeApiSpinner;
|
||||
private TextView mActualNativeApiView;
|
||||
|
||||
private TextView mActualMMapView;
|
||||
private CheckBox mRequestedMMapView;
|
||||
private TextView mActualExclusiveView;
|
||||
private TextView mActualPerformanceView;
|
||||
private Spinner mPerformanceSpinner;
|
||||
private CheckBox mRequestedExclusiveView;
|
||||
private CheckBox mChannelConversionBox;
|
||||
private CheckBox mFormatConversionBox;
|
||||
private Spinner mChannelCountSpinner;
|
||||
private TextView mActualChannelCountView;
|
||||
private TextView mActualFormatView;
|
||||
|
||||
private TextView mActualInputPresetView;
|
||||
private Spinner mInputPresetSpinner;
|
||||
private TableRow mInputPresetTableRow;
|
||||
private Spinner mFormatSpinner;
|
||||
private Spinner mSampleRateSpinner;
|
||||
private Spinner mRateConversionQualitySpinner;
|
||||
private TextView mActualSampleRateView;
|
||||
private LinearLayout mHideableView;
|
||||
|
||||
private AudioDeviceSpinner mDeviceSpinner;
|
||||
private TextView mActualSessionIdView;
|
||||
private CheckBox mRequestAudioEffect;
|
||||
|
||||
private TextView mStreamInfoView;
|
||||
private TextView mStreamStatusView;
|
||||
private TextView mOptionExpander;
|
||||
private String mHideSettingsText;
|
||||
private String mShowSettingsText;
|
||||
|
||||
// Create an anonymous implementation of OnClickListener
|
||||
private View.OnClickListener mToggleListener = new View.OnClickListener() {
|
||||
public void onClick(View v) {
|
||||
if (mHideableView.isShown()) {
|
||||
hideSettingsView();
|
||||
} else {
|
||||
showSettingsView();
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
public static String yesOrNo(boolean b) {
|
||||
return b ? "YES" : "NO";
|
||||
}
|
||||
|
||||
private void updateSettingsViewText() {
|
||||
if (mHideableView.isShown()) {
|
||||
mOptionExpander.setText(mHideSettingsText);
|
||||
} else {
|
||||
mOptionExpander.setText(mShowSettingsText);
|
||||
}
|
||||
}
|
||||
|
||||
public void showSettingsView() {
|
||||
mHideableView.setVisibility(View.VISIBLE);
|
||||
updateSettingsViewText();
|
||||
}
|
||||
|
||||
public void hideSampleRateMenu() {
|
||||
if (mSampleRateSpinner != null) {
|
||||
mSampleRateSpinner.setVisibility(View.GONE);
|
||||
}
|
||||
}
|
||||
|
||||
public void hideSettingsView() {
|
||||
mHideableView.setVisibility(View.GONE);
|
||||
updateSettingsViewText();
|
||||
}
|
||||
|
||||
public StreamConfigurationView(Context context) {
|
||||
super(context);
|
||||
initializeViews(context);
|
||||
}
|
||||
|
||||
public StreamConfigurationView(Context context, AttributeSet attrs) {
|
||||
super(context, attrs);
|
||||
initializeViews(context);
|
||||
}
|
||||
|
||||
public StreamConfigurationView(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.stream_config, this);
|
||||
|
||||
mHideSettingsText = getResources().getString(R.string.hint_hide_settings);
|
||||
mShowSettingsText = getResources().getString(R.string.hint_show_settings);
|
||||
|
||||
mHideableView = (LinearLayout) findViewById(R.id.hideableView);
|
||||
|
||||
mOptionExpander = (TextView) findViewById(R.id.toggle_stream_config);
|
||||
mOptionExpander.setOnClickListener(mToggleListener);
|
||||
|
||||
mNativeApiSpinner = (Spinner) findViewById(R.id.spinnerNativeApi);
|
||||
mNativeApiSpinner.setOnItemSelectedListener(new NativeApiSpinnerListener());
|
||||
mNativeApiSpinner.setSelection(StreamConfiguration.NATIVE_API_UNSPECIFIED);
|
||||
|
||||
mActualNativeApiView = (TextView) findViewById(R.id.actualNativeApi);
|
||||
|
||||
mChannelConversionBox = (CheckBox) findViewById(R.id.checkChannelConversion);
|
||||
mChannelConversionBox.setOnClickListener(new View.OnClickListener() {
|
||||
@Override
|
||||
public void onClick(View v) {
|
||||
mRequestedConfiguration.setChannelConversionAllowed(mChannelConversionBox.isChecked());
|
||||
}
|
||||
});
|
||||
|
||||
mFormatConversionBox = (CheckBox) findViewById(R.id.checkFormatConversion);
|
||||
mFormatConversionBox.setOnClickListener(new View.OnClickListener() {
|
||||
@Override
|
||||
public void onClick(View v) {
|
||||
mRequestedConfiguration.setFormatConversionAllowed(mFormatConversionBox.isChecked());
|
||||
}
|
||||
});
|
||||
|
||||
mActualMMapView = (TextView) findViewById(R.id.actualMMap);
|
||||
mRequestedMMapView = (CheckBox) findViewById(R.id.requestedMMapEnable);
|
||||
mRequestedMMapView.setOnClickListener(new View.OnClickListener() {
|
||||
@Override
|
||||
public void onClick(View v) {
|
||||
mRequestedConfiguration.setMMap(mRequestedMMapView.isChecked());
|
||||
}
|
||||
});
|
||||
boolean mmapSupported = NativeEngine.isMMapSupported();
|
||||
mRequestedMMapView.setEnabled(mmapSupported);
|
||||
mRequestedMMapView.setChecked(mmapSupported);
|
||||
|
||||
mActualExclusiveView = (TextView) findViewById(R.id.actualExclusiveMode);
|
||||
mRequestedExclusiveView = (CheckBox) findViewById(R.id.requestedExclusiveMode);
|
||||
mRequestedExclusiveView.setOnClickListener(new View.OnClickListener() {
|
||||
@Override
|
||||
public void onClick(View v) {
|
||||
mRequestedConfiguration.setSharingMode(mRequestedExclusiveView.isChecked()
|
||||
? StreamConfiguration.SHARING_MODE_EXCLUSIVE
|
||||
: StreamConfiguration.SHARING_MODE_SHARED);
|
||||
}
|
||||
});
|
||||
|
||||
boolean mmapExclusiveSupported = NativeEngine.isMMapExclusiveSupported();
|
||||
mRequestedExclusiveView.setEnabled(mmapExclusiveSupported);
|
||||
mRequestedExclusiveView.setChecked(mmapExclusiveSupported);
|
||||
|
||||
mActualSessionIdView = (TextView) findViewById(R.id.sessionId);
|
||||
mRequestAudioEffect = (CheckBox) findViewById(R.id.requestAudioEffect);
|
||||
mRequestAudioEffect.setOnClickListener(new View.OnClickListener() {
|
||||
@Override
|
||||
public void onClick(View v) {
|
||||
mRequestedConfiguration.setSessionId(mRequestAudioEffect.isChecked()
|
||||
? StreamConfiguration.SESSION_ID_ALLOCATE
|
||||
: StreamConfiguration.SESSION_ID_NONE);
|
||||
}
|
||||
});
|
||||
|
||||
mActualSampleRateView = (TextView) findViewById(R.id.actualSampleRate);
|
||||
mSampleRateSpinner = (Spinner) findViewById(R.id.spinnerSampleRate);
|
||||
mSampleRateSpinner.setOnItemSelectedListener(new SampleRateSpinnerListener());
|
||||
|
||||
mActualChannelCountView = (TextView) findViewById(R.id.actualChannelCount);
|
||||
mChannelCountSpinner = (Spinner) findViewById(R.id.spinnerChannelCount);
|
||||
mChannelCountSpinner.setOnItemSelectedListener(new ChannelCountSpinnerListener());
|
||||
|
||||
mActualFormatView = (TextView) findViewById(R.id.actualAudioFormat);
|
||||
mFormatSpinner = (Spinner) findViewById(R.id.spinnerFormat);
|
||||
mFormatSpinner.setOnItemSelectedListener(new FormatSpinnerListener());
|
||||
|
||||
mRateConversionQualitySpinner = (Spinner) findViewById(R.id.spinnerSRCQuality);
|
||||
mRateConversionQualitySpinner.setOnItemSelectedListener(new RateConversionQualitySpinnerListener());
|
||||
|
||||
mActualPerformanceView = (TextView) findViewById(R.id.actualPerformanceMode);
|
||||
mPerformanceSpinner = (Spinner) findViewById(R.id.spinnerPerformanceMode);
|
||||
mPerformanceSpinner.setOnItemSelectedListener(new PerformanceModeSpinnerListener());
|
||||
mPerformanceSpinner.setSelection(StreamConfiguration.PERFORMANCE_MODE_LOW_LATENCY
|
||||
- StreamConfiguration.PERFORMANCE_MODE_NONE);
|
||||
|
||||
mInputPresetTableRow = (TableRow) findViewById(R.id.rowInputPreset);
|
||||
mActualInputPresetView = (TextView) findViewById(R.id.actualInputPreset);
|
||||
mInputPresetSpinner = (Spinner) findViewById(R.id.spinnerInputPreset);
|
||||
mInputPresetSpinner.setOnItemSelectedListener(new InputPresetSpinnerListener());
|
||||
mInputPresetSpinner.setSelection(2); // TODO need better way to select voice recording default
|
||||
|
||||
mStreamInfoView = (TextView) findViewById(R.id.streamInfo);
|
||||
|
||||
mStreamStatusView = (TextView) findViewById(R.id.statusView);
|
||||
|
||||
mDeviceSpinner = (AudioDeviceSpinner) findViewById(R.id.devices_spinner);
|
||||
mDeviceSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
|
||||
@Override
|
||||
public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
|
||||
int id = ((AudioDeviceListEntry) mDeviceSpinner.getSelectedItem()).getId();
|
||||
mRequestedConfiguration.setDeviceId(id);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onNothingSelected(AdapterView<?> adapterView) {
|
||||
mRequestedConfiguration.setDeviceId(StreamConfiguration.UNSPECIFIED);
|
||||
}
|
||||
});
|
||||
|
||||
showSettingsView();
|
||||
}
|
||||
|
||||
public void setOutput(boolean output) {
|
||||
String ioText;
|
||||
if (output) {
|
||||
mDeviceSpinner.setDirectionType(AudioManager.GET_DEVICES_OUTPUTS);
|
||||
ioText = "OUTPUT";
|
||||
} else {
|
||||
mDeviceSpinner.setDirectionType(AudioManager.GET_DEVICES_INPUTS);
|
||||
ioText = "INPUT";
|
||||
}
|
||||
mHideSettingsText = getResources().getString(R.string.hint_hide_settings) + " - " + ioText;
|
||||
mShowSettingsText = getResources().getString(R.string.hint_show_settings) + " - " + ioText;
|
||||
updateSettingsViewText();
|
||||
|
||||
// Don't show InputPresets for output streams.
|
||||
mInputPresetTableRow.setVisibility(output ? View.GONE : View.VISIBLE);
|
||||
}
|
||||
|
||||
private class NativeApiSpinnerListener implements android.widget.AdapterView.OnItemSelectedListener {
|
||||
@Override
|
||||
public void onItemSelected(AdapterView<?> parent, View view, int pos, long id) {
|
||||
mRequestedConfiguration.setNativeApi(pos);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onNothingSelected(AdapterView<?> parent) {
|
||||
mRequestedConfiguration.setNativeApi(StreamConfiguration.NATIVE_API_UNSPECIFIED);
|
||||
}
|
||||
}
|
||||
|
||||
private class PerformanceModeSpinnerListener implements android.widget.AdapterView.OnItemSelectedListener {
|
||||
@Override
|
||||
public void onItemSelected(AdapterView<?> parent, View view, int performanceMode, long id) {
|
||||
mRequestedConfiguration.setPerformanceMode(performanceMode
|
||||
+ StreamConfiguration.PERFORMANCE_MODE_NONE);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onNothingSelected(AdapterView<?> parent) {
|
||||
mRequestedConfiguration.setPerformanceMode(StreamConfiguration.PERFORMANCE_MODE_NONE);
|
||||
}
|
||||
}
|
||||
|
||||
private class ChannelCountSpinnerListener implements android.widget.AdapterView.OnItemSelectedListener {
|
||||
@Override
|
||||
public void onItemSelected(AdapterView<?> parent, View view, int pos, long id) {
|
||||
mRequestedConfiguration.setChannelCount(pos);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onNothingSelected(AdapterView<?> parent) {
|
||||
mRequestedConfiguration.setChannelCount(StreamConfiguration.UNSPECIFIED);
|
||||
}
|
||||
}
|
||||
|
||||
private class SampleRateSpinnerListener implements android.widget.AdapterView.OnItemSelectedListener {
|
||||
@Override
|
||||
public void onItemSelected(AdapterView<?> parent, View view, int pos, long id) {
|
||||
String text = parent.getItemAtPosition(pos).toString();
|
||||
int sampleRate = Integer.parseInt(text);
|
||||
mRequestedConfiguration.setSampleRate(sampleRate);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onNothingSelected(AdapterView<?> parent) {
|
||||
mRequestedConfiguration.setSampleRate(StreamConfiguration.UNSPECIFIED);
|
||||
}
|
||||
}
|
||||
|
||||
private class FormatSpinnerListener implements android.widget.AdapterView.OnItemSelectedListener {
|
||||
@Override
|
||||
public void onItemSelected(AdapterView<?> parent, View view, int pos, long id) {
|
||||
// Menu position matches actual enum value!
|
||||
mRequestedConfiguration.setFormat(pos);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onNothingSelected(AdapterView<?> parent) {
|
||||
mRequestedConfiguration.setFormat(StreamConfiguration.UNSPECIFIED);
|
||||
}
|
||||
}
|
||||
|
||||
private class InputPresetSpinnerListener implements android.widget.AdapterView.OnItemSelectedListener {
|
||||
@Override
|
||||
public void onItemSelected(AdapterView<?> parent, View view, int pos, long id) {
|
||||
String text = parent.getItemAtPosition(pos).toString();
|
||||
int inputPreset = StreamConfiguration.convertTextToInputPreset(text);
|
||||
mRequestedConfiguration.setInputPreset(inputPreset);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onNothingSelected(AdapterView<?> parent) {
|
||||
mRequestedConfiguration.setInputPreset(StreamConfiguration.INPUT_PRESET_GENERIC);
|
||||
}
|
||||
}
|
||||
|
||||
private class RateConversionQualitySpinnerListener
|
||||
implements android.widget.AdapterView.OnItemSelectedListener {
|
||||
@Override
|
||||
public void onItemSelected(AdapterView<?> parent, View view, int pos, long id) {
|
||||
// Menu position matches actual enum value!
|
||||
mRequestedConfiguration.setRateConversionQuality(pos);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onNothingSelected(AdapterView<?> parent) {
|
||||
mRequestedConfiguration.setRateConversionQuality(StreamConfiguration.RATE_CONVERSION_QUALITY_HIGH);
|
||||
}
|
||||
}
|
||||
|
||||
public void setChildrenEnabled(boolean enabled) {
|
||||
mNativeApiSpinner.setEnabled(enabled);
|
||||
mPerformanceSpinner.setEnabled(enabled);
|
||||
mRequestedExclusiveView.setEnabled(enabled);
|
||||
mSampleRateSpinner.setEnabled(enabled);
|
||||
mChannelCountSpinner.setEnabled(enabled);
|
||||
mFormatSpinner.setEnabled(enabled);
|
||||
mDeviceSpinner.setEnabled(enabled);
|
||||
mRequestAudioEffect.setEnabled(enabled);
|
||||
}
|
||||
|
||||
// This must be called on the UI thread.
|
||||
void updateDisplay() {
|
||||
int value;
|
||||
|
||||
value = mActualConfiguration.getNativeApi();
|
||||
mActualNativeApiView.setText(StreamConfiguration.convertNativeApiToText(value));
|
||||
|
||||
mActualMMapView.setText(yesOrNo(mActualConfiguration.isMMap()));
|
||||
int sharingMode = mActualConfiguration.getSharingMode();
|
||||
boolean isExclusive = (sharingMode == StreamConfiguration.SHARING_MODE_EXCLUSIVE);
|
||||
mActualExclusiveView.setText(yesOrNo(isExclusive));
|
||||
|
||||
value = mActualConfiguration.getPerformanceMode();
|
||||
mActualPerformanceView.setText(StreamConfiguration.convertPerformanceModeToText(value));
|
||||
mActualPerformanceView.requestLayout();
|
||||
|
||||
value = mActualConfiguration.getFormat();
|
||||
mActualFormatView.setText(StreamConfiguration.convertFormatToText(value));
|
||||
mActualFormatView.requestLayout();
|
||||
|
||||
value = mActualConfiguration.getInputPreset();
|
||||
mActualInputPresetView.setText(StreamConfiguration.convertInputPresetToText(value));
|
||||
mActualInputPresetView.requestLayout();
|
||||
|
||||
mActualChannelCountView.setText(mActualConfiguration.getChannelCount() + "");
|
||||
mActualSampleRateView.setText(mActualConfiguration.getSampleRate() + "");
|
||||
mActualSessionIdView.setText("S#: " + mActualConfiguration.getSessionId());
|
||||
|
||||
boolean isMMap = mActualConfiguration.isMMap();
|
||||
mStreamInfoView.setText("burst = " + mActualConfiguration.getFramesPerBurst()
|
||||
+ ", capacity = " + mActualConfiguration.getBufferCapacityInFrames()
|
||||
+ ", devID = " + mActualConfiguration.getDeviceId()
|
||||
+ ", " + (mActualConfiguration.isMMap() ? "MMAP" : "Legacy")
|
||||
+ (isMMap ? ", " + StreamConfiguration.convertSharingModeToText(sharingMode) : "")
|
||||
);
|
||||
|
||||
mHideableView.requestLayout();
|
||||
}
|
||||
|
||||
// This must be called on the UI thread.
|
||||
public void setStatusText(String msg) {
|
||||
mStreamStatusView.setText(msg);
|
||||
}
|
||||
|
||||
protected StreamConfiguration getRequestedConfiguration() {
|
||||
return mRequestedConfiguration;
|
||||
}
|
||||
|
||||
public void setRequestedConfiguration(StreamConfiguration configuration) {
|
||||
mRequestedConfiguration = configuration;
|
||||
if (configuration != null) {
|
||||
mRateConversionQualitySpinner.setSelection(configuration.getRateConversionQuality());
|
||||
mChannelConversionBox.setChecked(configuration.getChannelConversionAllowed());
|
||||
mFormatConversionBox.setChecked(configuration.getFormatConversionAllowed());
|
||||
}
|
||||
}
|
||||
|
||||
protected StreamConfiguration getActualConfiguration() {
|
||||
return mActualConfiguration;
|
||||
}
|
||||
public void setActualConfiguration(StreamConfiguration configuration) {
|
||||
mActualConfiguration = configuration;
|
||||
}
|
||||
|
||||
public void setExclusiveMode(boolean b) {
|
||||
mRequestedExclusiveView.setChecked(b);
|
||||
mRequestedConfiguration.setSharingMode(b
|
||||
? StreamConfiguration.SHARING_MODE_EXCLUSIVE
|
||||
: StreamConfiguration.SHARING_MODE_SHARED);
|
||||
}
|
||||
|
||||
public void setFormat(int format) {
|
||||
mFormatSpinner.setSelection(format); // position matches format
|
||||
mRequestedConfiguration.setFormat(format);
|
||||
}
|
||||
|
||||
public void setFormatConversionAllowed(boolean allowed) {
|
||||
mFormatConversionBox.setChecked(allowed);
|
||||
mRequestedConfiguration.setFormatConversionAllowed(allowed);
|
||||
}
|
||||
}
|
||||
+108
@@ -0,0 +1,108 @@
|
||||
/*
|
||||
* 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.util.ArrayList;
|
||||
|
||||
public class TapLatencyAnalyser {
|
||||
public static final int TYPE_TAP = 0;
|
||||
float[] mHighPassBuffer;
|
||||
|
||||
private float mDroop = 0.995f;
|
||||
private static float LOW_THRESHOLD = 0.01f;
|
||||
private static float HIGH_THRESHOLD = 0.03f;
|
||||
|
||||
public static class TapLatencyEvent {
|
||||
public int type;
|
||||
public int sampleIndex;
|
||||
public TapLatencyEvent(int type, int sampleIndex) {
|
||||
this.type = type;
|
||||
this.sampleIndex = sampleIndex;
|
||||
}
|
||||
}
|
||||
|
||||
public TapLatencyEvent[] analyze(float[] buffer, int offset, int numSamples) {
|
||||
// Use high pass filter to remove rumble from air conditioners.
|
||||
mHighPassBuffer = new float[numSamples];
|
||||
highPassFilter(buffer, offset, numSamples, mHighPassBuffer);
|
||||
float[] peakBuffer = new float[numSamples];
|
||||
fillPeakBuffer(mHighPassBuffer, 0, numSamples, peakBuffer);
|
||||
return scanForEdges(peakBuffer, numSamples);
|
||||
}
|
||||
|
||||
public float[] getFilteredBuffer() {
|
||||
return mHighPassBuffer;
|
||||
}
|
||||
|
||||
private void highPassFilter(float[] buffer, int offset, int numSamples, float[] highPassBuffer) {
|
||||
float xn1 = 0.0f;
|
||||
float yn1 = 0.0f;
|
||||
float alpha = 0.05f;
|
||||
for (int i = 0; i < numSamples; i++) {
|
||||
float xn = buffer[i + offset];
|
||||
float yn = alpha * yn1 + ((1.0f - alpha) * (xn - xn1));
|
||||
highPassBuffer[i] = yn;
|
||||
xn1 = xn;
|
||||
yn1 = yn;
|
||||
}
|
||||
}
|
||||
|
||||
private TapLatencyEvent[] scanForEdges(float[] peakBuffer, int numSamples) {
|
||||
ArrayList<TapLatencyEvent> events = new ArrayList<TapLatencyEvent>();
|
||||
float slow = 0.0f;
|
||||
float fast = 0.0f;
|
||||
float slowCoefficient = 0.01f;
|
||||
float fastCoefficient = 0.10f;
|
||||
boolean armed = true;
|
||||
int sampleIndex = 0;
|
||||
for (float level : peakBuffer) {
|
||||
slow = slow + (level - slow) * slowCoefficient; // low pass filter
|
||||
fast = fast + (level - fast) * fastCoefficient;
|
||||
if (armed && (fast > HIGH_THRESHOLD) && (fast > (2.0 * slow))) {
|
||||
//System.out.println("edge at " + sampleIndex + ", slow " + slow + ", fast " + fast);
|
||||
events.add(new TapLatencyEvent(TYPE_TAP, sampleIndex));
|
||||
armed = false;
|
||||
}
|
||||
// Use hysteresis when rearming.
|
||||
if (!armed && (fast < LOW_THRESHOLD)) {
|
||||
armed = true;
|
||||
}
|
||||
sampleIndex++;
|
||||
}
|
||||
return events.toArray(new TapLatencyEvent[0]);
|
||||
}
|
||||
|
||||
private void fillPeakBuffer(float[] buffer, int offset, int numSamples, float[] peakBuffer) {
|
||||
float previous = 0.0f;
|
||||
float maxInput = 0.0f;
|
||||
float maxOutput = 0.0f;
|
||||
for (int i = 0; i < numSamples; i++) {
|
||||
float input = buffer[i + offset];
|
||||
if (input > maxInput) {
|
||||
maxInput = input;
|
||||
}
|
||||
float output = previous * mDroop;
|
||||
if (input > output) {
|
||||
output = input;
|
||||
}
|
||||
previous = output;
|
||||
peakBuffer[i] = output;
|
||||
if (output > maxOutput) {
|
||||
maxOutput = output;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
+386
@@ -0,0 +1,386 @@
|
||||
/*
|
||||
* 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.Manifest;
|
||||
import android.content.pm.PackageManager;
|
||||
import android.media.midi.MidiDevice;
|
||||
import android.media.midi.MidiDeviceInfo;
|
||||
import android.media.midi.MidiInputPort;
|
||||
import android.media.midi.MidiManager;
|
||||
import android.os.Bundle;
|
||||
import android.os.Handler;
|
||||
import android.os.Looper;
|
||||
import android.util.Log;
|
||||
import android.view.Menu;
|
||||
import android.view.MenuItem;
|
||||
import android.view.MotionEvent;
|
||||
import android.view.View;
|
||||
import android.widget.TextView;
|
||||
import android.widget.Toast;
|
||||
|
||||
import com.mobileer.miditools.MidiOutputPortConnectionSelector;
|
||||
import com.mobileer.miditools.MidiPortConnector;
|
||||
import com.mobileer.miditools.MidiTools;
|
||||
|
||||
import java.io.IOException;
|
||||
|
||||
import static com.google.sample.oboe.manualtest.AudioMidiTester.TestListener;
|
||||
import static com.google.sample.oboe.manualtest.AudioMidiTester.TestResult;
|
||||
|
||||
public class TapToToneActivity extends TestOutputActivityBase {
|
||||
private static final int MY_PERMISSIONS_REQUEST_RECORD_AUDIO = 1234;
|
||||
private TextView mResultView;
|
||||
private MidiManager mMidiManager;
|
||||
private MidiInputPort mInputPort;
|
||||
|
||||
protected AudioMidiTester mAudioMidiTester;
|
||||
|
||||
private MidiOutputPortConnectionSelector mPortSelector;
|
||||
private MyTestListener mTestListener = new MyTestListener();
|
||||
private WaveformView mWaveformView;
|
||||
// Stats for latency
|
||||
private int mMeasurementCount;
|
||||
private int mLatencySumSamples;
|
||||
private int mLatencyMin;
|
||||
private int mLatencyMax;
|
||||
|
||||
@Override
|
||||
protected void inflateActivity() {
|
||||
setContentView(R.layout.activity_tap_to_tone);
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void onCreate(Bundle savedInstanceState) {
|
||||
super.onCreate(savedInstanceState);
|
||||
|
||||
mAudioOutTester = addAudioOutputTester();
|
||||
|
||||
mResultView = (TextView) findViewById(R.id.resultView);
|
||||
|
||||
if (getPackageManager().hasSystemFeature(PackageManager.FEATURE_MIDI)) {
|
||||
setupMidi();
|
||||
} else {
|
||||
Toast.makeText(TapToToneActivity.this,
|
||||
"MIDI not supported!", Toast.LENGTH_LONG)
|
||||
.show();
|
||||
}
|
||||
|
||||
mWaveformView = (WaveformView) findViewById(R.id.waveview_audio);
|
||||
|
||||
// Start a blip test when the waveform view is tapped.
|
||||
mWaveformView.setOnTouchListener(new View.OnTouchListener() {
|
||||
@Override
|
||||
public boolean onTouch(View view, MotionEvent event) {
|
||||
int action = event.getActionMasked();
|
||||
switch (action) {
|
||||
case MotionEvent.ACTION_DOWN:
|
||||
case MotionEvent.ACTION_POINTER_DOWN:
|
||||
mAudioMidiTester.setEnabled(true);
|
||||
break;
|
||||
case MotionEvent.ACTION_MOVE:
|
||||
break;
|
||||
case MotionEvent.ACTION_UP:
|
||||
case MotionEvent.ACTION_POINTER_UP:
|
||||
mAudioMidiTester.setEnabled(false);
|
||||
break;
|
||||
}
|
||||
// Must return true or we do not get the ACTION_MOVE and
|
||||
// ACTION_UP events.
|
||||
return true;
|
||||
}
|
||||
});
|
||||
|
||||
updateEnabledWidgets();
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void onStart() {
|
||||
super.onStart();
|
||||
setActivityType(ACTIVITY_TAP_TO_TONE);
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void onDestroy() {
|
||||
mAudioMidiTester.removeTestListener(mTestListener);
|
||||
closeMidiResources();
|
||||
super.onDestroy();
|
||||
}
|
||||
|
||||
private void setupMidi() {
|
||||
// Setup MIDI
|
||||
mMidiManager = (MidiManager) getSystemService(MIDI_SERVICE);
|
||||
MidiDeviceInfo[] infos = mMidiManager.getDevices();
|
||||
|
||||
// Open the port now so that the AudioMidiTester gets created.
|
||||
for (MidiDeviceInfo info : infos) {
|
||||
Bundle properties = info.getProperties();
|
||||
String product = properties
|
||||
.getString(MidiDeviceInfo.PROPERTY_PRODUCT);
|
||||
|
||||
Log.i(TAG, "product = " + product);
|
||||
if ("AudioLatencyTester".equals(product)) {
|
||||
openPort(info);
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
// These should only be set after mAudioMidiTester is set.
|
||||
private void setSpinnerListeners() {
|
||||
MidiDeviceInfo synthInfo = MidiTools.findDevice(mMidiManager, "AndroidTest",
|
||||
"AudioLatencyTester");
|
||||
Log.i(TAG, "found tester virtual device info: " + synthInfo);
|
||||
int portIndex = 0;
|
||||
mPortSelector = new MidiOutputPortConnectionSelector(mMidiManager, this,
|
||||
R.id.spinner_synth_sender, synthInfo, portIndex);
|
||||
mPortSelector.setConnectedListener(new MyPortsConnectedListener());
|
||||
|
||||
}
|
||||
|
||||
private class MyTestListener implements TestListener {
|
||||
@Override
|
||||
public void onTestFinished(final TestResult result) {
|
||||
runOnUiThread(new Runnable() {
|
||||
public void run() {
|
||||
showTestResults(result);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onNoteOn(final int pitch) {
|
||||
runOnUiThread(new Runnable() {
|
||||
public void run() {
|
||||
mStreamContexts.get(0).configurationView.setStatusText("MIDI pitch = " + pitch);
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
// Runs on UI thread.
|
||||
private void showTestResults(TestResult result) {
|
||||
String text;
|
||||
int previous = 0;
|
||||
if (result == null) {
|
||||
text = "";
|
||||
mWaveformView.clearSampleData();
|
||||
} else {
|
||||
if (result.events.length < 2) {
|
||||
text = "Not enough edges. Use fingernail.\n";
|
||||
mWaveformView.setCursorData(null);
|
||||
} else if (result.events.length > 2) {
|
||||
text = "Too many edges.\n";
|
||||
mWaveformView.setCursorData(null);
|
||||
} else {
|
||||
int[] cursors = new int[2];
|
||||
cursors[0] = result.events[0].sampleIndex;
|
||||
cursors[1] = result.events[1].sampleIndex;
|
||||
int latencySamples = cursors[1] - cursors[0];
|
||||
mLatencySumSamples += latencySamples;
|
||||
mMeasurementCount++;
|
||||
|
||||
int latencyMillis = 1000 * latencySamples / result.frameRate;
|
||||
if (mLatencyMin > latencyMillis) {
|
||||
mLatencyMin = latencyMillis;
|
||||
}
|
||||
if (mLatencyMax < latencyMillis) {
|
||||
mLatencyMax = latencyMillis;
|
||||
}
|
||||
|
||||
text = String.format("latency = %3d msec\n", latencyMillis);
|
||||
mWaveformView.setCursorData(cursors);
|
||||
}
|
||||
mWaveformView.setSampleData(result.filtered);
|
||||
}
|
||||
|
||||
if (mMeasurementCount > 0) {
|
||||
int averageLatencySamples = mLatencySumSamples / mMeasurementCount;
|
||||
int averageLatencyMillis = 1000 * averageLatencySamples / result.frameRate;
|
||||
final String plural = (mMeasurementCount == 1) ? "test" : "tests";
|
||||
text = text + String.format("min = %3d, avg = %3d, max = %3d, %d %s",
|
||||
mLatencyMin, averageLatencyMillis, mLatencyMax, mMeasurementCount, plural);
|
||||
}
|
||||
final String postText = text;
|
||||
mWaveformView.post(new Runnable() {
|
||||
public void run() {
|
||||
mResultView.setText(postText);
|
||||
mWaveformView.postInvalidate();
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
private void openPort(final MidiDeviceInfo info) {
|
||||
mMidiManager.openDevice(info, new MidiManager.OnDeviceOpenedListener() {
|
||||
@Override
|
||||
public void onDeviceOpened(MidiDevice device) {
|
||||
if (device == null) {
|
||||
Log.e(TAG, "could not open device " + info);
|
||||
} else {
|
||||
mInputPort = device.openInputPort(0);
|
||||
Log.i(TAG, "opened MIDI port = " + mInputPort + " on " + info);
|
||||
mAudioMidiTester = AudioMidiTester.getInstance();
|
||||
|
||||
Log.i(TAG, "openPort() mAudioMidiTester = " + mAudioMidiTester);
|
||||
// Now that we have created the AudioMidiTester, close the port so we can
|
||||
// open it later.
|
||||
try {
|
||||
mInputPort.close();
|
||||
} catch (IOException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
mAudioMidiTester.addTestListener(mTestListener);
|
||||
|
||||
setSpinnerListeners();
|
||||
}
|
||||
}
|
||||
}, new Handler(Looper.getMainLooper())
|
||||
);
|
||||
}
|
||||
|
||||
// TODO Listen to the synth server
|
||||
// for open/close events and then disable/enable the spinner.
|
||||
private class MyPortsConnectedListener
|
||||
implements MidiPortConnector.OnPortsConnectedListener {
|
||||
@Override
|
||||
public void onPortsConnected(final MidiDevice.MidiConnection connection) {
|
||||
Log.i(TAG, "onPortsConnected, connection = " + connection);
|
||||
runOnUiThread(new Runnable() {
|
||||
@Override
|
||||
public void run() {
|
||||
if (connection == null) {
|
||||
Toast.makeText(TapToToneActivity.this,
|
||||
R.string.error_port_busy, Toast.LENGTH_LONG)
|
||||
.show();
|
||||
mPortSelector.clearSelection();
|
||||
} else {
|
||||
Toast.makeText(TapToToneActivity.this,
|
||||
R.string.port_open_ok, Toast.LENGTH_LONG)
|
||||
.show();
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
private void closeMidiResources() {
|
||||
if (mPortSelector != null) {
|
||||
mPortSelector.close();
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean onCreateOptionsMenu(Menu menu) {
|
||||
// Inflate the menu; this adds items to the action bar if it is present.
|
||||
getMenuInflater().inflate(R.menu.menu_main, menu);
|
||||
return true;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean onOptionsItemSelected(MenuItem item) {
|
||||
// Handle action bar item clicks here. The action bar will
|
||||
// automatically handle clicks on the Home/Up button, so long
|
||||
// as you specify a parent activity in AndroidManifest.xml.
|
||||
int id = item.getItemId();
|
||||
|
||||
//noinspection SimplifiableIfStatement
|
||||
if (id == R.id.action_settings) {
|
||||
return true;
|
||||
}
|
||||
|
||||
return super.onOptionsItemSelected(item);
|
||||
}
|
||||
|
||||
private boolean hasRecordAudioPermission(){
|
||||
boolean hasPermission = (checkSelfPermission(
|
||||
Manifest.permission.RECORD_AUDIO) == PackageManager.PERMISSION_GRANTED);
|
||||
Log.i(TAG, "Has RECORD_AUDIO permission? " + hasPermission);
|
||||
return hasPermission;
|
||||
}
|
||||
|
||||
private void requestRecordAudioPermission(){
|
||||
|
||||
String requiredPermission = Manifest.permission.RECORD_AUDIO;
|
||||
|
||||
// If the user previously denied this permission then show a message explaining why
|
||||
// this permission is needed
|
||||
if (shouldShowRequestPermissionRationale(requiredPermission)) {
|
||||
showErrorToast("This app needs to record audio through the microphone....");
|
||||
}
|
||||
|
||||
// request the permission.
|
||||
requestPermissions(new String[]{requiredPermission},
|
||||
MY_PERMISSIONS_REQUEST_RECORD_AUDIO);
|
||||
}
|
||||
@Override
|
||||
public void onRequestPermissionsResult(int requestCode,
|
||||
String permissions[], int[] grantResults) {
|
||||
// TODO
|
||||
}
|
||||
|
||||
@Override
|
||||
public void startAudio() {
|
||||
if (hasRecordAudioPermission()) {
|
||||
startAudioPermitted();
|
||||
} else {
|
||||
requestRecordAudioPermission();
|
||||
}
|
||||
}
|
||||
|
||||
private void startAudioPermitted() {
|
||||
super.startAudio();
|
||||
resetLatency();
|
||||
try {
|
||||
mAudioMidiTester.start();
|
||||
if (mAudioOutTester != null) {
|
||||
mAudioOutTester.setToneType(OboeAudioOutputStream.TONE_TYPE_SAW_PING);
|
||||
} else {
|
||||
Log.w(TAG, "startAudioPermitted, mAudioOutTester = null, cannot setToneType(ping)");
|
||||
}
|
||||
} catch (IOException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void stopAudio() {
|
||||
mAudioMidiTester.stop();
|
||||
super.stopAudio();
|
||||
}
|
||||
|
||||
@Override
|
||||
public void pauseAudio() {
|
||||
mAudioMidiTester.stop();
|
||||
super.pauseAudio();
|
||||
}
|
||||
|
||||
@Override
|
||||
public void closeAudio() {
|
||||
mAudioMidiTester.stop();
|
||||
super.closeAudio();
|
||||
}
|
||||
|
||||
private void resetLatency() {
|
||||
mMeasurementCount = 0;
|
||||
mLatencySumSamples = 0;
|
||||
mLatencyMin = Integer.MAX_VALUE;
|
||||
mLatencyMax = 0;
|
||||
showTestResults(null);
|
||||
}
|
||||
|
||||
}
|
||||
+486
@@ -0,0 +1,486 @@
|
||||
/*
|
||||
* 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.media.AudioManager;
|
||||
import android.os.Bundle;
|
||||
import android.os.Handler;
|
||||
import android.os.Looper;
|
||||
import android.util.Log;
|
||||
import android.view.View;
|
||||
import android.view.WindowManager;
|
||||
import android.widget.Button;
|
||||
import android.widget.CheckBox;
|
||||
import android.widget.Toast;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.text.DateFormat;
|
||||
import java.text.SimpleDateFormat;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Calendar;
|
||||
import java.util.Date;
|
||||
|
||||
/**
|
||||
* Base class for other Activities.
|
||||
*/
|
||||
abstract class TestAudioActivity extends Activity {
|
||||
public static final String TAG = "TestOboe";
|
||||
|
||||
protected static final int FADER_PROGRESS_MAX = 1000;
|
||||
|
||||
public static final int AUDIO_STATE_OPEN = 0;
|
||||
public static final int AUDIO_STATE_STARTED = 1;
|
||||
public static final int AUDIO_STATE_PAUSED = 2;
|
||||
public static final int AUDIO_STATE_STOPPED = 3;
|
||||
public static final int AUDIO_STATE_CLOSED = 4;
|
||||
|
||||
public static final int COLOR_ACTIVE = 0xFFD0D0A0;
|
||||
public static final int COLOR_IDLE = 0xFFD0D0D0;
|
||||
|
||||
// Pass the activity index to native so it can know how to respond to the start and stop calls.
|
||||
// WARNING - must match definitions in NativeAudioContext.h ActivityType
|
||||
public static final int ACTIVITY_TEST_OUTPUT = 0;
|
||||
public static final int ACTIVITY_TEST_INPUT = 1;
|
||||
public static final int ACTIVITY_TAP_TO_TONE = 2;
|
||||
public static final int ACTIVITY_RECORD_PLAY = 3;
|
||||
public static final int ACTIVITY_ECHO = 4;
|
||||
public static final int ACTIVITY_RT_LATENCY = 5;
|
||||
public static final int ACTIVITY_GLITCHES = 6;
|
||||
public static final int ACTIVITY_TEST_DISCONNECT = 7;
|
||||
|
||||
private int mAudioState = AUDIO_STATE_CLOSED;
|
||||
protected String audioManagerSampleRate;
|
||||
protected int audioManagerFramesPerBurst;
|
||||
protected ArrayList<StreamContext> mStreamContexts;
|
||||
private Button mOpenButton;
|
||||
private Button mStartButton;
|
||||
private Button mPauseButton;
|
||||
private Button mStopButton;
|
||||
private Button mCloseButton;
|
||||
private MyStreamSniffer mStreamSniffer;
|
||||
private CheckBox mCallbackReturnStopBox;
|
||||
private int mSampleRate;
|
||||
|
||||
public static class StreamContext {
|
||||
StreamConfigurationView configurationView;
|
||||
AudioStreamTester tester;
|
||||
|
||||
boolean isInput() {
|
||||
return tester.getCurrentAudioStream().isInput();
|
||||
}
|
||||
}
|
||||
|
||||
// Periodically query the status of the streams.
|
||||
protected class MyStreamSniffer {
|
||||
public static final int SNIFFER_UPDATE_PERIOD_MSEC = 150;
|
||||
public static final int SNIFFER_UPDATE_DELAY_MSEC = 300;
|
||||
|
||||
private Handler mHandler;
|
||||
|
||||
// Display status info for the stream.
|
||||
private Runnable runnableCode = new Runnable() {
|
||||
@Override
|
||||
public void run() {
|
||||
boolean streamClosed = false;
|
||||
boolean gotViews = false;
|
||||
for (StreamContext streamContext : mStreamContexts) {
|
||||
AudioStreamBase.StreamStatus status = streamContext.tester.getCurrentAudioStream().getStreamStatus();
|
||||
if (streamContext.configurationView != null) {
|
||||
// Handler runs this on the main UI thread.
|
||||
int framesPerBurst = streamContext.tester.getCurrentAudioStream().getFramesPerBurst();
|
||||
status.framesPerCallback = getFramesPerCallback();
|
||||
final String msg = status.dump(framesPerBurst);
|
||||
streamContext.configurationView.setStatusText(msg);
|
||||
updateStreamDisplay();
|
||||
gotViews = true;
|
||||
}
|
||||
|
||||
streamClosed = streamClosed || (status.state >= 12);
|
||||
}
|
||||
|
||||
if (streamClosed) {
|
||||
onStreamClosed();
|
||||
} else {
|
||||
// Repeat this runnable code block again.
|
||||
if (gotViews) {
|
||||
mHandler.postDelayed(runnableCode, SNIFFER_UPDATE_PERIOD_MSEC);
|
||||
}
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
private void startStreamSniffer() {
|
||||
stopStreamSniffer();
|
||||
mHandler = new Handler(Looper.getMainLooper());
|
||||
// Start the initial runnable task by posting through the handler
|
||||
mHandler.postDelayed(runnableCode, SNIFFER_UPDATE_DELAY_MSEC);
|
||||
}
|
||||
|
||||
private void stopStreamSniffer() {
|
||||
if (mHandler != null) {
|
||||
mHandler.removeCallbacks(runnableCode);
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
public void onStreamClosed() {
|
||||
}
|
||||
|
||||
protected abstract void inflateActivity();
|
||||
|
||||
void updateStreamDisplay() {
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void onCreate(Bundle savedInstanceState) {
|
||||
super.onCreate(savedInstanceState);
|
||||
inflateActivity();
|
||||
findAudioCommon();
|
||||
}
|
||||
|
||||
public void hideSettingsViews() {
|
||||
for (StreamContext streamContext : mStreamContexts) {
|
||||
if (streamContext.configurationView != null) {
|
||||
streamContext.configurationView.hideSettingsView();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void onStart() {
|
||||
super.onStart();
|
||||
resetConfiguration();
|
||||
}
|
||||
|
||||
protected void resetConfiguration() {
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void onStop() {
|
||||
Log.i(TAG, "onStop() called so stopping audio =========================");
|
||||
stopAudio();
|
||||
closeAudio();
|
||||
super.onStop();
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void onDestroy() {
|
||||
mAudioState = AUDIO_STATE_CLOSED;
|
||||
super.onDestroy();
|
||||
}
|
||||
|
||||
protected void updateEnabledWidgets() {
|
||||
if (mOpenButton != null) {
|
||||
mOpenButton.setBackgroundColor(mAudioState == AUDIO_STATE_OPEN ? COLOR_ACTIVE : COLOR_IDLE);
|
||||
mStartButton.setBackgroundColor(mAudioState == AUDIO_STATE_STARTED ? COLOR_ACTIVE : COLOR_IDLE);
|
||||
mPauseButton.setBackgroundColor(mAudioState == AUDIO_STATE_PAUSED ? COLOR_ACTIVE : COLOR_IDLE);
|
||||
mStopButton.setBackgroundColor(mAudioState == AUDIO_STATE_STOPPED ? COLOR_ACTIVE : COLOR_IDLE);
|
||||
mCloseButton.setBackgroundColor(mAudioState == AUDIO_STATE_CLOSED ? COLOR_ACTIVE : COLOR_IDLE);
|
||||
}
|
||||
setConfigViewsEnabled(mAudioState == AUDIO_STATE_CLOSED);
|
||||
}
|
||||
|
||||
private void setConfigViewsEnabled(boolean b) {
|
||||
for (StreamContext streamContext : mStreamContexts) {
|
||||
if (streamContext.configurationView != null) {
|
||||
streamContext.configurationView.setChildrenEnabled(b);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
abstract boolean isOutput();
|
||||
|
||||
public void clearStreamContexts() {
|
||||
mStreamContexts.clear();
|
||||
}
|
||||
|
||||
public StreamContext addOutputStreamContext() {
|
||||
StreamContext streamContext = new StreamContext();
|
||||
streamContext.tester = AudioOutputTester.getInstance();
|
||||
streamContext.configurationView = (StreamConfigurationView)
|
||||
findViewById(R.id.outputStreamConfiguration);
|
||||
if (streamContext.configurationView == null) {
|
||||
streamContext.configurationView = (StreamConfigurationView)
|
||||
findViewById(R.id.streamConfiguration);
|
||||
}
|
||||
if (streamContext.configurationView != null) {
|
||||
streamContext.configurationView.setOutput(true);
|
||||
streamContext.configurationView.setRequestedConfiguration(streamContext.tester.requestedConfiguration);
|
||||
streamContext.configurationView.setActualConfiguration(streamContext.tester.actualConfiguration);
|
||||
}
|
||||
mStreamContexts.add(streamContext);
|
||||
return streamContext;
|
||||
}
|
||||
|
||||
|
||||
public AudioOutputTester addAudioOutputTester() {
|
||||
StreamContext streamContext = addOutputStreamContext();
|
||||
return (AudioOutputTester) streamContext.tester;
|
||||
}
|
||||
|
||||
public StreamContext addInputStreamContext() {
|
||||
StreamContext streamContext = new StreamContext();
|
||||
streamContext.tester = AudioInputTester.getInstance();
|
||||
streamContext.configurationView = (StreamConfigurationView)
|
||||
findViewById(R.id.inputStreamConfiguration);
|
||||
if (streamContext.configurationView == null) {
|
||||
streamContext.configurationView = (StreamConfigurationView)
|
||||
findViewById(R.id.streamConfiguration);
|
||||
}
|
||||
if (streamContext.configurationView != null) {
|
||||
streamContext.configurationView.setOutput(false);
|
||||
streamContext.configurationView.setRequestedConfiguration(streamContext.tester.requestedConfiguration);
|
||||
streamContext.configurationView.setActualConfiguration(streamContext.tester.actualConfiguration);
|
||||
}
|
||||
streamContext.tester = AudioInputTester.getInstance();
|
||||
mStreamContexts.add(streamContext);
|
||||
return streamContext;
|
||||
}
|
||||
|
||||
public AudioInputTester addAudioInputTester() {
|
||||
StreamContext streamContext = addInputStreamContext();
|
||||
return (AudioInputTester) streamContext.tester;
|
||||
}
|
||||
|
||||
void updateStreamConfigurationViews() {
|
||||
for (StreamContext streamContext : mStreamContexts) {
|
||||
if (streamContext.configurationView != null) {
|
||||
streamContext.configurationView.updateDisplay();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
StreamContext getFirstInputStreamContext() {
|
||||
for (StreamContext streamContext : mStreamContexts) {
|
||||
if (streamContext.isInput())
|
||||
return streamContext;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
StreamContext getFirstOutputStreamContext() {
|
||||
for (StreamContext streamContext : mStreamContexts) {
|
||||
if (!streamContext.isInput())
|
||||
return streamContext;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
protected void findAudioCommon() {
|
||||
mOpenButton = (Button) findViewById(R.id.button_open);
|
||||
if (mOpenButton != null) {
|
||||
mStartButton = (Button) findViewById(R.id.button_start);
|
||||
mPauseButton = (Button) findViewById(R.id.button_pause);
|
||||
mStopButton = (Button) findViewById(R.id.button_stop);
|
||||
mCloseButton = (Button) findViewById(R.id.button_close);
|
||||
}
|
||||
mStreamContexts = new ArrayList<StreamContext>();
|
||||
|
||||
queryNativeAudioParameters();
|
||||
|
||||
mCallbackReturnStopBox = (CheckBox) findViewById(R.id.callbackReturnStop);
|
||||
if (mCallbackReturnStopBox != null) {
|
||||
mCallbackReturnStopBox.setOnClickListener(new View.OnClickListener() {
|
||||
@Override
|
||||
public void onClick(View v) {
|
||||
OboeAudioStream.setCallbackReturnStop(mCallbackReturnStopBox.isChecked());
|
||||
}
|
||||
});
|
||||
}
|
||||
OboeAudioStream.setCallbackReturnStop(false);
|
||||
|
||||
mStreamSniffer = new MyStreamSniffer();
|
||||
}
|
||||
|
||||
private void queryNativeAudioParameters() {
|
||||
AudioManager myAudioMgr = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
|
||||
audioManagerSampleRate = myAudioMgr.getProperty(AudioManager.PROPERTY_OUTPUT_SAMPLE_RATE);
|
||||
String audioManagerFramesPerBurstText = myAudioMgr.getProperty(AudioManager.PROPERTY_OUTPUT_FRAMES_PER_BUFFER);
|
||||
audioManagerFramesPerBurst = Integer.parseInt(audioManagerFramesPerBurstText);
|
||||
}
|
||||
|
||||
abstract public void setupEffects(int sessionId);
|
||||
|
||||
protected void showErrorToast(String message) {
|
||||
showToast("Error: " + message);
|
||||
}
|
||||
|
||||
protected void showToast(final String message) {
|
||||
runOnUiThread(new Runnable() {
|
||||
@Override
|
||||
public void run() {
|
||||
Toast.makeText(TestAudioActivity.this,
|
||||
message,
|
||||
Toast.LENGTH_SHORT).show();
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
public void openAudio(View view) {
|
||||
try {
|
||||
openAudio();
|
||||
} catch (Exception e) {
|
||||
showErrorToast(e.getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
public void startAudio(View view) {
|
||||
Log.i(TAG, "startAudio() called =======================================");
|
||||
startAudio();
|
||||
keepScreenOn(true);
|
||||
}
|
||||
|
||||
protected void keepScreenOn(boolean on) {
|
||||
if (on) {
|
||||
getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
|
||||
} else {
|
||||
getWindow().clearFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
|
||||
}
|
||||
}
|
||||
|
||||
public void stopAudio(View view) {
|
||||
stopAudio();
|
||||
keepScreenOn(false);
|
||||
}
|
||||
|
||||
public void pauseAudio(View view) {
|
||||
pauseAudio();
|
||||
keepScreenOn(false);
|
||||
}
|
||||
|
||||
public void closeAudio(View view) {
|
||||
closeAudio();
|
||||
}
|
||||
|
||||
public int getSampleRate() {
|
||||
return mSampleRate;
|
||||
}
|
||||
|
||||
public void openAudio() throws IOException {
|
||||
closeAudio();
|
||||
|
||||
int sampleRate = 0;
|
||||
|
||||
// Open output streams then open input streams.
|
||||
// This is so that the capacity of input stream can be expanded to
|
||||
// match the burst size of the output for full duplex.
|
||||
for (StreamContext streamContext : mStreamContexts) {
|
||||
if (!streamContext.isInput()) {
|
||||
openStreamContext(streamContext);
|
||||
int streamSampleRate = streamContext.tester.actualConfiguration.getSampleRate();
|
||||
if (sampleRate == 0) {
|
||||
sampleRate = streamSampleRate;
|
||||
}
|
||||
}
|
||||
}
|
||||
for (StreamContext streamContext : mStreamContexts) {
|
||||
if (streamContext.isInput()) {
|
||||
if (sampleRate != 0) {
|
||||
streamContext.tester.requestedConfiguration.setSampleRate(sampleRate);
|
||||
}
|
||||
openStreamContext(streamContext);
|
||||
}
|
||||
}
|
||||
updateEnabledWidgets();
|
||||
mStreamSniffer.startStreamSniffer();
|
||||
}
|
||||
|
||||
private void openStreamContext(StreamContext streamContext) throws IOException {
|
||||
StreamConfiguration requestedConfig = streamContext.tester.requestedConfiguration;
|
||||
StreamConfiguration actualConfig = streamContext.tester.actualConfiguration;
|
||||
|
||||
requestedConfig.setFramesPerBurst(audioManagerFramesPerBurst);
|
||||
streamContext.tester.open();
|
||||
mSampleRate = actualConfig.getSampleRate();
|
||||
mAudioState = AUDIO_STATE_OPEN;
|
||||
int sessionId = actualConfig.getSessionId();
|
||||
if (sessionId > 0) {
|
||||
setupEffects(sessionId);
|
||||
}
|
||||
if (streamContext.configurationView != null) {
|
||||
streamContext.configurationView.updateDisplay();
|
||||
}
|
||||
}
|
||||
|
||||
// Native methods
|
||||
private native int startNative();
|
||||
private native int pauseNative();
|
||||
private native int stopNative();
|
||||
protected native void setActivityType(int activityType);
|
||||
private native int getFramesPerCallback();
|
||||
|
||||
public void startAudio() {
|
||||
int result = startNative();
|
||||
if (result < 0) {
|
||||
showErrorToast("Start failed with " + result);
|
||||
} else {
|
||||
for (StreamContext streamContext : mStreamContexts) {
|
||||
StreamConfigurationView configView = streamContext.configurationView;
|
||||
if (configView != null) {
|
||||
configView.updateDisplay();
|
||||
}
|
||||
}
|
||||
mAudioState = AUDIO_STATE_STARTED;
|
||||
updateEnabledWidgets();
|
||||
}
|
||||
}
|
||||
|
||||
public void pauseAudio() {
|
||||
int result = pauseNative();
|
||||
if (result < 0) {
|
||||
showErrorToast("Pause failed with " + result);
|
||||
} else {
|
||||
mAudioState = AUDIO_STATE_PAUSED;
|
||||
updateEnabledWidgets();
|
||||
}
|
||||
}
|
||||
|
||||
public void stopAudio() {
|
||||
int result = stopNative();
|
||||
if (result < 0) {
|
||||
showErrorToast("Stop failed with " + result);
|
||||
} else {
|
||||
mAudioState = AUDIO_STATE_STOPPED;
|
||||
updateEnabledWidgets();
|
||||
}
|
||||
}
|
||||
|
||||
public void stopAudioQuiet() {
|
||||
stopNative();
|
||||
mAudioState = AUDIO_STATE_STOPPED;
|
||||
updateEnabledWidgets();
|
||||
}
|
||||
|
||||
public void closeAudio() {
|
||||
mStreamSniffer.stopStreamSniffer();
|
||||
for (StreamContext streamContext : mStreamContexts) {
|
||||
streamContext.tester.close();
|
||||
}
|
||||
mAudioState = AUDIO_STATE_CLOSED;
|
||||
updateEnabledWidgets();
|
||||
}
|
||||
|
||||
String getTimestampString() {
|
||||
DateFormat df = new SimpleDateFormat("yyyyMMdd-HHmmss");
|
||||
Date now = Calendar.getInstance().getTime();
|
||||
return df.format(now);
|
||||
}
|
||||
|
||||
}
|
||||
+482
@@ -0,0 +1,482 @@
|
||||
/*
|
||||
* 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.BroadcastReceiver;
|
||||
import android.content.Context;
|
||||
import android.content.Intent;
|
||||
import android.content.IntentFilter;
|
||||
import android.os.Build;
|
||||
import android.os.Bundle;
|
||||
import android.text.method.ScrollingMovementMethod;
|
||||
import android.view.View;
|
||||
import android.widget.Button;
|
||||
import android.widget.TextView;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.util.Date;
|
||||
|
||||
/**
|
||||
* Guide the user through a series of tests plugging in and unplugging a headset.
|
||||
* Print a summary at the end of any failures.
|
||||
*
|
||||
* TODO Test Input
|
||||
*/
|
||||
public class TestDisconnectActivity extends TestAudioActivity implements Runnable {
|
||||
|
||||
private static final String TEXT_SKIP = "SKIP";
|
||||
private static final String TEXT_PASS = "PASS";
|
||||
private static final String TEXT_FAIL = "FAIL !!!!";
|
||||
public static final int POLL_DURATION_MILLIS = 50;
|
||||
public static final int SETTLING_TIME_MILLIS = 600;
|
||||
public static final int TIME_TO_FAILURE_MILLIS = 3000;
|
||||
|
||||
private TextView mInstructionsTextView;
|
||||
private TextView mAutoTextView;
|
||||
private TextView mStatusTextView;
|
||||
private TextView mPlugTextView;
|
||||
|
||||
private Thread mAutoThread;
|
||||
private volatile boolean mThreadEnabled;
|
||||
private volatile boolean mTestFailed;
|
||||
private volatile boolean mSkipTest;
|
||||
private volatile int mPlugCount;
|
||||
private int mTestCount;
|
||||
private StringBuffer mFailedSummary;
|
||||
private int mPassCount;
|
||||
private int mFailCount;
|
||||
private BroadcastReceiver mPluginReceiver = new PluginBroadcastReceiver();
|
||||
private Button mStartButton;
|
||||
private Button mStopButton;
|
||||
private Button mShareButton;
|
||||
private Button mFailButton;
|
||||
private Button mSkipButton;
|
||||
|
||||
// Receive a broadcast Intent when a headset is plugged in or unplugged.
|
||||
// Display a count on screen.
|
||||
public class PluginBroadcastReceiver extends BroadcastReceiver {
|
||||
@Override
|
||||
public void onReceive(Context context, Intent intent) {
|
||||
mPlugCount++;
|
||||
runOnUiThread(new Runnable() {
|
||||
@Override
|
||||
public void run() {
|
||||
String message = "Intent.HEADSET_PLUG #" + mPlugCount;
|
||||
mPlugTextView.setText(message);
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void inflateActivity() {
|
||||
setContentView(R.layout.activity_test_disconnect);
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void onCreate(Bundle savedInstanceState) {
|
||||
super.onCreate(savedInstanceState);
|
||||
|
||||
mInstructionsTextView = (TextView) findViewById(R.id.text_instructions);
|
||||
mStatusTextView = (TextView) findViewById(R.id.text_status);
|
||||
mPlugTextView = (TextView) findViewById(R.id.text_plug_events);
|
||||
mAutoTextView = (TextView) findViewById(R.id.text_log);
|
||||
mAutoTextView.setMovementMethod(new ScrollingMovementMethod());
|
||||
|
||||
mStartButton = (Button) findViewById(R.id.button_start);
|
||||
mStopButton = (Button) findViewById(R.id.button_stop);
|
||||
mShareButton = (Button) findViewById(R.id.button_share);
|
||||
mShareButton.setEnabled(false);
|
||||
mFailButton = (Button) findViewById(R.id.button_fail);
|
||||
mSkipButton = (Button) findViewById(R.id.button_skip);
|
||||
updateStartStopButtons(false);
|
||||
updateFailSkipButton(false);
|
||||
}
|
||||
|
||||
private void updateStartStopButtons(boolean running) {
|
||||
mStartButton.setEnabled(!running);
|
||||
mStopButton.setEnabled(running);
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void onStart() {
|
||||
super.onStart();
|
||||
setActivityType(ACTIVITY_TEST_DISCONNECT);
|
||||
}
|
||||
|
||||
@Override
|
||||
boolean isOutput() {
|
||||
return true;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void setupEffects(int sessionId) {
|
||||
}
|
||||
|
||||
private void updateFailSkipButton(final boolean running) {
|
||||
runOnUiThread(new Runnable() {
|
||||
@Override
|
||||
public void run() {
|
||||
mFailButton.setEnabled(running);
|
||||
mSkipButton.setEnabled(running);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
// Write to scrollable TextView
|
||||
private void log(final String text) {
|
||||
runOnUiThread(new Runnable() {
|
||||
@Override
|
||||
public void run() {
|
||||
mAutoTextView.append(text);
|
||||
mAutoTextView.append("\n");
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
// Write to status and command view
|
||||
private void setInstructionsText(final String text) {
|
||||
runOnUiThread(new Runnable() {
|
||||
@Override
|
||||
public void run() {
|
||||
mInstructionsTextView.setText(text);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
// Write to status and command view
|
||||
private void setStatusText(final String text) {
|
||||
runOnUiThread(new Runnable() {
|
||||
@Override
|
||||
public void run() {
|
||||
mStatusTextView.setText(text);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
private void logClear() {
|
||||
runOnUiThread(new Runnable() {
|
||||
@Override
|
||||
public void run() {
|
||||
mAutoTextView.setText("");
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onResume() {
|
||||
super.onResume();
|
||||
IntentFilter filter = new IntentFilter(Intent.ACTION_HEADSET_PLUG);
|
||||
this.registerReceiver(mPluginReceiver, filter);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onPause() {
|
||||
this.unregisterReceiver(mPluginReceiver);
|
||||
super.onPause();
|
||||
}
|
||||
|
||||
// Only call from UI thread.
|
||||
public void onTestFinished() {
|
||||
updateStartStopButtons(false);
|
||||
mShareButton.setEnabled(true);
|
||||
}
|
||||
|
||||
public void startAudioTest() throws IOException {
|
||||
openAudio();
|
||||
startAudio();
|
||||
}
|
||||
|
||||
public void stopAudioTest() {
|
||||
stopAudioQuiet();
|
||||
closeAudio();
|
||||
}
|
||||
|
||||
public void onCancel(View view) {
|
||||
stopAudioTest();
|
||||
onTestFinished();
|
||||
}
|
||||
|
||||
// Called on UI thread
|
||||
public void onStopAudioTest(View view) {
|
||||
stopAudioTest();
|
||||
onTestFinished();
|
||||
keepScreenOn(false);
|
||||
}
|
||||
|
||||
public void onStartDisconnectTest(View view) {
|
||||
updateStartStopButtons(true);
|
||||
mThreadEnabled = true;
|
||||
mAutoThread = new Thread(this);
|
||||
mAutoThread.start();
|
||||
}
|
||||
|
||||
public void onStopDisconnectTest(View view) {
|
||||
try {
|
||||
if (mAutoThread != null) {
|
||||
mThreadEnabled = false;
|
||||
mAutoThread.interrupt();
|
||||
mAutoThread.join(100);
|
||||
mAutoThread = null;
|
||||
}
|
||||
} catch (InterruptedException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
|
||||
public void onFailTest(View view) {
|
||||
mTestFailed = true;
|
||||
}
|
||||
|
||||
public void onSkipTest(View view) {
|
||||
mSkipTest = true;
|
||||
}
|
||||
|
||||
// Share text from log via GMail, Drive or other method.
|
||||
public void onShareResult(View view) {
|
||||
Intent sharingIntent = new Intent(Intent.ACTION_SEND);
|
||||
sharingIntent.setType("text/plain");
|
||||
|
||||
String subjectText = "OboeTester Test Disconnect result " + getTimestampString();
|
||||
sharingIntent.putExtra(Intent.EXTRA_SUBJECT, subjectText);
|
||||
|
||||
String shareBody = mAutoTextView.getText().toString();
|
||||
sharingIntent.putExtra(Intent.EXTRA_TEXT, shareBody);
|
||||
|
||||
startActivity(Intent.createChooser(sharingIntent, "Share using:"));
|
||||
}
|
||||
|
||||
private String getConfigText(StreamConfiguration config) {
|
||||
return ((config.getDirection() == StreamConfiguration.DIRECTION_OUTPUT) ? "OUT" : "IN")
|
||||
+ ", Perf = " + StreamConfiguration.convertPerformanceModeToText(
|
||||
config.getPerformanceMode())
|
||||
+ ", " + StreamConfiguration.convertSharingModeToText(config.getSharingMode());
|
||||
}
|
||||
|
||||
private void testConfiguration(boolean isInput,
|
||||
int perfMode,
|
||||
int sharingMode,
|
||||
int channelCount,
|
||||
boolean requestPlugin) throws InterruptedException {
|
||||
String actualConfigText = "none";
|
||||
mSkipTest = false;
|
||||
|
||||
AudioInputTester mAudioInTester = null;
|
||||
AudioOutputTester mAudioOutTester = null;
|
||||
|
||||
clearStreamContexts();
|
||||
|
||||
if (isInput) {
|
||||
mAudioInTester = addAudioInputTester();
|
||||
} else {
|
||||
mAudioOutTester = addAudioOutputTester();
|
||||
}
|
||||
|
||||
// Configure settings
|
||||
StreamConfiguration requestedConfig = (isInput)
|
||||
? mAudioInTester.requestedConfiguration
|
||||
: mAudioOutTester.requestedConfiguration;
|
||||
StreamConfiguration actualConfig = (isInput)
|
||||
? mAudioInTester.actualConfiguration
|
||||
: mAudioOutTester.actualConfiguration;
|
||||
|
||||
requestedConfig.reset();
|
||||
requestedConfig.setPerformanceMode(perfMode);
|
||||
requestedConfig.setSharingMode(sharingMode);
|
||||
requestedConfig.setChannelCount(channelCount);
|
||||
|
||||
log("========================== #" + mTestCount);
|
||||
log("Requested:");
|
||||
log(getConfigText(requestedConfig));
|
||||
|
||||
// Give previous stream time to close and release resources. Avoid race conditions.
|
||||
Thread.sleep(SETTLING_TIME_MILLIS);
|
||||
if (!mThreadEnabled) return;
|
||||
boolean openFailed = false;
|
||||
AudioStreamBase stream = null;
|
||||
try {
|
||||
startAudioTest(); // this will fill in actualConfig
|
||||
log("Actual:");
|
||||
actualConfigText = getConfigText(actualConfig)
|
||||
+ ", " + (actualConfig.isMMap() ? "MMAP" : "Legacy");
|
||||
log(actualConfigText);
|
||||
|
||||
stream = (isInput)
|
||||
? mAudioInTester.getCurrentAudioStream()
|
||||
: mAudioOutTester.getCurrentAudioStream();
|
||||
} catch (IOException e) {
|
||||
openFailed = true;
|
||||
log(e.getMessage());
|
||||
}
|
||||
|
||||
// The test is only worth running if we got the configuration we requested.
|
||||
boolean valid = true;
|
||||
if (!openFailed) {
|
||||
if(actualConfig.getSharingMode() != sharingMode) {
|
||||
log("did not get requested sharing mode");
|
||||
valid = false;
|
||||
}
|
||||
if (actualConfig.getPerformanceMode() != perfMode) {
|
||||
log("did not get requested performance mode");
|
||||
valid = false;
|
||||
}
|
||||
if (actualConfig.getNativeApi() == StreamConfiguration.NATIVE_API_OPENSLES) {
|
||||
log("OpenSL ES does not support automatic disconnect");
|
||||
valid = false;
|
||||
}
|
||||
}
|
||||
|
||||
int oldPlugCount = mPlugCount;
|
||||
if (!openFailed && valid) {
|
||||
mTestFailed = false;
|
||||
updateFailSkipButton(true);
|
||||
// poll for stream disconnected
|
||||
while (!mTestFailed && mThreadEnabled && !mSkipTest &&
|
||||
stream.getState() == StreamConfiguration.STREAM_STATE_STARTING) {
|
||||
Thread.sleep(POLL_DURATION_MILLIS);
|
||||
}
|
||||
String message = (requestPlugin ? "Plug IN" : "UNplug") + " headset now!";
|
||||
setStatusText("Testing:\n" + actualConfigText);
|
||||
setInstructionsText(message);
|
||||
int timeoutCount = 0;
|
||||
// Wait for Java plug count to change or stream to disconnect.
|
||||
while (!mTestFailed && mThreadEnabled && !mSkipTest &&
|
||||
stream.getState() == StreamConfiguration.STREAM_STATE_STARTED) {
|
||||
Thread.sleep(POLL_DURATION_MILLIS);
|
||||
if (mPlugCount > oldPlugCount) {
|
||||
timeoutCount = TIME_TO_FAILURE_MILLIS / POLL_DURATION_MILLIS;
|
||||
break;
|
||||
}
|
||||
}
|
||||
// Wait for timeout or stream to disconnect.
|
||||
while (!mTestFailed && mThreadEnabled && !mSkipTest && (timeoutCount > 0) &&
|
||||
stream.getState() == StreamConfiguration.STREAM_STATE_STARTED) {
|
||||
Thread.sleep(POLL_DURATION_MILLIS);
|
||||
timeoutCount--;
|
||||
if (timeoutCount == 0) {
|
||||
mTestFailed = true;
|
||||
} else {
|
||||
setStatusText("Plug detected by Java.\nCounting down to Oboe failure: " + timeoutCount);
|
||||
}
|
||||
}
|
||||
setStatusText(mTestFailed ? "Failed" : "Passed - detected");
|
||||
}
|
||||
updateFailSkipButton(false);
|
||||
setInstructionsText("Wait...");
|
||||
|
||||
if (!openFailed) {
|
||||
stopAudioTest();
|
||||
}
|
||||
|
||||
if (mSkipTest) valid = false;
|
||||
|
||||
if (valid) {
|
||||
if (openFailed) {
|
||||
mFailedSummary.append("------ #" + mTestCount);
|
||||
mFailedSummary.append("\n");
|
||||
mFailedSummary.append(getConfigText(requestedConfig));
|
||||
mFailedSummary.append("\n");
|
||||
mFailedSummary.append("Open failed!\n");
|
||||
mFailCount++;
|
||||
} else {
|
||||
log("Result:");
|
||||
boolean passed = !mTestFailed;
|
||||
String resultText = requestPlugin ? "plugIN" : "UNplug";
|
||||
resultText += ", " + (passed ? TEXT_PASS : TEXT_FAIL);
|
||||
log(resultText);
|
||||
if (!passed) {
|
||||
mFailedSummary.append("------ #" + mTestCount);
|
||||
mFailedSummary.append("\n");
|
||||
mFailedSummary.append(" ");
|
||||
mFailedSummary.append(actualConfigText);
|
||||
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(1000);
|
||||
mTestCount++;
|
||||
}
|
||||
|
||||
private void testConfiguration(boolean isInput, int performanceMode,
|
||||
int sharingMode) throws InterruptedException {
|
||||
int channelCount = 2;
|
||||
boolean requestPlugin = true; // plug IN
|
||||
testConfiguration(isInput, performanceMode, sharingMode, channelCount, requestPlugin);
|
||||
requestPlugin = false; // UNplug
|
||||
testConfiguration(isInput, performanceMode, sharingMode, channelCount, requestPlugin);
|
||||
}
|
||||
|
||||
private void testConfiguration(int performanceMode,
|
||||
int sharingMode) throws InterruptedException {
|
||||
testConfiguration(false, performanceMode, sharingMode);
|
||||
testConfiguration(true, performanceMode, sharingMode);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void run() {
|
||||
mPlugCount = 0;
|
||||
logClear();
|
||||
log("=== STARTED at " + new Date());
|
||||
log(Build.MANUFACTURER + " " + Build.PRODUCT);
|
||||
log(Build.DISPLAY);
|
||||
mFailedSummary = new StringBuffer();
|
||||
mTestCount = 0;
|
||||
mPassCount = 0;
|
||||
mFailCount = 0;
|
||||
// Try several different configurations.
|
||||
try {
|
||||
testConfiguration(StreamConfiguration.PERFORMANCE_MODE_LOW_LATENCY,
|
||||
StreamConfiguration.SHARING_MODE_EXCLUSIVE);
|
||||
testConfiguration(StreamConfiguration.PERFORMANCE_MODE_LOW_LATENCY,
|
||||
StreamConfiguration.SHARING_MODE_SHARED);
|
||||
testConfiguration(StreamConfiguration.PERFORMANCE_MODE_NONE,
|
||||
StreamConfiguration.SHARING_MODE_SHARED);
|
||||
} catch (InterruptedException e) {
|
||||
e.printStackTrace();
|
||||
} finally {
|
||||
stopAudioTest();
|
||||
setInstructionsText("See summary below.");
|
||||
setStatusText("Finished.");
|
||||
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();
|
||||
}
|
||||
});
|
||||
updateFailSkipButton(false);
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
+247
@@ -0,0 +1,247 @@
|
||||
/*
|
||||
* 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.Manifest;
|
||||
import android.content.Intent;
|
||||
import android.content.pm.PackageManager;
|
||||
import android.media.audiofx.AcousticEchoCanceler;
|
||||
import android.media.audiofx.AutomaticGainControl;
|
||||
import android.net.Uri;
|
||||
import android.os.Bundle;
|
||||
import android.os.Environment;
|
||||
import android.support.annotation.NonNull;
|
||||
import android.support.v4.app.ActivityCompat;
|
||||
import android.support.v4.content.FileProvider;
|
||||
import android.view.View;
|
||||
import android.widget.CheckBox;
|
||||
import android.widget.RadioButton;
|
||||
import android.widget.TextView;
|
||||
import android.widget.Toast;
|
||||
|
||||
import com.google.sample.oboe.manualtest.R;
|
||||
|
||||
import java.io.File;
|
||||
import java.io.IOException;
|
||||
|
||||
/**
|
||||
* Test Oboe Capture
|
||||
*/
|
||||
|
||||
public class TestInputActivity extends TestAudioActivity
|
||||
implements ActivityCompat.OnRequestPermissionsResultCallback {
|
||||
|
||||
private static final int AUDIO_ECHO_REQUEST = 0;
|
||||
protected AudioInputTester mAudioInputTester;
|
||||
private static final int NUM_VOLUME_BARS = 4;
|
||||
private VolumeBarView[] mVolumeBars = new VolumeBarView[NUM_VOLUME_BARS];
|
||||
private InputMarginView mInputMarginView;
|
||||
private int mInputMarginBursts = 0;
|
||||
private WorkloadView mWorkloadView;
|
||||
|
||||
public native void setMinimumFramesBeforeRead(int frames);
|
||||
public native int saveWaveFile(String absolutePath);
|
||||
|
||||
@Override boolean isOutput() { return false; }
|
||||
|
||||
@Override
|
||||
protected void inflateActivity() {
|
||||
setContentView(R.layout.activity_test_input);
|
||||
|
||||
BufferSizeView bufferSizeView = findViewById(R.id.buffer_size_view);
|
||||
bufferSizeView.setVisibility(View.GONE);
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void onCreate(Bundle savedInstanceState) {
|
||||
super.onCreate(savedInstanceState);
|
||||
|
||||
mVolumeBars[0] = (VolumeBarView) findViewById(R.id.volumeBar0);
|
||||
mVolumeBars[1] = (VolumeBarView) findViewById(R.id.volumeBar1);
|
||||
mVolumeBars[2] = (VolumeBarView) findViewById(R.id.volumeBar2);
|
||||
mVolumeBars[3] = (VolumeBarView) findViewById(R.id.volumeBar3);
|
||||
|
||||
mInputMarginView = (InputMarginView) findViewById(R.id.input_margin_view);
|
||||
|
||||
updateEnabledWidgets();
|
||||
|
||||
mAudioInputTester = addAudioInputTester();
|
||||
|
||||
mWorkloadView = (WorkloadView) findViewById(R.id.workload_view);
|
||||
if (mWorkloadView != null) {
|
||||
mWorkloadView.setAudioStreamTester(mAudioInputTester);
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void onStart() {
|
||||
super.onStart();
|
||||
setActivityType(ACTIVITY_TEST_INPUT);
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void resetConfiguration() {
|
||||
super.resetConfiguration();
|
||||
mAudioInputTester.reset();
|
||||
}
|
||||
|
||||
@Override
|
||||
void updateStreamDisplay() {
|
||||
int numChannels = mAudioInputTester.getCurrentAudioStream().getChannelCount();
|
||||
if (numChannels > NUM_VOLUME_BARS) {
|
||||
numChannels = NUM_VOLUME_BARS;
|
||||
}
|
||||
for (int i = 0; i < numChannels; i++) {
|
||||
if (mVolumeBars[i] == null) break;
|
||||
double level = mAudioInputTester.getPeakLevel(i);
|
||||
mVolumeBars[i].setVolume((float) level);
|
||||
}
|
||||
}
|
||||
|
||||
void resetVolumeBars() {
|
||||
for (int i = 0; i < mVolumeBars.length; i++) {
|
||||
if (mVolumeBars[i] == null) break;
|
||||
mVolumeBars[i].setVolume((float) 0.0);
|
||||
}
|
||||
}
|
||||
|
||||
void setMinimumBurstsBeforeRead(int numBursts) {
|
||||
int framesPerBurst = mAudioInputTester.getCurrentAudioStream().getFramesPerBurst();
|
||||
if (framesPerBurst > 0) {
|
||||
setMinimumFramesBeforeRead(numBursts * framesPerBurst);
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void openAudio() throws IOException {
|
||||
if (!isRecordPermissionGranted()){
|
||||
requestRecordPermission();
|
||||
return;
|
||||
}
|
||||
super.openAudio();
|
||||
setMinimumBurstsBeforeRead(mInputMarginBursts);
|
||||
resetVolumeBars();
|
||||
}
|
||||
|
||||
@Override
|
||||
public void stopAudio() {
|
||||
super.stopAudio();
|
||||
resetVolumeBars();
|
||||
}
|
||||
|
||||
private boolean isRecordPermissionGranted() {
|
||||
return (ActivityCompat.checkSelfPermission(this,
|
||||
Manifest.permission.RECORD_AUDIO) == PackageManager.PERMISSION_GRANTED);
|
||||
}
|
||||
|
||||
private void requestRecordPermission(){
|
||||
ActivityCompat.requestPermissions(
|
||||
this,
|
||||
new String[]{Manifest.permission.RECORD_AUDIO},
|
||||
AUDIO_ECHO_REQUEST);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions,
|
||||
@NonNull int[] grantResults) {
|
||||
|
||||
if (AUDIO_ECHO_REQUEST != requestCode) {
|
||||
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
|
||||
return;
|
||||
}
|
||||
|
||||
if (grantResults.length != 1 ||
|
||||
grantResults[0] != PackageManager.PERMISSION_GRANTED) {
|
||||
|
||||
Toast.makeText(getApplicationContext(),
|
||||
getString(R.string.need_record_audio_permission),
|
||||
Toast.LENGTH_SHORT)
|
||||
.show();
|
||||
} else {
|
||||
// Permission was granted
|
||||
try {
|
||||
super.openAudio();
|
||||
} catch (IOException e) {
|
||||
showErrorToast(e.getMessage());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public void setupAGC(int sessionId) {
|
||||
AutomaticGainControl effect = AutomaticGainControl.create(sessionId);
|
||||
}
|
||||
|
||||
public void setupAEC(int sessionId) {
|
||||
AcousticEchoCanceler effect = AcousticEchoCanceler.create(sessionId);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void setupEffects(int sessionId) {
|
||||
setupAEC(sessionId);
|
||||
}
|
||||
|
||||
protected int saveWaveFile(File file) {
|
||||
// Pass filename to native to write WAV file
|
||||
int result = saveWaveFile(file.getAbsolutePath());
|
||||
if (result < 0) {
|
||||
showErrorToast("Save returned " + result);
|
||||
} else {
|
||||
showToast("Saved " + result + " bytes.");
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
String getWaveTag() {
|
||||
return "input";
|
||||
}
|
||||
|
||||
@NonNull
|
||||
private File createFileName() {
|
||||
// Get directory and filename
|
||||
File dir = getExternalFilesDir(Environment.DIRECTORY_MUSIC);
|
||||
return new File(dir, "oboe_" + getWaveTag() + "_" + getTimestampString() + ".wav");
|
||||
}
|
||||
|
||||
public void shareWaveFile() {
|
||||
// Share WAVE file via GMail, Drive or other method.
|
||||
File file = createFileName();
|
||||
int result = saveWaveFile(file);
|
||||
if (result > 0) {
|
||||
Intent sharingIntent = new Intent(android.content.Intent.ACTION_SEND);
|
||||
sharingIntent.setType("audio/wav");
|
||||
String subjectText = file.getName();
|
||||
sharingIntent.putExtra(android.content.Intent.EXTRA_SUBJECT, subjectText);
|
||||
Uri uri = FileProvider.getUriForFile(this,
|
||||
BuildConfig.APPLICATION_ID + ".provider",
|
||||
file);
|
||||
sharingIntent.putExtra(Intent.EXTRA_STREAM, uri);
|
||||
sharingIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
|
||||
startActivity(Intent.createChooser(sharingIntent, "Share WAV using:"));
|
||||
}
|
||||
}
|
||||
|
||||
public void onShareFile(View view) {
|
||||
shareWaveFile();
|
||||
}
|
||||
|
||||
public void onMarginBoxClicked(View view) {
|
||||
RadioButton radioButton = (RadioButton) view;
|
||||
String text = (String) radioButton.getText();
|
||||
mInputMarginBursts = Integer.parseInt(text);
|
||||
setMinimumBurstsBeforeRead(mInputMarginBursts);
|
||||
}
|
||||
}
|
||||
+121
@@ -0,0 +1,121 @@
|
||||
/*
|
||||
* 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.os.Bundle;
|
||||
import android.util.Log;
|
||||
import android.view.View;
|
||||
import android.widget.AdapterView;
|
||||
import android.widget.CheckBox;
|
||||
import android.widget.Spinner;
|
||||
|
||||
import java.io.IOException;
|
||||
|
||||
/**
|
||||
* Test basic output.
|
||||
*/
|
||||
public final class TestOutputActivity extends TestOutputActivityBase {
|
||||
|
||||
public static final int MAX_CHANNEL_BOXES = 8;
|
||||
private CheckBox[] mChannelBoxes;
|
||||
private Spinner mNativeApiSpinner;
|
||||
|
||||
private class NativeApiSpinnerListener implements android.widget.AdapterView.OnItemSelectedListener {
|
||||
@Override
|
||||
public void onItemSelected(AdapterView<?> parent, View view, int pos, long id) {
|
||||
mAudioOutTester.setSignalType(pos);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onNothingSelected(AdapterView<?> parent) {
|
||||
mAudioOutTester.setSignalType(0);
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void inflateActivity() {
|
||||
setContentView(R.layout.activity_test_output);
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void onCreate(Bundle savedInstanceState) {
|
||||
super.onCreate(savedInstanceState);
|
||||
|
||||
updateEnabledWidgets();
|
||||
|
||||
mAudioOutTester = addAudioOutputTester();
|
||||
|
||||
mChannelBoxes = new CheckBox[MAX_CHANNEL_BOXES];
|
||||
int ic = 0;
|
||||
mChannelBoxes[ic++] = (CheckBox) findViewById(R.id.channelBox0);
|
||||
mChannelBoxes[ic++] = (CheckBox) findViewById(R.id.channelBox1);
|
||||
mChannelBoxes[ic++] = (CheckBox) findViewById(R.id.channelBox2);
|
||||
mChannelBoxes[ic++] = (CheckBox) findViewById(R.id.channelBox3);
|
||||
mChannelBoxes[ic++] = (CheckBox) findViewById(R.id.channelBox4);
|
||||
mChannelBoxes[ic++] = (CheckBox) findViewById(R.id.channelBox5);
|
||||
mChannelBoxes[ic++] = (CheckBox) findViewById(R.id.channelBox6);
|
||||
mChannelBoxes[ic++] = (CheckBox) findViewById(R.id.channelBox7);
|
||||
configureChannelBoxes(0);
|
||||
|
||||
|
||||
mNativeApiSpinner = (Spinner) findViewById(R.id.spinnerOutputSignal);
|
||||
mNativeApiSpinner.setOnItemSelectedListener(new NativeApiSpinnerListener());
|
||||
mNativeApiSpinner.setSelection(StreamConfiguration.NATIVE_API_UNSPECIFIED);
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void onStart() {
|
||||
super.onStart();
|
||||
setActivityType(ACTIVITY_TEST_OUTPUT);
|
||||
}
|
||||
|
||||
public void openAudio() throws IOException {
|
||||
super.openAudio();
|
||||
int channelCount = mAudioOutTester.getCurrentAudioStream().getChannelCount();
|
||||
configureChannelBoxes(channelCount);
|
||||
}
|
||||
|
||||
private void configureChannelBoxes(int channelCount) {
|
||||
for (int i = 0; i < mChannelBoxes.length; i++) {
|
||||
mChannelBoxes[i].setChecked(i < channelCount);
|
||||
mChannelBoxes[i].setEnabled(i < channelCount);
|
||||
}
|
||||
}
|
||||
|
||||
public void startAudio() {
|
||||
super.startAudio();
|
||||
mAudioOutTester.setToneType(OboeAudioOutputStream.TONE_TYPE_SINE);
|
||||
mAudioOutTester.setEnabled(true);
|
||||
}
|
||||
|
||||
public void stopAudio() {
|
||||
mAudioOutTester.setEnabled(false);
|
||||
super.stopAudio();
|
||||
}
|
||||
|
||||
public void closeAudio() {
|
||||
configureChannelBoxes(0);
|
||||
super.closeAudio();
|
||||
}
|
||||
|
||||
public void onChannelBoxClicked(View view) {
|
||||
CheckBox checkBox = (CheckBox) view;
|
||||
String text = (String) checkBox.getText();
|
||||
int channelIndex = Integer.parseInt(text);
|
||||
mAudioOutTester.setChannelEnabled(channelIndex, checkBox.isChecked());
|
||||
}
|
||||
}
|
||||
+90
@@ -0,0 +1,90 @@
|
||||
/*
|
||||
* 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.media.audiofx.Equalizer;
|
||||
import android.media.audiofx.PresetReverb;
|
||||
import android.util.Log;
|
||||
import android.widget.SeekBar;
|
||||
import android.widget.TextView;
|
||||
|
||||
import java.io.IOException;
|
||||
|
||||
|
||||
abstract class TestOutputActivityBase extends TestAudioActivity {
|
||||
AudioOutputTester mAudioOutTester;
|
||||
|
||||
private BufferSizeView mBufferSizeView;
|
||||
private WorkloadView mWorkloadView;
|
||||
|
||||
@Override boolean isOutput() { return true; }
|
||||
|
||||
@Override
|
||||
protected void resetConfiguration() {
|
||||
super.resetConfiguration();
|
||||
mAudioOutTester.reset();
|
||||
}
|
||||
|
||||
protected void findAudioCommon() {
|
||||
super.findAudioCommon();
|
||||
mBufferSizeView = (BufferSizeView) findViewById(R.id.buffer_size_view);
|
||||
mWorkloadView = (WorkloadView) findViewById(R.id.workload_view);
|
||||
}
|
||||
|
||||
@Override
|
||||
public AudioOutputTester addAudioOutputTester() {
|
||||
AudioOutputTester audioOutTester = super.addAudioOutputTester();
|
||||
mBufferSizeView.setAudioOutTester(audioOutTester);
|
||||
mWorkloadView.setAudioStreamTester(audioOutTester);
|
||||
return audioOutTester;
|
||||
}
|
||||
|
||||
|
||||
@Override
|
||||
public void openAudio() throws IOException {
|
||||
super.openAudio();
|
||||
if (mBufferSizeView != null) {
|
||||
mBufferSizeView.updateBufferSize();
|
||||
}
|
||||
}
|
||||
|
||||
// TODO Add editor
|
||||
public void setupEqualizer(int sessionId) {
|
||||
Equalizer equalizer = new Equalizer(0, sessionId);
|
||||
int numBands = equalizer.getNumberOfBands();
|
||||
Log.d(TAG, "numBands " + numBands);
|
||||
for (short band = 0; band < numBands; band++) {
|
||||
String msg = "band " + band
|
||||
+ ", center = " + equalizer.getCenterFreq(band)
|
||||
+ ", level = " + equalizer.getBandLevel(band);
|
||||
Log.d(TAG, msg);
|
||||
equalizer.setBandLevel(band, (short)40);
|
||||
}
|
||||
|
||||
equalizer.setBandLevel((short) 1, (short) 300);
|
||||
}
|
||||
|
||||
public void setupReverb(int sessionId) {
|
||||
PresetReverb effect = new PresetReverb(0, sessionId);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void setupEffects(int sessionId) {
|
||||
// setupEqualizer(sessionId);
|
||||
// setupReverb(sessionId);
|
||||
}
|
||||
}
|
||||
+77
@@ -0,0 +1,77 @@
|
||||
/*
|
||||
* 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.content.Context;
|
||||
import android.content.res.Resources;
|
||||
import android.content.res.TypedArray;
|
||||
import android.graphics.Canvas;
|
||||
import android.graphics.Color;
|
||||
import android.graphics.Paint;
|
||||
import android.util.AttributeSet;
|
||||
import android.view.View;
|
||||
|
||||
public class VolumeBarView extends View {
|
||||
|
||||
private Paint mBarPaint;
|
||||
private int mCurrentWidth;
|
||||
private int mCurrentHeight;
|
||||
private Paint mBackgroundPaint;
|
||||
private float mVolume;
|
||||
|
||||
public VolumeBarView(Context context, AttributeSet attrs) {
|
||||
super(context, attrs);
|
||||
// TypedArray a = context.getTheme().obtainStyledAttributes(attrs,
|
||||
// R.styleable.VolumeBarView, 0, 0);
|
||||
init();
|
||||
}
|
||||
|
||||
private void init() {
|
||||
mBarPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
|
||||
mBarPaint.setColor(Color.RED);
|
||||
mBarPaint.setStyle(Paint.Style.FILL);
|
||||
|
||||
mBackgroundPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
|
||||
mBackgroundPaint.setColor(Color.LTGRAY);
|
||||
mBackgroundPaint.setStyle(Paint.Style.FILL);
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void onSizeChanged(int w, int h, int oldw, int oldh) {
|
||||
mCurrentWidth = w;
|
||||
mCurrentHeight = h;
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void onDraw(Canvas canvas) {
|
||||
super.onDraw(canvas);
|
||||
canvas.drawRect(0.0f, 0.0f, mCurrentWidth,
|
||||
mCurrentHeight, mBackgroundPaint);
|
||||
float scaledVolume = mVolume * mCurrentWidth;
|
||||
canvas.drawRect(0.0f, 0.0f, scaledVolume,
|
||||
mCurrentHeight, mBarPaint);
|
||||
}
|
||||
|
||||
/**
|
||||
* Set volume between 0.0 and 1.0
|
||||
*/
|
||||
public void setVolume(float volume) {
|
||||
mVolume = volume;
|
||||
postInvalidate();
|
||||
}
|
||||
|
||||
}
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user