diff --git a/build.gradle b/build.gradle index 2868633..82c3d97 100644 --- a/build.gradle +++ b/build.gradle @@ -8,7 +8,7 @@ buildscript { mavenCentral() } dependencies { - classpath 'com.android.tools.build:gradle:7.1.3' + classpath 'com.android.tools.build:gradle:8.0.0' } } allprojects { @@ -33,6 +33,9 @@ android { } productFlavors { } + android { + namespace 'com.kaytat.simpleprotocolplayer' + } } dependencies { diff --git a/gradle/.gitattributes b/gradle/.gitattributes new file mode 100644 index 0000000..097f9f9 --- /dev/null +++ b/gradle/.gitattributes @@ -0,0 +1,9 @@ +# +# https://help.github.com/articles/dealing-with-line-endings/ +# +# Linux start script should use lf +/gradlew text eol=lf + +# These are Windows script files and should use crlf +*.bat text eol=crlf + diff --git a/gradle/.gitignore b/gradle/.gitignore new file mode 100644 index 0000000..1b6985c --- /dev/null +++ b/gradle/.gitignore @@ -0,0 +1,5 @@ +# Ignore Gradle project-specific cache directory +.gradle + +# Ignore Gradle build output directory +build diff --git a/gradle/build.gradle b/gradle/build.gradle new file mode 100644 index 0000000..77713a0 --- /dev/null +++ b/gradle/build.gradle @@ -0,0 +1,6 @@ +/* + * This file was generated by the Gradle 'init' task. + * + * This is a general purpose Gradle build. + * Learn more about Gradle by exploring our samples at https://docs.gradle.org/8.1/samples + */ diff --git a/gradle/gradle/wrapper/gradle-wrapper.jar b/gradle/gradle/wrapper/gradle-wrapper.jar new file mode 100644 index 0000000..c1962a7 Binary files /dev/null and b/gradle/gradle/wrapper/gradle-wrapper.jar differ diff --git a/gradle/gradle/wrapper/gradle-wrapper.properties b/gradle/gradle/wrapper/gradle-wrapper.properties new file mode 100644 index 0000000..0c85a1f --- /dev/null +++ b/gradle/gradle/wrapper/gradle-wrapper.properties @@ -0,0 +1,6 @@ +distributionBase=GRADLE_USER_HOME +distributionPath=wrapper/dists +distributionUrl=https\://services.gradle.org/distributions/gradle-8.1-bin.zip +networkTimeout=10000 +zipStoreBase=GRADLE_USER_HOME +zipStorePath=wrapper/dists diff --git a/gradle/gradlew b/gradle/gradlew new file mode 100755 index 0000000..aeb74cb --- /dev/null +++ b/gradle/gradlew @@ -0,0 +1,245 @@ +#!/bin/sh + +# +# Copyright © 2015-2021 the original authors. +# +# 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 +# +# https://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. +# + +############################################################################## +# +# Gradle start up script for POSIX generated by Gradle. +# +# Important for running: +# +# (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is +# noncompliant, but you have some other compliant shell such as ksh or +# bash, then to run this script, type that shell name before the whole +# command line, like: +# +# ksh Gradle +# +# Busybox and similar reduced shells will NOT work, because this script +# requires all of these POSIX shell features: +# * functions; +# * expansions «$var», «${var}», «${var:-default}», «${var+SET}», +# «${var#prefix}», «${var%suffix}», and «$( cmd )»; +# * compound commands having a testable exit status, especially «case»; +# * various built-in commands including «command», «set», and «ulimit». +# +# Important for patching: +# +# (2) This script targets any POSIX shell, so it avoids extensions provided +# by Bash, Ksh, etc; in particular arrays are avoided. +# +# The "traditional" practice of packing multiple parameters into a +# space-separated string is a well documented source of bugs and security +# problems, so this is (mostly) avoided, by progressively accumulating +# options in "$@", and eventually passing that to Java. +# +# Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS, +# and GRADLE_OPTS) rely on word-splitting, this is performed explicitly; +# see the in-line comments for details. +# +# There are tweaks for specific operating systems such as AIX, CygWin, +# Darwin, MinGW, and NonStop. +# +# (3) This script is generated from the Groovy template +# https://github.com/gradle/gradle/blob/HEAD/subprojects/plugins/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt +# within the Gradle project. +# +# You can find Gradle at https://github.com/gradle/gradle/. +# +############################################################################## + +# Attempt to set APP_HOME + +# Resolve links: $0 may be a link +app_path=$0 + +# Need this for daisy-chained symlinks. +while + APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path + [ -h "$app_path" ] +do + ls=$( ls -ld "$app_path" ) + link=${ls#*' -> '} + case $link in #( + /*) app_path=$link ;; #( + *) app_path=$APP_HOME$link ;; + esac +done + +# This is normally unused +# shellcheck disable=SC2034 +APP_BASE_NAME=${0##*/} +APP_HOME=$( cd "${APP_HOME:-./}" && pwd -P ) || exit + +# Use the maximum available, or set MAX_FD != -1 to use that value. +MAX_FD=maximum + +warn () { + echo "$*" +} >&2 + +die () { + echo + echo "$*" + echo + exit 1 +} >&2 + +# 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 ;; #( + MSYS* | 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" && ! "$darwin" && ! "$nonstop" ; then + case $MAX_FD in #( + max*) + # In POSIX sh, ulimit -H is undefined. That's why the result is checked to see if it worked. + # shellcheck disable=SC3045 + MAX_FD=$( ulimit -H -n ) || + warn "Could not query maximum file descriptor limit" + esac + case $MAX_FD in #( + '' | soft) :;; #( + *) + # In POSIX sh, ulimit -n is undefined. That's why the result is checked to see if it worked. + # shellcheck disable=SC3045 + ulimit -n "$MAX_FD" || + warn "Could not set maximum file descriptor limit to $MAX_FD" + esac +fi + +# Collect all arguments for the java command, stacking in reverse order: +# * args from the command line +# * the main class name +# * -classpath +# * -D...appname settings +# * --module-path (only if needed) +# * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables. + +# For Cygwin or MSYS, switch paths to Windows format before running java +if "$cygwin" || "$msys" ; then + APP_HOME=$( cygpath --path --mixed "$APP_HOME" ) + CLASSPATH=$( cygpath --path --mixed "$CLASSPATH" ) + + JAVACMD=$( cygpath --unix "$JAVACMD" ) + + # Now convert the arguments - kludge to limit ourselves to /bin/sh + for arg do + if + case $arg in #( + -*) false ;; # don't mess with options #( + /?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath + [ -e "$t" ] ;; #( + *) false ;; + esac + then + arg=$( cygpath --path --ignore --mixed "$arg" ) + fi + # Roll the args list around exactly as many times as the number of + # args, so each arg winds up back in the position where it started, but + # possibly modified. + # + # NB: a `for` loop captures its iteration list before it begins, so + # changing the positional parameters here affects neither the number of + # iterations, nor the values presented in `arg`. + shift # remove old arg + set -- "$@" "$arg" # push replacement arg + done +fi + + +# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"' + +# Collect all arguments for the java command; +# * $DEFAULT_JVM_OPTS, $JAVA_OPTS, and $GRADLE_OPTS can contain fragments of +# shell script including quotes and variable substitutions, so put them in +# double quotes to make sure that they get re-expanded; and +# * put everything else in single quotes, so that it's not re-expanded. + +set -- \ + "-Dorg.gradle.appname=$APP_BASE_NAME" \ + -classpath "$CLASSPATH" \ + org.gradle.wrapper.GradleWrapperMain \ + "$@" + +# Stop when "xargs" is not available. +if ! command -v xargs >/dev/null 2>&1 +then + die "xargs is not available" +fi + +# Use "xargs" to parse quoted args. +# +# With -n1 it outputs one arg per line, with the quotes and backslashes removed. +# +# In Bash we could simply go: +# +# readarray ARGS < <( xargs -n1 <<<"$var" ) && +# set -- "${ARGS[@]}" "$@" +# +# but POSIX shell has neither arrays nor command substitution, so instead we +# post-process each arg (as a line of input to sed) to backslash-escape any +# character that might be a shell metacharacter, then use eval to reverse +# that process (while maintaining the separation between arguments), and wrap +# the whole thing up as a single "set" statement. +# +# This will of course break if any of these variables contains a newline or +# an unmatched quote. +# + +eval "set -- $( + printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" | + xargs -n1 | + sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' | + tr '\n' ' ' + )" '"$@"' + +exec "$JAVACMD" "$@" diff --git a/gradle/gradlew.bat b/gradle/gradlew.bat new file mode 100644 index 0000000..93e3f59 --- /dev/null +++ b/gradle/gradlew.bat @@ -0,0 +1,92 @@ +@rem +@rem Copyright 2015 the original author or authors. +@rem +@rem Licensed under the Apache License, Version 2.0 (the "License"); +@rem you may not use this file except in compliance with the License. +@rem You may obtain a copy of the License at +@rem +@rem https://www.apache.org/licenses/LICENSE-2.0 +@rem +@rem Unless required by applicable law or agreed to in writing, software +@rem distributed under the License is distributed on an "AS IS" BASIS, +@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +@rem See the License for the specific language governing permissions and +@rem limitations under the License. +@rem + +@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=. +@rem This is normally unused +set APP_BASE_NAME=%~n0 +set APP_HOME=%DIRNAME% + +@rem Resolve any "." and ".." in APP_HOME to make it shorter. +for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi + +@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="-Xmx64m" "-Xms64m" + +@rem Find java.exe +if defined JAVA_HOME goto findJavaFromJavaHome + +set JAVA_EXE=java.exe +%JAVA_EXE% -version >NUL 2>&1 +if %ERRORLEVEL% equ 0 goto execute + +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 execute + +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 + +: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 %* + +:end +@rem End local scope for the variables with windows NT shell +if %ERRORLEVEL% equ 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! +set EXIT_CODE=%ERRORLEVEL% +if %EXIT_CODE% equ 0 set EXIT_CODE=1 +if not ""=="%GRADLE_EXIT_CONSOLE%" exit %EXIT_CODE% +exit /b %EXIT_CODE% + +:mainEnd +if "%OS%"=="Windows_NT" endlocal + +:omega diff --git a/gradle/settings.gradle b/gradle/settings.gradle new file mode 100644 index 0000000..5bd3c39 --- /dev/null +++ b/gradle/settings.gradle @@ -0,0 +1,10 @@ +/* + * This file was generated by the Gradle 'init' task. + * + * The settings file is used to specify which projects to include in your build. + * + * Detailed information about configuring a multi-project build in Gradle can be found + * in the user manual at https://docs.gradle.org/8.1/userguide/multi_project_builds.html + */ + +rootProject.name = 'gradle' diff --git a/gradle/wrapper/gradle-wrapper.jar b/gradle/wrapper/gradle-wrapper.jar index 2322723..c1962a7 100644 Binary files a/gradle/wrapper/gradle-wrapper.jar and b/gradle/wrapper/gradle-wrapper.jar differ diff --git a/gradle/wrapper/gradle-wrapper.properties b/gradle/wrapper/gradle-wrapper.properties index 4d601f1..37aef8d 100644 --- a/gradle/wrapper/gradle-wrapper.properties +++ b/gradle/wrapper/gradle-wrapper.properties @@ -1,6 +1,6 @@ -#Sat Oct 29 16:24:45 PDT 2016 distributionBase=GRADLE_USER_HOME distributionPath=wrapper/dists +distributionUrl=https\://services.gradle.org/distributions/gradle-8.1.1-bin.zip +networkTimeout=10000 zipStoreBase=GRADLE_USER_HOME zipStorePath=wrapper/dists -distributionUrl=https\://services.gradle.org/distributions/gradle-7.2-all.zip diff --git a/gradlew b/gradlew index 935f1eb..aeb74cb 100755 --- a/gradlew +++ b/gradlew @@ -1,164 +1,245 @@ -#!/usr/bin/env bash +#!/bin/sh + +# +# Copyright © 2015-2021 the original authors. +# +# 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 +# +# https://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. +# ############################################################################## -## -## Gradle start up script for UN*X -## +# +# Gradle start up script for POSIX generated by Gradle. +# +# Important for running: +# +# (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is +# noncompliant, but you have some other compliant shell such as ksh or +# bash, then to run this script, type that shell name before the whole +# command line, like: +# +# ksh Gradle +# +# Busybox and similar reduced shells will NOT work, because this script +# requires all of these POSIX shell features: +# * functions; +# * expansions «$var», «${var}», «${var:-default}», «${var+SET}», +# «${var#prefix}», «${var%suffix}», and «$( cmd )»; +# * compound commands having a testable exit status, especially «case»; +# * various built-in commands including «command», «set», and «ulimit». +# +# Important for patching: +# +# (2) This script targets any POSIX shell, so it avoids extensions provided +# by Bash, Ksh, etc; in particular arrays are avoided. +# +# The "traditional" practice of packing multiple parameters into a +# space-separated string is a well documented source of bugs and security +# problems, so this is (mostly) avoided, by progressively accumulating +# options in "$@", and eventually passing that to Java. +# +# Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS, +# and GRADLE_OPTS) rely on word-splitting, this is performed explicitly; +# see the in-line comments for details. +# +# There are tweaks for specific operating systems such as AIX, CygWin, +# Darwin, MinGW, and NonStop. +# +# (3) This script is generated from the Groovy template +# https://github.com/gradle/gradle/blob/HEAD/subprojects/plugins/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt +# within the Gradle project. +# +# You can find Gradle at https://github.com/gradle/gradle/. +# ############################################################################## -# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. -DEFAULT_JVM_OPTS="" +# Attempt to set APP_HOME + +# Resolve links: $0 may be a link +app_path=$0 + +# Need this for daisy-chained symlinks. +while + APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path + [ -h "$app_path" ] +do + ls=$( ls -ld "$app_path" ) + link=${ls#*' -> '} + case $link in #( + /*) app_path=$link ;; #( + *) app_path=$APP_HOME$link ;; + esac +done -APP_NAME="Gradle" -APP_BASE_NAME=$(basename "$0") +# This is normally unused +# shellcheck disable=SC2034 +APP_BASE_NAME=${0##*/} +APP_HOME=$( cd "${APP_HOME:-./}" && pwd -P ) || exit # Use the maximum available, or set MAX_FD != -1 to use that value. -MAX_FD="maximum" +MAX_FD=maximum -warn() { - echo "$*" -} +warn () { + echo "$*" +} >&2 -die() { - echo - echo "$*" - echo - exit 1 -} +die () { + echo + echo "$*" + echo + exit 1 +} >&2 # OS specific support (must be 'true' or 'false'). cygwin=false msys=false darwin=false -case "$(uname)" in -CYGWIN*) - cygwin=true - ;; -Darwin*) - darwin=true - ;; -MINGW*) - msys=true - ;; +nonstop=false +case "$( uname )" in #( + CYGWIN* ) cygwin=true ;; #( + Darwin* ) darwin=true ;; #( + MSYS* | MINGW* ) msys=true ;; #( + NONSTOP* ) nonstop=true ;; esac -# For Cygwin, ensure paths are in UNIX format before anything is touched. -if $cygwin; then - [ -n "$JAVA_HOME" ] && JAVA_HOME=$(cygpath --unix "$JAVA_HOME") -fi - -# 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\")/" >&- -APP_HOME="$(pwd -P)" -cd "$SAVED" >&- - 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 +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 + 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. + 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" ]; 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 +if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then + case $MAX_FD in #( + max*) + # In POSIX sh, ulimit -H is undefined. That's why the result is checked to see if it worked. + # shellcheck disable=SC3045 + MAX_FD=$( ulimit -H -n ) || + warn "Could not query maximum file descriptor limit" + esac + case $MAX_FD in #( + '' | soft) :;; #( + *) + # In POSIX sh, ulimit -n is undefined. That's why the result is checked to see if it worked. + # shellcheck disable=SC3045 + ulimit -n "$MAX_FD" || + warn "Could not set maximum file descriptor limit to $MAX_FD" + esac 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\"" +# Collect all arguments for the java command, stacking in reverse order: +# * args from the command line +# * the main class name +# * -classpath +# * -D...appname settings +# * --module-path (only if needed) +# * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables. + +# For Cygwin or MSYS, switch paths to Windows format before running java +if "$cygwin" || "$msys" ; then + APP_HOME=$( cygpath --path --mixed "$APP_HOME" ) + CLASSPATH=$( cygpath --path --mixed "$CLASSPATH" ) + + JAVACMD=$( cygpath --unix "$JAVACMD" ) + + # Now convert the arguments - kludge to limit ourselves to /bin/sh + for arg do + if + case $arg in #( + -*) false ;; # don't mess with options #( + /?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath + [ -e "$t" ] ;; #( + *) false ;; + esac + then + arg=$( cygpath --path --ignore --mixed "$arg" ) + fi + # Roll the args list around exactly as many times as the number of + # args, so each arg winds up back in the position where it started, but + # possibly modified. + # + # NB: a `for` loop captures its iteration list before it begins, so + # changing the positional parameters here affects neither the number of + # iterations, nor the values presented in `arg`. + shift # remove old arg + set -- "$@" "$arg" # push replacement arg + done 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") - - # 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 -# Split up the JVM_OPTS And GRADLE_OPTS values into an array, following the shell quoting and substitution rules -function splitJvmOpts() { - JVM_OPTS=("$@") -} -eval splitJvmOpts $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS -JVM_OPTS[${#JVM_OPTS[*]}]="-Dorg.gradle.appname=$APP_BASE_NAME" +# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"' + +# Collect all arguments for the java command; +# * $DEFAULT_JVM_OPTS, $JAVA_OPTS, and $GRADLE_OPTS can contain fragments of +# shell script including quotes and variable substitutions, so put them in +# double quotes to make sure that they get re-expanded; and +# * put everything else in single quotes, so that it's not re-expanded. + +set -- \ + "-Dorg.gradle.appname=$APP_BASE_NAME" \ + -classpath "$CLASSPATH" \ + org.gradle.wrapper.GradleWrapperMain \ + "$@" + +# Stop when "xargs" is not available. +if ! command -v xargs >/dev/null 2>&1 +then + die "xargs is not available" +fi -exec "$JAVACMD" "${JVM_OPTS[@]}" -classpath "$CLASSPATH" org.gradle.wrapper.GradleWrapperMain "$@" +# Use "xargs" to parse quoted args. +# +# With -n1 it outputs one arg per line, with the quotes and backslashes removed. +# +# In Bash we could simply go: +# +# readarray ARGS < <( xargs -n1 <<<"$var" ) && +# set -- "${ARGS[@]}" "$@" +# +# but POSIX shell has neither arrays nor command substitution, so instead we +# post-process each arg (as a line of input to sed) to backslash-escape any +# character that might be a shell metacharacter, then use eval to reverse +# that process (while maintaining the separation between arguments), and wrap +# the whole thing up as a single "set" statement. +# +# This will of course break if any of these variables contains a newline or +# an unmatched quote. +# + +eval "set -- $( + printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" | + xargs -n1 | + sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' | + tr '\n' ' ' + )" '"$@"' + +exec "$JAVACMD" "$@" diff --git a/gradlew.bat b/gradlew.bat index aec9973..6689b85 100644 --- a/gradlew.bat +++ b/gradlew.bat @@ -1,4 +1,20 @@ -@if "%DEBUG%" == "" @echo off +@rem +@rem Copyright 2015 the original author or authors. +@rem +@rem Licensed under the Apache License, Version 2.0 (the "License"); +@rem you may not use this file except in compliance with the License. +@rem You may obtain a copy of the License at +@rem +@rem https://www.apache.org/licenses/LICENSE-2.0 +@rem +@rem Unless required by applicable law or agreed to in writing, software +@rem distributed under the License is distributed on an "AS IS" BASIS, +@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +@rem See the License for the specific language governing permissions and +@rem limitations under the License. +@rem + +@if "%DEBUG%"=="" @echo off @rem ########################################################################## @rem @rem Gradle startup script for Windows @@ -8,20 +24,24 @@ @rem Set local scope for the variables with windows NT shell if "%OS%"=="Windows_NT" setlocal -@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= - set DIRNAME=%~dp0 -if "%DIRNAME%" == "" set DIRNAME=. +if "%DIRNAME%"=="" set DIRNAME=. +@rem This is normally unused set APP_BASE_NAME=%~n0 set APP_HOME=%DIRNAME% +@rem Resolve any "." and ".." in APP_HOME to make it shorter. +for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi + +@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="-Xmx64m" "-Xms64m" + @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 +if %ERRORLEVEL% equ 0 goto execute echo. echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. @@ -35,7 +55,7 @@ goto fail set JAVA_HOME=%JAVA_HOME:"=% set JAVA_EXE=%JAVA_HOME%/bin/java.exe -if exist "%JAVA_EXE%" goto init +if exist "%JAVA_EXE%" goto execute echo. echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% @@ -45,44 +65,26 @@ echo location of your Java installation. goto fail -:init -@rem Get command-line arguments, handling Windowz variants - -if not "%OS%" == "Windows_NT" goto win9xME_args -if "%@eval[2+2]" == "4" goto 4NT_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=%* -goto execute - -:4NT_args -@rem Get arguments from the 4NT Shell from JP Software -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% +"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %* :end @rem End local scope for the variables with windows NT shell -if "%ERRORLEVEL%"=="0" goto mainEnd +if %ERRORLEVEL% equ 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 +set EXIT_CODE=%ERRORLEVEL% +if %EXIT_CODE% equ 0 set EXIT_CODE=1 +if not ""=="%GRADLE_EXIT_CONSOLE%" exit %EXIT_CODE% +exit /b %EXIT_CODE% :mainEnd if "%OS%"=="Windows_NT" endlocal diff --git a/src/main/java/com/kaytat/simpleprotocolplayer/BufferToAudioTrackThread.java b/src/main/java/com/kaytat/simpleprotocolplayer/BufferToAudioTrackThread.java index f2daed8..8a972b3 100644 --- a/src/main/java/com/kaytat/simpleprotocolplayer/BufferToAudioTrackThread.java +++ b/src/main/java/com/kaytat/simpleprotocolplayer/BufferToAudioTrackThread.java @@ -43,12 +43,28 @@ public BufferToAudioTrackThread(WorkerThreadPair syncObject, public void run() { Log.i(TAG, "start"); + int floatLengthBuffer = syncObject.bytesPerAudioPacket / 4; + float[] floatArray = new float[floatLengthBuffer]; + byte[] audioData = new byte[syncObject.bytesPerAudioPacket]; + if(!syncObject.useFloatAudio){ + floatArray = null; + } mTrack.play(); try { while (running) { - mTrack.write(syncObject.dataQueue.take(), 0, - syncObject.bytesPerAudioPacket); + audioData = syncObject.dataQueue.take(); + if (syncObject.useFloatAudio) { + for(int i = 0; i < floatLengthBuffer; i++){ + floatArray[i] = Float.intBitsToFloat((audioData[i * 4] & 0xFF) + | ((audioData[i * 4 + 1] & 0xFF) << 8) + | ((audioData[i * 4 + 2] & 0xFF) << 16) + | ((audioData[i * 4 + 3] & 0xFF) << 24)); + } + mTrack.write(floatArray, 0, floatArray.length, AudioTrack.WRITE_NON_BLOCKING); + } else { + mTrack.write(audioData, 0, audioData.length); + } } } catch (Exception e) { Log.e(TAG, "exception:" + e); diff --git a/src/main/java/com/kaytat/simpleprotocolplayer/MainActivity.java b/src/main/java/com/kaytat/simpleprotocolplayer/MainActivity.java index 5777bd7..b7cf0ec 100644 --- a/src/main/java/com/kaytat/simpleprotocolplayer/MainActivity.java +++ b/src/main/java/com/kaytat/simpleprotocolplayer/MainActivity.java @@ -73,13 +73,14 @@ public class MainActivity extends AppCompatActivity implements OnClickListener { ArrayList audioPortList; ArrayAdapter audioPortAdapter; - int sampleRate; + int sampleRate, bitDepth; boolean stereo; int bufferMs; boolean retry; boolean usePerformanceMode; boolean useMinBuffer; - + boolean useRndis; + boolean autoConnectOnStart; Button playButton; Button stopButton; @@ -89,6 +90,94 @@ private enum NetworkConnection { NON_WIFI_CONNECTED } + public void loadPrefs(){ + SharedPreferences myPrefs = getSharedPreferences("myPrefs", MODE_PRIVATE); + + ipAddrList = getListFromPrefs(myPrefs, IP_JSON_PREF, IP_PREF); + ipAddrAdapter = + new NoFilterArrayAdapter<>(this, android.R.layout.simple_list_item_1, + ipAddrList); + ipAddrText.setAdapter(ipAddrAdapter); + ipAddrText.setThreshold(1); + if (ipAddrList.size() != 0) { + ipAddrText.setText(ipAddrList.get(0)); + } + + if (!isEmpty(ipAddrText)) { + getWindow().setSoftInputMode( + WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN); + } + + audioPortList = getListFromPrefs(myPrefs, PORT_JSON_PREF, PORT_PREF); + audioPortAdapter = + new NoFilterArrayAdapter<>(this, android.R.layout.simple_list_item_1, + audioPortList); + audioPortText.setAdapter(audioPortAdapter); + audioPortText.setThreshold(1); + if (audioPortList.size() != 0) { + audioPortText.setText(audioPortList.get(0)); + } + + // These hard-coded values should match the defaults in the strings array + Resources res = getResources(); + + sampleRate = myPrefs.getInt(RATE_PREF, MusicService.DEFAULT_SAMPLE_RATE); + String rateString = Integer.toString(sampleRate); + String[] sampleRateStrings = res.getStringArray(R.array.sampleRates); + for (int i = 0; i < sampleRateStrings.length; i++) { + if (sampleRateStrings[i].contains(rateString)) { + Spinner sampleRateSpinner = findViewById(R.id.spinnerSampleRate); + sampleRateSpinner.setSelection(i); + break; + } + } + + bitDepth = myPrefs.getInt(BITDEPTH_PREF, MusicService.DEFAULT_BIT_DEPTH); + String bitDepthString = Integer.toString(bitDepth); + String[] bitDepthStrings = res.getStringArray(R.array.bitDepths); + for (int i = 0; i < bitDepthStrings.length; i++) { + if (bitDepthStrings[i].contains(bitDepthString)) { + Spinner bitDepthSpinner = findViewById(R.id.spinnerBitDepth); + bitDepthSpinner.setSelection(i); + break; + } + } + + stereo = myPrefs.getBoolean(STEREO_PREF, MusicService.DEFAULT_STEREO); + String[] stereoStrings = res.getStringArray(R.array.stereo); + Spinner stereoSpinner = findViewById(R.id.stereo); + String stereoKey = getResources().getString(R.string.stereoKey); + if (stereoStrings[0].contains(stereoKey) == stereo) { + stereoSpinner.setSelection(0); + } else { + stereoSpinner.setSelection(1); + } + + bufferMs = myPrefs.getInt(BUFFER_MS_PREF, MusicService.DEFAULT_BUFFER_MS); + Log.d(TAG, "bufferMs:" + bufferMs); + EditText e = findViewById(R.id.editTextBufferSize); + e.setText(String.format(Locale.getDefault(), "%d", bufferMs)); + + retry = myPrefs.getBoolean(RETRY_PREF, MusicService.DEFAULT_RETRY); + ((CheckBox) findViewById(R.id.checkBoxRetry)).setChecked(retry); + Log.d(TAG, "retry:" + retry); + + usePerformanceMode = myPrefs.getBoolean(USE_PERFORMANCE_MODE_PREF, MusicService.DEFAULT_USE_PERFORMANCE_MODE); + ((CheckBox) findViewById(R.id.checkBoxUsePerformanceMode)).setChecked(usePerformanceMode); + Log.d(TAG, "usePerformanceMode:" + usePerformanceMode); + + useMinBuffer = myPrefs.getBoolean(USE_MIN_BUFFER_PREF, MusicService.DEFAULT_USE_MIN_BUFFER); + ((CheckBox) findViewById(R.id.checkBoxUseMinBuffer)).setChecked(useMinBuffer); + Log.d(TAG, "useMinBuffer:" + useMinBuffer); + + useRndis = myPrefs.getBoolean(USE_RNDIS, MusicService.DEFAULT_USE_RNDIS); + ((CheckBox) findViewById(R.id.checkBoxUseRndis)).setChecked(useRndis); + Log.d(TAG, "useRndis:" + useRndis); + + autoConnectOnStart = myPrefs.getBoolean(AUTOCONNECT_ON_START, MusicService.DEFAULT_AUTOCONNECT_ON_START); + ((CheckBox) findViewById(R.id.checkBoxAutoConnectOnStart)).setChecked(autoConnectOnStart); + Log.d(TAG, "autoConnectOnStart:" + autoConnectOnStart); + } /** * Called when the activity is first created. Here, we simply set the * event listeners and start the background service ({@link MusicService}) @@ -131,6 +220,12 @@ public void onCreate(Bundle savedInstanceState) { } }); + + SharedPreferences myPrefs = getSharedPreferences("myPrefs", MODE_PRIVATE); + loadPrefs(); + if(autoConnectOnStart){ + play(); + } } /** @@ -145,11 +240,14 @@ public void onCreate(Bundle savedInstanceState) { static final String PORT_JSON_PREF = "PORT_JSON_PREF"; static final String RATE_PREF = "RATE"; + static final String BITDEPTH_PREF = "BITDEPTH"; static final String STEREO_PREF = "STEREO"; static final String BUFFER_MS_PREF = "BUFFER_MS"; static final String RETRY_PREF = "RETRY"; + static final String USE_RNDIS = "USE_RNDIS"; static final String USE_PERFORMANCE_MODE_PREF = "USE_PERFORMANCE_MODE"; static final String USE_MIN_BUFFER_PREF = "USE_MIN_BUFFER"; + static final String AUTOCONNECT_ON_START = "AUTOCONNECT_ON_START"; ArrayList getListFromPrefs(SharedPreferences prefs, String keyJson, String keySingle) { @@ -227,10 +325,13 @@ private void savePrefs() { prefsEditor.putBoolean(STEREO_PREF, stereo); prefsEditor.putInt(RATE_PREF, sampleRate); + prefsEditor.putInt(BITDEPTH_PREF, bitDepth); prefsEditor.putInt(BUFFER_MS_PREF, bufferMs); prefsEditor.putBoolean(RETRY_PREF, retry); prefsEditor.putBoolean(USE_PERFORMANCE_MODE_PREF, usePerformanceMode); prefsEditor.putBoolean(USE_MIN_BUFFER_PREF, useMinBuffer); + prefsEditor.putBoolean(USE_RNDIS, useRndis); + prefsEditor.putBoolean(AUTOCONNECT_ON_START, autoConnectOnStart); prefsEditor.apply(); // Update adapters @@ -279,73 +380,7 @@ protected void publishResults(CharSequence arg0, @Override public void onResume() { super.onResume(); - SharedPreferences myPrefs = getSharedPreferences("myPrefs", MODE_PRIVATE); - - ipAddrList = getListFromPrefs(myPrefs, IP_JSON_PREF, IP_PREF); - ipAddrAdapter = - new NoFilterArrayAdapter<>(this, android.R.layout.simple_list_item_1, - ipAddrList); - ipAddrText.setAdapter(ipAddrAdapter); - ipAddrText.setThreshold(1); - if (ipAddrList.size() != 0) { - ipAddrText.setText(ipAddrList.get(0)); - } - - if (!isEmpty(ipAddrText)) { - getWindow().setSoftInputMode( - WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN); - } - - audioPortList = getListFromPrefs(myPrefs, PORT_JSON_PREF, PORT_PREF); - audioPortAdapter = - new NoFilterArrayAdapter<>(this, android.R.layout.simple_list_item_1, - audioPortList); - audioPortText.setAdapter(audioPortAdapter); - audioPortText.setThreshold(1); - if (audioPortList.size() != 0) { - audioPortText.setText(audioPortList.get(0)); - } - - // These hard-coded values should match the defaults in the strings array - Resources res = getResources(); - - sampleRate = myPrefs.getInt(RATE_PREF, MusicService.DEFAULT_SAMPLE_RATE); - String rateString = Integer.toString(sampleRate); - String[] sampleRateStrings = res.getStringArray(R.array.sampleRates); - for (int i = 0; i < sampleRateStrings.length; i++) { - if (sampleRateStrings[i].contains(rateString)) { - Spinner sampleRateSpinner = findViewById(R.id.spinnerSampleRate); - sampleRateSpinner.setSelection(i); - break; - } - } - - stereo = myPrefs.getBoolean(STEREO_PREF, MusicService.DEFAULT_STEREO); - String[] stereoStrings = res.getStringArray(R.array.stereo); - Spinner stereoSpinner = findViewById(R.id.stereo); - String stereoKey = getResources().getString(R.string.stereoKey); - if (stereoStrings[0].contains(stereoKey) == stereo) { - stereoSpinner.setSelection(0); - } else { - stereoSpinner.setSelection(1); - } - - bufferMs = myPrefs.getInt(BUFFER_MS_PREF, MusicService.DEFAULT_BUFFER_MS); - Log.d(TAG, "bufferMs:" + bufferMs); - EditText e = findViewById(R.id.editTextBufferSize); - e.setText(String.format(Locale.getDefault(), "%d", bufferMs)); - - retry = myPrefs.getBoolean(RETRY_PREF, MusicService.DEFAULT_RETRY); - ((CheckBox) findViewById(R.id.checkBoxRetry)).setChecked(retry); - Log.d(TAG, "retry:" + retry); - - usePerformanceMode = myPrefs.getBoolean(USE_PERFORMANCE_MODE_PREF, MusicService.DEFAULT_USE_PERFORMANCE_MODE); - ((CheckBox) findViewById(R.id.checkBoxUsePerformanceMode)).setChecked(usePerformanceMode); - Log.d(TAG, "usePerformanceMode:" + usePerformanceMode); - - useMinBuffer = myPrefs.getBoolean(USE_MIN_BUFFER_PREF, MusicService.DEFAULT_USE_MIN_BUFFER); - ((CheckBox) findViewById(R.id.checkBoxUseMinBuffer)).setChecked(useMinBuffer); - Log.d(TAG, "useMinBuffer:" + useMinBuffer); + loadPrefs(); } @Override @@ -366,10 +401,7 @@ public boolean onOptionsItemSelected(MenuItem item) { } } - public void onClick(View target) { - // Send the correct intent to the MusicService, according to the - // button that was clicked - if (target == playButton) { + public void play () { switch (getNetworkConnection()) { case NOT_CONNECTED: Toast.makeText(getApplicationContext(), "No network connectivity.", @@ -432,6 +464,21 @@ public void onClick(View target) { return; } + // Extract bit dephts + Spinner bitDepthSpinner = findViewById(R.id.spinnerBitDepth); + String bitDepthStr = String.valueOf(bitDepthSpinner.getSelectedItem()); + String[] bitDepthSplit = bitDepthStr.split(" "); + try { + bitDepth = Integer.parseInt(bitDepthSplit[0]); + Log.i(TAG, "bit depth:" + bitDepth); + i.putExtra(MusicService.DATA_BIT_DEPTH, bitDepth); + } catch (NumberFormatException nfe) { + Log.e(TAG, "Invalid bit depth:" + nfe); + Toast.makeText(getApplicationContext(), "Invalid bit depth", + Toast.LENGTH_SHORT).show(); + return; + } + // Extract stereo/mono setting Spinner stereoSpinner = findViewById(R.id.stereo); String stereoSettingString = @@ -470,9 +517,26 @@ public void onClick(View target) { Log.d(TAG, "useMinBuffer:" + useMinBuffer); i.putExtra(MusicService.DATA_USE_MIN_BUFFER, useMinBuffer); + // Get the useRndis checkbox + useRndis = ((CheckBox) findViewById(R.id.checkBoxUseRndis)).isChecked(); + Log.d(TAG, "useRndis:" + useRndis); + i.putExtra(MusicService.DATA_USE_RNDIS, useRndis); + + // Get the autoConnectOnStart checkbox + autoConnectOnStart = ((CheckBox) findViewById(R.id.checkBoxAutoConnectOnStart)).isChecked(); + Log.d(TAG, "autoConnectOnStart:" + autoConnectOnStart); + i.putExtra(MusicService.DATA_AUTO_CONNECT_ON_START, autoConnectOnStart); + // Save current settings savePrefs(); startService(i); + } + + public void onClick(View target) { + // Send the correct intent to the MusicService, according to the + // button that was clicked + if (target == playButton) { + play(); } else if (target == stopButton) { hideKb(); diff --git a/src/main/java/com/kaytat/simpleprotocolplayer/MusicService.java b/src/main/java/com/kaytat/simpleprotocolplayer/MusicService.java index 80b404b..9aa83b3 100644 --- a/src/main/java/com/kaytat/simpleprotocolplayer/MusicService.java +++ b/src/main/java/com/kaytat/simpleprotocolplayer/MusicService.java @@ -42,12 +42,15 @@ public class MusicService extends Service implements MusicFocusable { static final String TAG = "SimpleProtocol"; static final int DEFAULT_AUDIO_PORT = 12345; - static final int DEFAULT_SAMPLE_RATE = 44100; + static final int DEFAULT_SAMPLE_RATE = 48000; + static final int DEFAULT_BIT_DEPTH = 32; static final boolean DEFAULT_STEREO = true; static final int DEFAULT_BUFFER_MS = 50; static final boolean DEFAULT_RETRY = false; + static final boolean DEFAULT_USE_RNDIS = false; static final boolean DEFAULT_USE_PERFORMANCE_MODE = false; static final boolean DEFAULT_USE_MIN_BUFFER = false; + static final boolean DEFAULT_AUTOCONNECT_ON_START = false; // These are the Intent actions that we are prepared to handle. Notice // that the fact these constants exist in our class is a mere @@ -62,11 +65,14 @@ public class MusicService extends Service implements MusicFocusable { public static final String DATA_IP_ADDRESS = "ip_addr"; public static final String DATA_AUDIO_PORT = "audio_port"; public static final String DATA_SAMPLE_RATE = "sample_rate"; + public static final String DATA_BIT_DEPTH = "bit_depth"; public static final String DATA_STEREO = "stereo"; public static final String DATA_BUFFER_MS = "buffer_ms"; public static final String DATA_RETRY = "retry"; public static final String DATA_USE_PERFORMANCE_MODE = "use_performance_mode"; public static final String DATA_USE_MIN_BUFFER = "use_min_buffer"; + public static final String DATA_USE_RNDIS = "use_rndis"; + public static final String DATA_AUTO_CONNECT_ON_START = "auto_connect_on_start"; // The volume we set the media player to when we lose audio focus, but // are allowed to reduce the volume instead of stopping playback. @@ -158,11 +164,13 @@ void processPlayRequest(Intent i) { i.getStringExtra(DATA_IP_ADDRESS), i.getIntExtra(DATA_AUDIO_PORT, DEFAULT_AUDIO_PORT), i.getIntExtra(DATA_SAMPLE_RATE, DEFAULT_SAMPLE_RATE), + i.getIntExtra(DATA_BIT_DEPTH, DEFAULT_BIT_DEPTH), i.getBooleanExtra(DATA_STEREO, DEFAULT_STEREO), i.getIntExtra(DATA_BUFFER_MS, DEFAULT_BUFFER_MS), i.getBooleanExtra(DATA_RETRY, DEFAULT_RETRY), i.getBooleanExtra(DATA_USE_PERFORMANCE_MODE, DEFAULT_USE_PERFORMANCE_MODE), - i.getBooleanExtra(DATA_USE_MIN_BUFFER, DEFAULT_USE_MIN_BUFFER)); + i.getBooleanExtra(DATA_USE_MIN_BUFFER, DEFAULT_USE_MIN_BUFFER), + i.getBooleanExtra(DATA_USE_RNDIS, DEFAULT_USE_RNDIS)); } void processStopRequest() { @@ -254,17 +262,19 @@ void playStream( String serverAddr, int serverPort, int sample_rate, + int bitDepth, boolean stereo, int buffer_ms, boolean retry, boolean usePerformanceMode, - boolean useMinBuffer) { + boolean useMinBuffer, + boolean useRndis) { mState = State.Stopped; relaxResources(); workers.add(new WorkerThreadPair(this, serverAddr, serverPort, - sample_rate, stereo, buffer_ms, retry, usePerformanceMode, useMinBuffer)); + sample_rate, bitDepth, stereo, buffer_ms, retry, usePerformanceMode, useMinBuffer, useRndis)); mWifiLock.acquire(); diff --git a/src/main/java/com/kaytat/simpleprotocolplayer/NetworkReadThread.java b/src/main/java/com/kaytat/simpleprotocolplayer/NetworkReadThread.java index bb82a08..10f6168 100644 --- a/src/main/java/com/kaytat/simpleprotocolplayer/NetworkReadThread.java +++ b/src/main/java/com/kaytat/simpleprotocolplayer/NetworkReadThread.java @@ -21,6 +21,13 @@ import java.io.DataInputStream; import java.io.IOException; import java.net.Socket; +import java.net.SocketException; +import java.net.NetworkInterface; +import java.util.Enumeration; +import androidx.annotation.Nullable; +import android.widget.Toast; +import java.net.InterfaceAddress; +import java.net.InetAddress; /** * Worker thread reads data from the network @@ -35,12 +42,14 @@ class NetworkReadThread extends ThreadStoppable { }; final WorkerThreadPair syncObject; - final String ipAddr; + String ipAddr; final int port; + final boolean useRndis; final boolean attemptConnectionRetry; final byte[][] dataBuffer; final int numBuffers; int bufferIndex; + MusicService musicService; // socket timeout at 5 seconds static final int SOCKET_TIMEOUT = 5 * 1000; @@ -50,12 +59,16 @@ public NetworkReadThread( String ipAddr, int port, boolean attemptConnectionRetry, - String debugTag) { + String debugTag, + boolean useRndis, + MusicService musicService) { this.TAG = debugTag; this.setName(debugTag); this.syncObject = syncObject; this.ipAddr = ipAddr; + this.useRndis = useRndis; this.port = port; + this.musicService = musicService; this.attemptConnectionRetry = attemptConnectionRetry; // since we use BlockingQueue to pass data @@ -70,6 +83,50 @@ public NetworkReadThread( } } + @Nullable + public String checkIPRange(String ip) { + String[] parts = ip.split("\\."); + String baseIP = parts[0] + "." + parts[1] + "." + parts[2] + "."; + int end = Integer.parseInt(parts[3]); + for (int i = 1; i <= 254; i++) { + String ipAddress = baseIP + i; + if(end != i){ + try { + InetAddress inet = InetAddress.getByName(ipAddress); + if (inet.isReachable(1)) { + return ipAddress; + } + } catch (IOException e) { + Toast.makeText(musicService.getApplicationContext(), "Error while checking IP: " + ipAddress + ": " + e.getMessage(), Toast.LENGTH_SHORT).show(); + } + } + } + return null; + } + + @Nullable + public String getTetheredGatewayIp() { + try { + Enumeration networkInterfaces = NetworkInterface.getNetworkInterfaces(); + while (networkInterfaces.hasMoreElements()) { + NetworkInterface nic = networkInterfaces.nextElement(); + if (nic.isUp() && nic.getName().contains("rndis")) { + for ( InterfaceAddress interfaceAddress : nic.getInterfaceAddresses()){ + String ip = interfaceAddress.getAddress().getHostAddress(); + if(ip.indexOf('%') == -1){ // Skips IPv6 IP + return checkIPRange(ip); + } + } + } + } + } + catch (Exception e) { + e.printStackTrace(); + Toast.makeText(musicService.getApplicationContext(), e.getMessage(), Toast.LENGTH_SHORT).show(); + } + return null; + } + @Override public void run() { Log.i(TAG, "start"); @@ -130,6 +187,12 @@ public boolean runImpl() { try { // Create the TCP socket and setup some parameters + if(useRndis){ + String tetherIp = getTetheredGatewayIp(); + if(tetherIp != null){ + ipAddr = tetherIp; + } + } socket = new Socket(ipAddr, port); DataInputStream is = new DataInputStream(socket.getInputStream()); socket.setSoTimeout(SOCKET_TIMEOUT); diff --git a/src/main/java/com/kaytat/simpleprotocolplayer/WorkerThreadPair.java b/src/main/java/com/kaytat/simpleprotocolplayer/WorkerThreadPair.java index 2779b1c..124e5d4 100644 --- a/src/main/java/com/kaytat/simpleprotocolplayer/WorkerThreadPair.java +++ b/src/main/java/com/kaytat/simpleprotocolplayer/WorkerThreadPair.java @@ -38,11 +38,26 @@ public class WorkerThreadPair { private final BufferToAudioTrackThread audioThread; private final NetworkReadThread networkThread; final AudioTrack audioTrack; - + boolean useFloatAudio; + static int bitDepthToFormat (int bitDepth){ + switch(bitDepth) { + case 8: + return AudioFormat.ENCODING_PCM_8BIT; + case 16: + return AudioFormat.ENCODING_PCM_16BIT; + case 24: + return AudioFormat.ENCODING_PCM_24BIT_PACKED; + case 32: + return AudioFormat.ENCODING_PCM_FLOAT; + } + Log.d(TAG, "error bit depth to format conversion: " + bitDepth); + return 0; + } public WorkerThreadPair(MusicService musicService, String serverAddr, - int serverPort, int sampleRate, boolean stereo, int requestedBufferMs, - boolean retry, boolean usePerformanceMode, boolean useMinBuffer) { + int serverPort, int sampleRate, int bitDepth, boolean stereo, int requestedBufferMs, + boolean retry, boolean usePerformanceMode, boolean useMinBuffer, boolean useRndis) { this.musicService = musicService; + this.useFloatAudio = bitDepth == 32; int channelMask = stereo ? AudioFormat.CHANNEL_OUT_STEREO : AudioFormat.CHANNEL_OUT_MONO; @@ -53,7 +68,7 @@ public WorkerThreadPair(MusicService musicService, String serverAddr, int audioTrackMinBuffer = AudioTrack .getMinBufferSize(sampleRate, channelMask, - AudioFormat.ENCODING_PCM_16BIT); + bitDepthToFormat(bitDepth)); Log.d(TAG, "audioTrackMinBuffer:" + audioTrackMinBuffer); if (useMinBuffer) { @@ -64,25 +79,25 @@ public WorkerThreadPair(MusicService musicService, String serverAddr, requestedBufferMs = MusicService.DEFAULT_BUFFER_MS; } bytesPerAudioPacket = - calcBytesPerAudioPacket(sampleRate, stereo, requestedBufferMs); + calcBytesPerAudioPacket(sampleRate, bitDepth, stereo, requestedBufferMs); } Log.d(TAG, "useMinBuffer:" + useMinBuffer); // The agreement here is that audioTrack will be shutdown by the helper - audioTrack = buildAudioTrack(sampleRate, channelMask, audioTrackMinBuffer, + audioTrack = buildAudioTrack(sampleRate, bitDepth, channelMask, audioTrackMinBuffer, usePerformanceMode); Log.d(TAG, "usePerformanceMode:" + usePerformanceMode); audioThread = new BufferToAudioTrackThread(this, "audio:" + serverAddr + ":" + serverPort); networkThread = new NetworkReadThread(this, serverAddr, serverPort, retry, - "net:" + serverAddr + ":" + serverPort); + "net:" + serverAddr + ":" + serverPort, useRndis, musicService); audioThread.start(); networkThread.start(); } - static AudioTrack buildAudioTrack(int sampleRate, int channelMask, + static AudioTrack buildAudioTrack(int sampleRate, int bitDepth, int channelMask, int audioTrackMinBuffer, boolean usePerformanceMode) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { // PERFORMANCE_MODE_LOW_LATENCY was only added in O (API 26). @@ -94,7 +109,7 @@ static AudioTrack buildAudioTrack(int sampleRate, int channelMask, .setContentType(AudioAttributes.CONTENT_TYPE_MUSIC) .build()) .setAudioFormat(new AudioFormat.Builder() - .setEncoding(AudioFormat.ENCODING_PCM_16BIT) + .setEncoding(bitDepthToFormat(bitDepth)) .setSampleRate(sampleRate) .setChannelMask(channelMask) .build()) @@ -108,16 +123,15 @@ static AudioTrack buildAudioTrack(int sampleRate, int channelMask, } else { return new AudioTrack(AudioManager.STREAM_MUSIC, sampleRate, - channelMask, AudioFormat.ENCODING_PCM_16BIT, audioTrackMinBuffer, + channelMask, bitDepthToFormat(bitDepth), audioTrackMinBuffer, AudioTrack.MODE_STREAM); } } - static int calcBytesPerAudioPacket(int sampleRate, boolean stereo, + static int calcBytesPerAudioPacket(int sampleRate, int bitDepth, boolean stereo, int requestedBufferMs) { - // Assume 16 bits per sample - int bytesPerSecond = sampleRate * 2; + int bytesPerSecond = sampleRate * (bitDepth / 8); if (stereo) { bytesPerSecond *= 2; } diff --git a/src/main/res/layout/main.xml b/src/main/res/layout/main.xml index 8cced4c..0a691af 100644 --- a/src/main/res/layout/main.xml +++ b/src/main/res/layout/main.xml @@ -123,6 +123,36 @@ android:entries="@array/sampleRates" /> + + + + + + + + + + + android:text="@string/useRndis" /> @@ -259,24 +290,86 @@ android:layout_centerHorizontal="true" android:visibility="invisible" /> + + android:text="@string/usePerformanceMode" /> + + + + + + + + + + + + + + + + + + + Notice Notice Sample Rate + Bit Depth Mono/Stereo 11025 12000 22050 24000 - 44100 (Default) - 48000 + 44100 + 48000 (Default) + 96000 + 192000 + 384000 + + + 8 + 16 (Default) + 24 + 32 (float) Mono @@ -42,8 +52,10 @@ Stereo Buffer size (in ms) Buffer size + Use USB Tethering (rndis) Enable network retries Performance mode Min AudioTrack buffer + Auto connect on app start Error