sonivox: Fix global buffer overflow in WT_InterpolateNoLoop am: 8bfcd9c03a am: 471c3bc380 am: 393f0fee8a am: 3310782787 am: bb6bb3aba8 am: 7f5ca1faec
Original change: https://googleplex-android-review.googlesource.com/c/platform/external/sonivox/+/15249031
Change-Id: I958bdf07d90be0ac053cb599fa2a3a2de19ce6e4
diff --git a/Android.bp b/Android.bp
index 0f8f3a4..8cc4146 100644
--- a/Android.bp
+++ b/Android.bp
@@ -1 +1,18 @@
+package {
+ default_applicable_licenses: ["external_sonivox_license"],
+}
+
+// Added automatically by a large-scale-change
+// See: http://go/android-license-faq
+license {
+ name: "external_sonivox_license",
+ visibility: [":__subpackages__"],
+ license_kinds: [
+ "SPDX-license-identifier-Apache-2.0",
+ ],
+ license_text: [
+ "NOTICE",
+ ],
+}
+
subdirs = ["arm-wt-22k"]
diff --git a/METADATA b/METADATA
new file mode 100644
index 0000000..d97975c
--- /dev/null
+++ b/METADATA
@@ -0,0 +1,3 @@
+third_party {
+ license_type: NOTICE
+}
diff --git a/OWNERS b/OWNERS
index 5c49fbc..8333c2f 100644
--- a/OWNERS
+++ b/OWNERS
@@ -1,4 +1,3 @@
-# Default code reviewers picked from top 3 or more developers.
-# Please update this list if you find better candidates.
-marcone@google.com
-wjia@google.com
+# owners for external/sonivox
+include platform/frameworks/av:/media/janitors/codec_OWNERS
+essick@google.com
diff --git a/arm-wt-22k/Android.bp b/arm-wt-22k/Android.bp
index bf45b0d..c05443b 100644
--- a/arm-wt-22k/Android.bp
+++ b/arm-wt-22k/Android.bp
@@ -1,3 +1,20 @@
+package {
+ default_applicable_licenses: ["external_sonivox_arm-wt-22k_license"],
+}
+
+// Added automatically by a large-scale-change
+// See: http://go/android-license-faq
+license {
+ name: "external_sonivox_arm-wt-22k_license",
+ visibility: [":__subpackages__"],
+ license_kinds: [
+ "SPDX-license-identifier-Apache-2.0",
+ ],
+ license_text: [
+ "NOTICE",
+ ],
+}
+
cc_defaults {
name: "libsonivox-defaults",
srcs: [
@@ -70,6 +87,14 @@
"liblog",
],
+ host_supported: true,
+
+ target: {
+ darwin: {
+ enabled: false,
+ },
+ },
+
arch: {
arm: {
instruction_set: "arm",
@@ -86,22 +111,15 @@
// In order to use #include instead of .include
"-xassembler-with-cpp",
- "-Wa,--defsym,SAMPLE_RATE_22050=1",
- "-Wa,--defsym,STEREO_OUTPUT=1",
- "-Wa,--defsym,FILTER_ENABLED=1",
- "-Wa,--defsym,SAMPLES_16_BIT=1",
+ "-DSAMPLE_RATE_22050=1",
+ "-DSTEREO_OUTPUT=1",
+ "-DFILTER_ENABLED=1",
+ "-DSAMPLES_16_BIT=1",
],
cflags: [
"-DNATIVE_EAS_KERNEL",
],
-
- // .s files not ported for Clang assembler yet.
- clang_asflags: ["-no-integrated-as"],
- },
- arm64: {
- // .s files not ported for Clang assembler yet.
- clang_asflags: ["-no-integrated-as"],
},
},
sanitize: {
@@ -135,5 +153,3 @@
"-DJET_INTERFACE",
],
}
-
-
diff --git a/arm-wt-22k/lib_src/ARM-E_filter_gnu.s b/arm-wt-22k/lib_src/ARM-E_filter_gnu.s
index 859d9a4..c4ffd55 100644
--- a/arm-wt-22k/lib_src/ARM-E_filter_gnu.s
+++ b/arm-wt-22k/lib_src/ARM-E_filter_gnu.s
@@ -55,7 +55,6 @@
@RestoreRegs RLIST {r4-r10, pc}
- .func WT_VoiceFilter
WT_VoiceFilter:
STMFD sp!, {r4-r10, lr}
@@ -112,7 +111,7 @@
MOV z1, tmp1, ASR #14 @ shift result to low word
- LDRGTSH tmp0, [pBuffer, #NEXT_OUTPUT_PCM] @ fetch next sample
+ LDRSHGT tmp0, [pBuffer, #NEXT_OUTPUT_PCM] @ fetch next sample
STRH z1, [pBuffer], #NEXT_OUTPUT_PCM @ write back to buffer
@@ -129,6 +128,5 @@
LDMFD sp!,{r4-r10, lr}
BX lr
- .endfunc
.end
diff --git a/arm-wt-22k/lib_src/ARM-E_interpolate_loop_gnu.s b/arm-wt-22k/lib_src/ARM-E_interpolate_loop_gnu.s
index 2529e93..59ab0fd 100644
--- a/arm-wt-22k/lib_src/ARM-E_interpolate_loop_gnu.s
+++ b/arm-wt-22k/lib_src/ARM-E_interpolate_loop_gnu.s
@@ -56,7 +56,6 @@
@SaveRegs RLIST {r4-r11,lr}
@RestoreRegs RLIST {r4-r11,pc}
- .func WT_Interpolate
WT_Interpolate:
STMFD sp!,{r4-r11,lr}
@@ -81,13 +80,15 @@
SUBS tmp0, pPhaseAccum, pLoopEnd @ check for loop end
ADDGE pPhaseAccum, pLoopStart, tmp0 @ loop back to start
- .ifdef SAMPLES_8_BIT
+ #ifdef SAMPLES_8_BIT
LDRSB tmp0, [pPhaseAccum] @ tmp0 = x0
LDRSB tmp1, [pPhaseAccum, #1] @ tmp1 = x1
- .else
+ #elif SAMPLES_16_BIT
LDRSH tmp0, [pPhaseAccum] @ tmp0 = x0
LDRSH tmp1, [pPhaseAccum, #2] @ tmp1 = x1
- .endif
+ #else
+ #error Must define one of SAMPLES_8_BIT or SAMPLES_16_BIT.
+ #endif
ADD tmp2, phaseIncrement, phaseFrac @ increment pointer here to avoid pipeline stall
@@ -101,11 +102,13 @@
@ saturation operation should take in the filter before scaling back to
@ 16 bits or the signal path should be increased to 18 bits or more.
- .ifdef SAMPLES_8_BIT
+ #ifdef SAMPLES_8_BIT
MOV tmp0, tmp0, LSL #6 @ boost 8-bit signal by 36dB
- .else
+ #elif SAMPLES_16_BIT
MOV tmp0, tmp0, ASR #2 @ reduce 16-bit signal by 12dB
- .endif
+ #else
+ #error Must define one of SAMPLES_8_BIT or SAMPLES_16_BIT.
+ #endif
ADD tmp1, tmp0, tmp1, ASR #(NUM_EG1_FRAC_BITS-6) @ tmp1 = tmp0 + (tmp1 >> (15-6))
@ = x0 + f * (x1 - x0) == interpolated result
@@ -126,6 +129,5 @@
LDMFD sp!,{r4-r11,lr}
BX lr
- .endfunc
.end
diff --git a/arm-wt-22k/lib_src/ARM-E_interpolate_noloop_gnu.s b/arm-wt-22k/lib_src/ARM-E_interpolate_noloop_gnu.s
index 55a0ba7..baa6f7a 100644
--- a/arm-wt-22k/lib_src/ARM-E_interpolate_noloop_gnu.s
+++ b/arm-wt-22k/lib_src/ARM-E_interpolate_noloop_gnu.s
@@ -54,7 +54,6 @@
@SaveRegs RLIST {r4-r9,lr}
@RestoreRegs RLIST {r4-r9,pc}
- .func WT_InterpolateNoLoop
WT_InterpolateNoLoop:
STMFD sp!, {r4-r9,lr}
@@ -73,13 +72,15 @@
InterpolationLoop:
- .ifdef SAMPLES_8_BIT
+ #ifdef SAMPLES_8_BIT
LDRSB tmp0, [pPhaseAccum] @ tmp0 = x0
LDRSB tmp1, [pPhaseAccum, #1] @ tmp1 = x1
- .else
+ #elif SAMPLES_16_BIT
LDRSH tmp0, [pPhaseAccum] @ tmp0 = x0
LDRSH tmp1, [pPhaseAccum, #2] @ tmp1 = x1
- .endif
+ #else
+ #error Must define one of SAMPLES_8_BIT or SAMPLES_16_BIT.
+ #endif
ADD tmp2, phaseIncrement, phaseFrac @ increment pointer here to avoid pipeline stall
@@ -93,11 +94,13 @@
@ saturation operation should take in the filter before scaling back to
@ 16 bits or the signal path should be increased to 18 bits or more.
- .ifdef SAMPLES_8_BIT
+ #ifdef SAMPLES_8_BIT
MOV tmp0, tmp0, LSL #6 @ boost 8-bit signal by 36dB
- .else
+ #elif SAMPLES_16_BIT
MOV tmp0, tmp0, ASR #2 @ reduce 16-bit signal by 12dB
- .endif
+ #else
+ #error Must define one of SAMPLES_8_BIT or SAMPLES_16_BIT.
+ #endif
ADD tmp1, tmp0, tmp1, ASR #(NUM_EG1_FRAC_BITS-6) @ tmp1 = tmp0 + (tmp1 >> (15-6))
@ = x0 + f * (x1 - x0) == interpolated result
@@ -125,6 +128,5 @@
LDMFD sp!,{r4-r9,lr}
BX lr
- .endfunc
.end
diff --git a/arm-wt-22k/lib_src/ARM-E_mastergain_gnu.s b/arm-wt-22k/lib_src/ARM-E_mastergain_gnu.s
index f443fbb..e53bb99 100644
--- a/arm-wt-22k/lib_src/ARM-E_mastergain_gnu.s
+++ b/arm-wt-22k/lib_src/ARM-E_mastergain_gnu.s
@@ -40,7 +40,6 @@
.arm
.text
- .func SynthMasterGain
SynthMasterGain:
.global SynthMasterGain @ allow other files to use this function
@@ -103,7 +102,5 @@
@*****************************************************************************
- .endfunc @ end of function/procedure
-
.end @ end of assembly code
diff --git a/arm-wt-22k/lib_src/ARM-E_voice_gain_gnu.s b/arm-wt-22k/lib_src/ARM-E_voice_gain_gnu.s
index 6ca28b2..9e1fcce 100644
--- a/arm-wt-22k/lib_src/ARM-E_voice_gain_gnu.s
+++ b/arm-wt-22k/lib_src/ARM-E_voice_gain_gnu.s
@@ -49,22 +49,21 @@
numSamples .req r9
- .if STEREO_OUTPUT
+ #if STEREO_OUTPUT
gainIncLeft .req r7
gainIncRight .req r8
gainLeft .req r10
gainRight .req r11
- .else
+ #else
gainIncrement .req r7
gain .req r8
- .endif
+ #endif
@ register context for local variables
@SaveRegs RLIST {r4-r11,lr}
@RestoreRegs RLIST {r4-r11,pc}
- .func WT_VoiceGain
WT_VoiceGain:
STMFD sp!, {r4-r11,lr}
@@ -80,7 +79,7 @@
@ due to storage and computational dependencies.
@----------------------------------------------------------------
- .if STEREO_OUTPUT
+ #if STEREO_OUTPUT
LDR tmp0, [pWTFrame, #m_prevGain]
LDR tmp1, [pWTFrame, #m_gainTarget]
@@ -132,7 +131,7 @@
@----------------------------------------------------------------
@ Mono version
@----------------------------------------------------------------
- .else
+ #else
LDR gain, [pWTFrame, #m_prevGain]
MOV gain, gain, LSL #(NUM_MIXER_GUARD_BITS + 4)
@@ -156,11 +155,10 @@
SUBS numSamples, numSamples, #1
BGT MonoGainLoop
- .endif @end Mono version
+ #endif @end Mono version
LDMFD sp!,{r4-r11,lr}
BX lr
- .endfunc
.end
diff --git a/arm-wt-22k/lib_src/ARM_synth_constants_gnu.inc b/arm-wt-22k/lib_src/ARM_synth_constants_gnu.inc
index c0f8df3..213944e 100644
--- a/arm-wt-22k/lib_src/ARM_synth_constants_gnu.inc
+++ b/arm-wt-22k/lib_src/ARM_synth_constants_gnu.inc
@@ -12,45 +12,45 @@
@****************************************************************
- .ifdef SAMPLE_RATE_8000
+ #ifdef SAMPLE_RATE_8000
.equ SYNTH_UPDATE_PERIOD_IN_BITS, 5
.equ BUFFER_SIZE_IN_MONO_SAMPLES, 32
- .endif
+ #endif
- .ifdef SAMPLE_RATE_16000
+ #ifdef SAMPLE_RATE_16000
.equ SYNTH_UPDATE_PERIOD_IN_BITS, 6
.equ BUFFER_SIZE_IN_MONO_SAMPLES, 64
- .endif
+ #endif
- .ifdef SAMPLE_RATE_20000
+ #ifdef SAMPLE_RATE_20000
.equ SYNTH_UPDATE_PERIOD_IN_BITS, 7
.equ BUFFER_SIZE_IN_MONO_SAMPLES, 128
- .endif
+ #endif
- .ifdef SAMPLE_RATE_22050
+ #ifdef SAMPLE_RATE_22050
.equ SYNTH_UPDATE_PERIOD_IN_BITS, 7
.equ BUFFER_SIZE_IN_MONO_SAMPLES, 128
- .endif
+ #endif
- .ifdef SAMPLE_RATE_24000
+ #ifdef SAMPLE_RATE_24000
.equ SYNTH_UPDATE_PERIOD_IN_BITS, 7
.equ BUFFER_SIZE_IN_MONO_SAMPLES, 128
- .endif
+ #endif
- .ifdef SAMPLE_RATE_32000
+ #ifdef SAMPLE_RATE_32000
.equ SYNTH_UPDATE_PERIOD_IN_BITS, 7
.equ BUFFER_SIZE_IN_MONO_SAMPLES, 128
- .endif
+ #endif
- .ifdef SAMPLE_RATE_44100
+ #ifdef SAMPLE_RATE_44100
.equ SYNTH_UPDATE_PERIOD_IN_BITS, 8
.equ BUFFER_SIZE_IN_MONO_SAMPLES, 256
- .endif
+ #endif
- .ifdef SAMPLE_RATE_48000
+ #ifdef SAMPLE_RATE_48000
.equ SYNTH_UPDATE_PERIOD_IN_BITS, 8
.equ BUFFER_SIZE_IN_MONO_SAMPLES, 256
- .endif
+ #endif
@ if the OUTPUT PCM sample is 16-bits, then when using indexed addressing,
@@ -64,13 +64,13 @@
.equ PHASE_FRAC_MASK, 0x7FFF
@ shift for phase accumulator when fraction carries over
- .ifdef SAMPLES_8_BIT
+ #ifdef SAMPLES_8_BIT
.equ NEXT_INPUT_PCM_SHIFT, 0
- .endif
+ #endif
- .ifdef SAMPLES_16_BIT
+ #ifdef SAMPLES_16_BIT
.equ NEXT_INPUT_PCM_SHIFT, 1
- .endif
+ #endif
@****************************************************************************
.equ NUM_MIXER_GUARD_BITS, 4
@@ -90,19 +90,19 @@
@ handle a struct in a compatible fashion. Switching to old fashion EQU
@
- .if FILTER_ENABLED
+ #if FILTER_ENABLED
@**************************************
@ typedef struct s_filter_tag
.equ m_z1, 0
.equ m_z2, 2
- .endif
+ #endif
@**************************************
@ typedef struct s_wt_frame_tag
.equ m_gainTarget, 0
.equ m_phaseIncrement, 4
- .if FILTER_ENABLED
+ #if FILTER_ENABLED
.equ m_k, 8
.equ m_b1, 12
.equ m_b2, 16
@@ -110,12 +110,12 @@
.equ m_pMixBuffer, 24
.equ m_numSamples, 28
.equ m_prevGain, 32
- .else
+ #else
.equ m_pAudioBuffer, 8
.equ m_pMixBuffer, 12
.equ m_numSamples, 16
.equ m_prevGain, 20
- .endif
+ #endif
@**************************************
@@ -125,10 +125,10 @@
.equ m_pPhaseAccum, 8 @ /* points to first sample at start of loop */
.equ m_phaseFrac, 12 @ /* points to first sample at start of loop */
- .if STEREO_OUTPUT
+ #if STEREO_OUTPUT
.equ m_gainLeft, 16 @ /* current gain, left ch */
.equ m_gainRight, 18 @ /* current gain, right ch */
- .endif
+ #endif
@****************************************************************************
diff --git a/arm-wt-22k/lib_src/eas_data.h b/arm-wt-22k/lib_src/eas_data.h
index 4191678..5fe52a9 100644
--- a/arm-wt-22k/lib_src/eas_data.h
+++ b/arm-wt-22k/lib_src/eas_data.h
@@ -31,6 +31,8 @@
#ifndef _EAS_DATA_H
#define _EAS_DATA_H
+#include <stdint.h>
+
#include "eas_types.h"
#include "eas_synthcfg.h"
#include "eas.h"
diff --git a/arm-wt-22k/lib_src/eas_rtttl.c b/arm-wt-22k/lib_src/eas_rtttl.c
index 79d1be8..1419d6d 100644
--- a/arm-wt-22k/lib_src/eas_rtttl.c
+++ b/arm-wt-22k/lib_src/eas_rtttl.c
@@ -439,6 +439,12 @@
/* dotted note */
else if (c == '.')
{
+ /* Number of ticks must not be greater than 32-bits */
+ if ((ticks >> 1) > (INT32_MAX - ticks))
+ {
+ return EAS_ERROR_FILE_FORMAT;
+ }
+
/*lint -e{704} shift for performance */
ticks += ticks >> 1;
}
@@ -490,12 +496,22 @@
}
/* next event is at end of this note */
+ if ((ticks - pData->restTicks) > (INT32_MAX - pData->time))
+ {
+ return EAS_ERROR_FILE_FORMAT;
+ }
pData->time += ticks - pData->restTicks;
}
/* rest */
else
+ {
+ if (ticks > (INT32_MAX - pData->time))
+ {
+ return EAS_ERROR_FILE_FORMAT;
+ }
pData->time += ticks;
+ }
/* event found, return to caller */
break;
diff --git a/arm-wt-22k/lib_src/eas_smf.c b/arm-wt-22k/lib_src/eas_smf.c
index e13e1d8..0e70f01 100644
--- a/arm-wt-22k/lib_src/eas_smf.c
+++ b/arm-wt-22k/lib_src/eas_smf.c
@@ -808,6 +808,10 @@
if ((result = SMF_GetVarLenData(hwInstData, pSMFStream->fileHandle, &ticks)) != EAS_SUCCESS)
return result;
+ /* number of ticks must not exceed 32-bits */
+ if (ticks > (UINT32_MAX - pSMFStream->ticks))
+ return EAS_ERROR_FILE_FORMAT;
+
pSMFStream->ticks += ticks;
return EAS_SUCCESS;
}
diff --git a/arm-wt-22k/lib_src/eas_wtsynth.c b/arm-wt-22k/lib_src/eas_wtsynth.c
index d3ca3af..74f78f5 100644
--- a/arm-wt-22k/lib_src/eas_wtsynth.c
+++ b/arm-wt-22k/lib_src/eas_wtsynth.c
@@ -482,7 +482,7 @@
#endif
/* now account for the fractional portion */
/*lint -e{703} use shift for performance */
- numSamples = (EAS_I32) ((numSamples << NUM_PHASE_FRAC_BITS) - pWTVoice->phaseFrac);
+ numSamples = (numSamples << NUM_PHASE_FRAC_BITS) - (EAS_I32) pWTVoice->phaseFrac;
if (pWTIntFrame->frame.phaseIncrement) {
pWTIntFrame->numSamples = 1 + (numSamples / pWTIntFrame->frame.phaseIncrement);
} else {
diff --git a/test/Android.bp b/test/Android.bp
new file mode 100644
index 0000000..4ce7e85
--- /dev/null
+++ b/test/Android.bp
@@ -0,0 +1,52 @@
+/*
+ * Copyright (C) 2020 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 {
+ // See: http://go/android-license-faq
+ // A large-scale-change added 'default_applicable_licenses' to import
+ // all of the 'license_kinds' from "external_sonivox_license"
+ // to get the below license kinds:
+ // SPDX-license-identifier-Apache-2.0
+ default_applicable_licenses: ["external_sonivox_license"],
+}
+
+cc_test {
+ name: "SonivoxTest",
+ gtest: true,
+
+ srcs: [ "SonivoxTest.cpp" ],
+
+ static_libs: [
+ "libsonivox",
+ ],
+
+ shared_libs: [
+ "liblog",
+ ],
+
+ cflags: [
+ "-Werror",
+ "-Wall",
+ ],
+
+ sanitize: {
+ cfi: false,
+ misc_undefined: [
+ "unsigned-integer-overflow",
+ "signed-integer-overflow",
+ ],
+ },
+}
diff --git a/test/AndroidTest.xml b/test/AndroidTest.xml
new file mode 100644
index 0000000..17a36bd
--- /dev/null
+++ b/test/AndroidTest.xml
@@ -0,0 +1,30 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!-- Copyright (C) 2020 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.
+-->
+<configuration description="Test module config for SonivoxTest unit test">
+ <option name="test-suite-tag" value="SonivoxTest" />
+ <target_preparer class="com.android.tradefed.targetprep.PushFilePreparer">
+ <option name="cleanup" value="true" />
+ <option name="push" value="SonivoxTest->/data/local/tmp/SonivoxTest" />
+ <option name="push-file"
+ key="https://storage.googleapis.com/android_media/external/sonivox/test/SonivoxTestRes-1.0.zip?unzip=true"
+ value="/data/local/tmp/SonivoxTestRes/" />
+ </target_preparer>
+ <test class="com.android.tradefed.testtype.GTest" >
+ <option name="native-test-device-path" value="/data/local/tmp" />
+ <option name="module-name" value="SonivoxTest" />
+ <option name="native-test-flag" value="-P /data/local/tmp/SonivoxTestRes/" />
+ </test>
+</configuration>
diff --git a/test/README.md b/test/README.md
new file mode 100644
index 0000000..9c0eed3
--- /dev/null
+++ b/test/README.md
@@ -0,0 +1,39 @@
+## Media Testing ##
+---
+#### Sonivox Unit Test
+The Sonivox Unit Test Suite validates the Sonivox library available in external/sonivox/
+
+Run the following steps to build the test suite:
+```
+m SonivoxTest
+```
+
+The 32-bit binaries will be created in the following path : ${OUT}/data/nativetest/
+
+The 64-bit binaries will be created in the following path : ${OUT}/data/nativetest64/
+
+To test 64-bit binary push binaries from nativetest64.
+```
+adb push ${OUT}/data/nativetest64/SonivoxTest/SonivoxTest /data/local/tmp/
+```
+
+To test 32-bit binary push binaries from nativetest.
+```
+adb push ${OUT}/data/nativetest/SonivoxTest/SonivoxTest /data/local/tmp/
+```
+
+The resource file for the tests is taken from [here](https://storage.googleapis.com/android_media/external/sonivox/test/SonivoxTestRes-1.0.zip). Download, unzip and push these files into device for testing.
+
+```
+adb push SonivoxTestRes-1.0/. /data/local/tmp/SonivoxTestRes/
+```
+
+usage: SonivoxTest -P \<path_to_res_folder\> -C <remove_output_file>
+```
+adb shell /data/local/tmp/SonivoxTest -P /data/local/tmp/SonivoxTestRes/ -C true
+```
+Alternatively, the test can also be run using atest command.
+
+```
+atest SonivoxTest -- --enable-module-dynamic-download=true
+```
diff --git a/test/SonivoxTest.cpp b/test/SonivoxTest.cpp
new file mode 100644
index 0000000..5894b50
--- /dev/null
+++ b/test/SonivoxTest.cpp
@@ -0,0 +1,368 @@
+/*
+ * Copyright (C) 2020 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 LOG_NDEBUG 0
+#define LOG_TAG "SonivoxTest"
+#include <utils/Log.h>
+
+#include <fcntl.h>
+#include <unistd.h>
+#include <fstream>
+
+#include <libsonivox/eas.h>
+#include <libsonivox/eas_reverb.h>
+
+#include "SonivoxTestEnvironment.h"
+
+#define OUTPUT_FILE "/data/local/tmp/output_midi.pcm"
+
+// number of Sonivox output buffers to aggregate into one MediaBuffer
+static constexpr uint32_t kNumBuffersToCombine = 4;
+static constexpr uint32_t kSeekBeyondPlayTimeOffsetMs = 10;
+
+static SonivoxTestEnvironment *gEnv = nullptr;
+static int readAt(void *, void *, int, int);
+static int getSize(void *);
+
+class SonivoxTest : public ::testing::TestWithParam<tuple</*fileName*/ string,
+ /*audioPlayTimeMs*/ uint32_t,
+ /*totalChannels*/ uint32_t,
+ /*sampleRateHz*/ uint32_t>> {
+ public:
+ SonivoxTest()
+ : mFd(-1),
+ mInputFp(nullptr),
+ mEASDataHandle(nullptr),
+ mEASStreamHandle(nullptr),
+ mPCMBuffer(nullptr),
+ mAudioBuffer(nullptr),
+ mEASConfig(nullptr) {}
+
+ ~SonivoxTest() {
+ if (mInputFp) fclose(mInputFp);
+ if (mFd >= 0) close(mFd);
+ if (mPCMBuffer) {
+ delete[] mPCMBuffer;
+ mPCMBuffer = nullptr;
+ }
+ if (mAudioBuffer) {
+ delete[] mAudioBuffer;
+ mAudioBuffer = nullptr;
+ }
+ if (gEnv->cleanUp()) remove(OUTPUT_FILE);
+ }
+
+ virtual void SetUp() override {
+ tuple<string, uint32_t, uint32_t, uint32_t> params = GetParam();
+ mInputMediaFile = gEnv->getRes() + get<0>(params);
+ mAudioplayTimeMs = get<1>(params);
+ mTotalAudioChannels = get<2>(params);
+ mAudioSampleRate = get<3>(params);
+
+ mFd = open(mInputMediaFile.c_str(), O_RDONLY | O_LARGEFILE);
+ ASSERT_GE(mFd, 0) << "Failed to get the file descriptor for file: " << mInputMediaFile;
+
+ struct stat buf;
+ int8_t err = stat(mInputMediaFile.c_str(), &buf);
+ ASSERT_EQ(err, 0) << "Failed to get information for file: " << mInputMediaFile;
+
+ mBase = 0;
+ mLength = buf.st_size;
+ mEasFile.handle = this;
+ mEasFile.readAt = ::readAt;
+ mEasFile.size = ::getSize;
+
+ EAS_RESULT result = EAS_Init(&mEASDataHandle);
+ ASSERT_EQ(result, EAS_SUCCESS) << "Failed to initialize synthesizer library";
+
+ ASSERT_NE(mEASDataHandle, nullptr) << "Failed to initialize EAS data handle";
+
+ result = EAS_OpenFile(mEASDataHandle, &mEasFile, &mEASStreamHandle);
+ ASSERT_EQ(result, EAS_SUCCESS) << "Failed to open file";
+
+ ASSERT_NE(mEASStreamHandle, nullptr) << "Failed to initialize EAS stream handle";
+
+ result = EAS_Prepare(mEASDataHandle, mEASStreamHandle);
+ ASSERT_EQ(result, EAS_SUCCESS) << "Failed to prepare EAS data and stream handles";
+
+ EAS_I32 playTimeMs;
+ result = EAS_ParseMetaData(mEASDataHandle, mEASStreamHandle, &playTimeMs);
+ ASSERT_EQ(result, EAS_SUCCESS) << "Failed to parse meta data";
+
+ ASSERT_EQ(playTimeMs, mAudioplayTimeMs)
+ << "Invalid audio play time found for file: " << mInputMediaFile;
+
+ EAS_I32 locationMs = -1;
+ /* EAS_ParseMetaData resets the parser to the starting of file */
+ result = EAS_GetLocation(mEASDataHandle, mEASStreamHandle, &locationMs);
+ ASSERT_EQ(result, EAS_SUCCESS) << "Failed to get the location after parsing meta data";
+
+ ASSERT_EQ(locationMs, 0) << "Expected position: 0, found: " << locationMs;
+
+ mEASConfig = EAS_Config();
+ ASSERT_NE(mEASConfig, nullptr) << "Failed to configure the library";
+
+ ASSERT_GT(mEASConfig->mixBufferSize, 0) << "Mix buffer size must be greater than 0";
+
+ ASSERT_GT(mEASConfig->numChannels, 0) << "Number of channels must be greater than 0";
+
+ mPCMBufferSize = sizeof(EAS_PCM) * mEASConfig->mixBufferSize * mEASConfig->numChannels *
+ kNumBuffersToCombine;
+
+ mPCMBuffer = new (std::nothrow) EAS_PCM[mPCMBufferSize];
+ ASSERT_NE(mPCMBuffer, nullptr) << "Failed to allocate a memory of size: " << mPCMBufferSize;
+
+ mAudioBuffer =
+ new (std::nothrow) EAS_PCM[mEASConfig->mixBufferSize * mEASConfig->numChannels];
+ ASSERT_NE(mAudioBuffer, nullptr) << "Failed to allocate a memory of size: "
+ << mEASConfig->mixBufferSize * mEASConfig->numChannels;
+ }
+
+ virtual void TearDown() {
+ EAS_RESULT result;
+ if (mEASDataHandle) {
+ if (mEASStreamHandle) {
+ result = EAS_CloseFile(mEASDataHandle, mEASStreamHandle);
+ ASSERT_EQ(result, EAS_SUCCESS) << "Failed to close audio file/stream";
+ }
+ result = EAS_Shutdown(mEASDataHandle);
+ ASSERT_EQ(result, EAS_SUCCESS)
+ << "Failed to deallocate the resources for synthesizer library";
+ }
+ }
+
+ bool seekToLocation(EAS_I32);
+ bool renderAudio();
+ int readAt(void *buf, int offset, int size);
+ int getSize();
+
+ string mInputMediaFile;
+ uint32_t mAudioplayTimeMs;
+ uint32_t mTotalAudioChannels;
+ uint32_t mAudioSampleRate;
+ off64_t mBase;
+ int64_t mLength;
+ int mFd;
+
+ FILE *mInputFp;
+ EAS_DATA_HANDLE mEASDataHandle;
+ EAS_HANDLE mEASStreamHandle;
+ EAS_FILE mEasFile;
+ EAS_PCM *mPCMBuffer;
+ EAS_PCM *mAudioBuffer;
+ EAS_I32 mPCMBufferSize;
+ const S_EAS_LIB_CONFIG *mEASConfig;
+};
+
+static int readAt(void *handle, void *buffer, int offset, int size) {
+ return ((SonivoxTest *)handle)->readAt(buffer, offset, size);
+}
+
+static int getSize(void *handle) {
+ return ((SonivoxTest *)handle)->getSize();
+}
+
+int SonivoxTest::readAt(void *buffer, int offset, int size) {
+ if (offset > mLength) offset = mLength;
+ lseek(mFd, mBase + offset, SEEK_SET);
+ if (offset + size > mLength) {
+ size = mLength - offset;
+ }
+
+ return read(mFd, buffer, size);
+}
+
+int SonivoxTest::getSize() {
+ return mLength;
+}
+
+bool SonivoxTest::seekToLocation(EAS_I32 locationExpectedMs) {
+ EAS_RESULT result = EAS_Locate(mEASDataHandle, mEASStreamHandle, locationExpectedMs, false);
+ if (result != EAS_SUCCESS) return false;
+
+ // position in milliseconds
+ EAS_I32 locationReceivedMs;
+ result = EAS_GetLocation(mEASDataHandle, mEASStreamHandle, &locationReceivedMs);
+ if (result != EAS_SUCCESS) return false;
+
+ if (locationReceivedMs != locationExpectedMs) return false;
+
+ return true;
+}
+
+bool SonivoxTest::renderAudio() {
+ EAS_I32 count = -1;
+ EAS_PCM *pcm = mAudioBuffer;
+
+ EAS_RESULT result = EAS_Render(mEASDataHandle, pcm, mEASConfig->mixBufferSize, &count);
+ if (result != EAS_SUCCESS) {
+ ALOGE("Failed to render audio");
+ return false;
+ }
+ if (count != mEASConfig->mixBufferSize) {
+ ALOGE("%ld of %ld bytes rendered", count, mEASConfig->mixBufferSize);
+ return false;
+ }
+
+ return true;
+}
+
+TEST_P(SonivoxTest, DecodeTest) {
+ EAS_I32 totalChannels = mEASConfig->numChannels;
+ ASSERT_EQ(totalChannels, mTotalAudioChannels)
+ << "Expected: " << mTotalAudioChannels << " channels, Found: " << totalChannels;
+
+ EAS_I32 sampleRate = mEASConfig->sampleRate;
+ ASSERT_EQ(sampleRate, mAudioSampleRate)
+ << "Expected: " << mAudioSampleRate << " sample rate, Found: " << sampleRate;
+
+ // TODO(b/158231824): Check and verify the output with other parameters present at eas_reverb.h
+ // select reverb preset and enable
+ EAS_RESULT result = EAS_SetParameter(mEASDataHandle, EAS_MODULE_REVERB, EAS_PARAM_REVERB_PRESET,
+ EAS_PARAM_REVERB_CHAMBER);
+ ASSERT_EQ(result, EAS_SUCCESS)
+ << "Failed to set reverberation preset parameter in reverb module";
+
+ result =
+ EAS_SetParameter(mEASDataHandle, EAS_MODULE_REVERB, EAS_PARAM_REVERB_BYPASS, EAS_FALSE);
+ ASSERT_EQ(result, EAS_SUCCESS)
+ << "Failed to set reverberation bypass parameter in reverb module";
+
+ EAS_I32 count;
+ EAS_STATE state;
+
+ FILE *filePtr = fopen(OUTPUT_FILE, "wb");
+ ASSERT_NE(filePtr, nullptr) << "Failed to open file: " << OUTPUT_FILE;
+
+ while (1) {
+ EAS_PCM *pcm = mPCMBuffer;
+ int32_t numBytesOutput = 0;
+ result = EAS_State(mEASDataHandle, mEASStreamHandle, &state);
+ ASSERT_EQ(result, EAS_SUCCESS) << "Failed to get EAS State";
+
+ ASSERT_NE(state, EAS_STATE_ERROR) << "Error state found";
+
+ /* is playback complete */
+ if (state == EAS_STATE_STOPPED) {
+ break;
+ }
+
+ EAS_I32 locationMs;
+ result = EAS_GetLocation(mEASDataHandle, mEASStreamHandle, &locationMs);
+ ASSERT_EQ(result, EAS_SUCCESS) << "Failed to get the current location in ms";
+
+ if (locationMs >= mAudioplayTimeMs) {
+ ASSERT_NE(state, EAS_STATE_STOPPED)
+ << "Invalid state reached when rendering is complete";
+
+ break;
+ }
+
+ for (uint32_t i = 0; i < kNumBuffersToCombine; i++) {
+ result = EAS_Render(mEASDataHandle, pcm, mEASConfig->mixBufferSize, &count);
+ ASSERT_EQ(result, EAS_SUCCESS) << "Failed to render the audio data";
+
+ pcm += count * mEASConfig->numChannels;
+ numBytesOutput += count * mEASConfig->numChannels * sizeof(EAS_PCM);
+ }
+ int32_t numBytes = fwrite(mPCMBuffer, 1, numBytesOutput, filePtr);
+ ASSERT_EQ(numBytes, numBytesOutput)
+ << "Wrote " << numBytes << " of " << numBytesOutput << " to file: " << OUTPUT_FILE;
+ }
+ fclose(filePtr);
+}
+
+TEST_P(SonivoxTest, SeekTest) {
+ bool status = seekToLocation(0);
+ ASSERT_TRUE(status) << "Seek test failed for location(ms): 0";
+
+ status = seekToLocation(mAudioplayTimeMs / 2);
+ ASSERT_TRUE(status) << "Seek test failed for location(ms): " << mAudioplayTimeMs / 2;
+
+ status = seekToLocation(mAudioplayTimeMs);
+ ASSERT_TRUE(status) << "Seek test failed for location(ms): " << mAudioplayTimeMs;
+
+ status = seekToLocation(mAudioplayTimeMs + kSeekBeyondPlayTimeOffsetMs);
+ ASSERT_FALSE(status) << "Invalid seek position: "
+ << mAudioplayTimeMs + kSeekBeyondPlayTimeOffsetMs;
+}
+
+TEST_P(SonivoxTest, DecodePauseResumeTest) {
+ EAS_I32 seekPosition = mAudioplayTimeMs / 2;
+ // go to middle of the audio
+ EAS_RESULT result = EAS_Locate(mEASDataHandle, mEASStreamHandle, seekPosition, false);
+ ASSERT_EQ(result, EAS_SUCCESS) << "Failed to locate to location(ms): " << seekPosition;
+
+ bool status = renderAudio();
+ ASSERT_TRUE(status) << "Failed to render audio";
+
+ result = EAS_Pause(mEASDataHandle, mEASStreamHandle);
+ ASSERT_EQ(result, EAS_SUCCESS) << "Failed to pause";
+
+ // will render previous audio again, no change in audio position
+ status = renderAudio();
+ ASSERT_TRUE(status) << "should not move audio position, since we're paused";
+
+ // current position in milliseconds
+ EAS_I32 currentPosMs = -1;
+ result = EAS_GetLocation(mEASDataHandle, mEASStreamHandle, ¤tPosMs);
+ ASSERT_EQ(result, EAS_SUCCESS) << "Failed to get current location";
+
+ ASSERT_EQ(currentPosMs, seekPosition) << "Must not move the audio position after pause";
+
+ EAS_STATE state;
+ result = EAS_State(mEASDataHandle, mEASStreamHandle, &state);
+ ASSERT_EQ(result, EAS_SUCCESS) << "Failed to get EAS state";
+
+ ASSERT_EQ(state, EAS_STATE_PAUSED) << "Invalid state reached when paused";
+
+ result = EAS_Resume(mEASDataHandle, mEASStreamHandle);
+ ASSERT_EQ(result, EAS_SUCCESS) << "Failed to resume";
+
+ status = renderAudio();
+ ASSERT_TRUE(status) << "Failed to render audio after resume";
+
+ currentPosMs = -1;
+ result = EAS_GetLocation(mEASDataHandle, mEASStreamHandle, ¤tPosMs);
+ ASSERT_EQ(result, EAS_SUCCESS) << "Failed to get current location";
+
+ ASSERT_GT(currentPosMs, seekPosition) << "Invalid position after resuming";
+
+ result = EAS_State(mEASDataHandle, mEASStreamHandle, &state);
+ ASSERT_EQ(result, EAS_SUCCESS) << "Failed to get EAS state";
+
+ ASSERT_EQ(state, EAS_STATE_PLAY) << "Invalid state reached when resumed";
+}
+
+INSTANTIATE_TEST_SUITE_P(SonivoxTestAll, SonivoxTest,
+ ::testing::Values(make_tuple("midi_a.mid", 2000, 2, 22050),
+ make_tuple("midi8sec.mid", 8002, 2, 22050),
+ make_tuple("midi_cs.mid", 2000, 2, 22050),
+ make_tuple("midi_gs.mid", 2000, 2, 22050),
+ make_tuple("ants.mid", 17233, 2, 22050),
+ make_tuple("testmxmf.mxmf", 29095, 2, 22050)));
+
+int main(int argc, char **argv) {
+ gEnv = new SonivoxTestEnvironment();
+ ::testing::AddGlobalTestEnvironment(gEnv);
+ ::testing::InitGoogleTest(&argc, argv);
+ int status = gEnv->initFromOptions(argc, argv);
+ if (status == 0) {
+ status = RUN_ALL_TESTS();
+ ALOGV("Test result = %d\n", status);
+ }
+ return status;
+}
diff --git a/test/SonivoxTestEnvironment.h b/test/SonivoxTestEnvironment.h
new file mode 100644
index 0000000..1b1690d
--- /dev/null
+++ b/test/SonivoxTestEnvironment.h
@@ -0,0 +1,84 @@
+/*
+ * Copyright (C) 2020 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 __SONIVOX_TEST_ENVIRONMENT_H__
+#define __SONIVOX_TEST_ENVIRONMENT_H__
+
+#include <gtest/gtest.h>
+
+#include <getopt.h>
+
+using namespace std;
+
+class SonivoxTestEnvironment : public::testing::Environment {
+ public:
+ SonivoxTestEnvironment() : res("/data/local/tmp/"), deleteOutput(true){}
+
+ // Parses the command line arguments
+ int initFromOptions(int argc, char **argv);
+
+ void setRes(const char *_res) { res = _res; }
+
+ const string getRes() const { return res; }
+
+ bool cleanUp() const { return deleteOutput; }
+
+ private:
+ string res;
+ bool deleteOutput;
+};
+
+int SonivoxTestEnvironment::initFromOptions(int argc, char **argv) {
+ static struct option options[] = {{"res", required_argument, 0, 'P'},
+ {"cleanUp", optional_argument, 0, 'C'},
+ {0, 0, 0, 0}};
+
+ while (true) {
+ int index = 0;
+ int c = getopt_long(argc, argv, "P:C:", options, &index);
+ if (c == -1) {
+ break;
+ }
+
+ switch (c) {
+ case 'P': {
+ setRes(optarg);
+ break;
+ }
+ case 'C':
+ if (!strcmp(optarg, "false")) {
+ deleteOutput = false;
+ }
+ break;
+ default:
+ break;
+ }
+ }
+
+ if (optind < argc) {
+ fprintf(stderr,
+ "unrecognized option: %s\n\n"
+ "usage: %s <gtest options> <test options>\n\n"
+ "test options are:\n\n"
+ "-P, --path: Resource files directory location\n"
+ "-C, default:true. Delete output file after test completes\n",
+ argv[optind ?: 1], argv[0]);
+ return 2;
+ }
+ return 0;
+}
+
+#endif // __SONIVOX_TEST_ENVIRONMENT_H__