Merge "Revert "RTP: integrate the echo canceller from speex."" into gingerbread
diff --git a/Android.mk b/Android.mk
index c1324c9..5f8b235 100644
--- a/Android.mk
+++ b/Android.mk
@@ -348,7 +348,7 @@
framework \
framework_docs_LOCAL_MODULE_CLASS := JAVA_LIBRARIES
-framework_docs_LOCAL_DROIDDOC_HTML_DIR := docs/html
+framework_docs_LOCAL_DROIDDOC_HTML_DIR := $(LOCAL_PATH)/docs/html $(OUT_DOCS)/gen
# The since flag (-since N.xml API_LEVEL) is used to add API Level information
# to the reference documentation. Must be in order of oldest to newest.
framework_docs_LOCAL_DROIDDOC_OPTIONS := \
@@ -539,8 +539,8 @@
include $(BUILD_DROIDDOC)
-# explicitly specify that online-sdk depends on framework-res.
-$(full_target): framework-res-package-target
+# explicitly specify that online-sdk depends on framework-res and any generated docs
+$(full_target): framework-res-package-target $(ALL_GENERATED_DOCS)
# ==== docs that have all of the stuff that's @hidden =======================
include $(CLEAR_VARS)
diff --git a/api/current.xml b/api/current.xml
index e7b0e3b..4b0068d 100644
--- a/api/current.xml
+++ b/api/current.xml
@@ -45115,6 +45115,17 @@
<parameter name="key" type="java.lang.String">
</parameter>
</method>
+<method name="startCommit"
+ return="void"
+ abstract="true"
+ native="false"
+ synchronized="false"
+ static="false"
+ final="false"
+ deprecated="not deprecated"
+ visibility="public"
+>
+</method>
</interface>
<interface name="SharedPreferences.OnSharedPreferenceChangeListener"
abstract="true"
@@ -77659,6 +77670,17 @@
visibility="public"
>
</field>
+<field name="TYPE_GRAVITY"
+ type="int"
+ transient="false"
+ volatile="false"
+ value="9"
+ static="true"
+ final="true"
+ deprecated="not deprecated"
+ visibility="public"
+>
+</field>
<field name="TYPE_GYROSCOPE"
type="int"
transient="false"
@@ -77681,6 +77703,17 @@
visibility="public"
>
</field>
+<field name="TYPE_LINEAR_ACCELERATION"
+ type="int"
+ transient="false"
+ volatile="false"
+ value="10"
+ static="true"
+ final="true"
+ deprecated="not deprecated"
+ visibility="public"
+>
+</field>
<field name="TYPE_MAGNETIC_FIELD"
type="int"
transient="false"
@@ -77725,6 +77758,17 @@
visibility="public"
>
</field>
+<field name="TYPE_ROTATION_VECTOR"
+ type="int"
+ transient="false"
+ volatile="false"
+ value="11"
+ static="true"
+ final="true"
+ deprecated="not deprecated"
+ visibility="public"
+>
+</field>
<field name="TYPE_TEMPERATURE"
type="int"
transient="false"
@@ -77884,6 +77928,23 @@
<parameter name="p" type="float">
</parameter>
</method>
+<method name="getAngleChange"
+ return="void"
+ abstract="false"
+ native="false"
+ synchronized="false"
+ static="true"
+ final="false"
+ deprecated="not deprecated"
+ visibility="public"
+>
+<parameter name="angleChange" type="float[]">
+</parameter>
+<parameter name="R" type="float[]">
+</parameter>
+<parameter name="prevR" type="float[]">
+</parameter>
+</method>
<method name="getDefaultSensor"
return="android.hardware.Sensor"
abstract="false"
@@ -77925,6 +77986,21 @@
<parameter name="values" type="float[]">
</parameter>
</method>
+<method name="getQuaternionFromVector"
+ return="void"
+ abstract="false"
+ native="false"
+ synchronized="false"
+ static="true"
+ final="false"
+ deprecated="not deprecated"
+ visibility="public"
+>
+<parameter name="Q" type="float[]">
+</parameter>
+<parameter name="rv" type="float[]">
+</parameter>
+</method>
<method name="getRotationMatrix"
return="boolean"
abstract="false"
@@ -77944,6 +78020,21 @@
<parameter name="geomagnetic" type="float[]">
</parameter>
</method>
+<method name="getRotationMatrixFromVector"
+ return="void"
+ abstract="false"
+ native="false"
+ synchronized="false"
+ static="true"
+ final="false"
+ deprecated="not deprecated"
+ visibility="public"
+>
+<parameter name="R" type="float[]">
+</parameter>
+<parameter name="rotationVector" type="float[]">
+</parameter>
+</method>
<method name="getSensorList"
return="java.util.List<android.hardware.Sensor>"
abstract="false"
@@ -129190,7 +129281,7 @@
deprecated="not deprecated"
visibility="public"
>
-<method name="getThreadBlockingPolicy"
+<method name="allowThreadDiskReads"
return="int"
abstract="false"
native="false"
@@ -129201,7 +129292,29 @@
visibility="public"
>
</method>
-<method name="setThreadBlockingPolicy"
+<method name="allowThreadDiskWrites"
+ return="int"
+ abstract="false"
+ native="false"
+ synchronized="false"
+ static="true"
+ final="false"
+ deprecated="not deprecated"
+ visibility="public"
+>
+</method>
+<method name="getThreadPolicy"
+ return="int"
+ abstract="false"
+ native="false"
+ synchronized="false"
+ static="true"
+ final="false"
+ deprecated="not deprecated"
+ visibility="public"
+>
+</method>
+<method name="setThreadPolicy"
return="void"
abstract="false"
native="false"
@@ -222935,7 +223048,9 @@
deprecated="not deprecated"
visibility="public"
>
-<parameter name="offset" type="int">
+<parameter name="x" type="int">
+</parameter>
+<parameter name="y" type="int">
</parameter>
</method>
<field name="FADE_OUT_DURATION"
@@ -257941,7 +258056,7 @@
>
<parameter name="numBits" type="int">
</parameter>
-<parameter name="rnd" type="java.util.Random">
+<parameter name="random" type="java.util.Random">
</parameter>
</constructor>
<constructor name="BigInteger"
@@ -257955,7 +258070,7 @@
</parameter>
<parameter name="certainty" type="int">
</parameter>
-<parameter name="rnd" type="java.util.Random">
+<parameter name="unused" type="java.util.Random">
</parameter>
</constructor>
<constructor name="BigInteger"
@@ -257965,7 +258080,7 @@
deprecated="not deprecated"
visibility="public"
>
-<parameter name="val" type="java.lang.String">
+<parameter name="value" type="java.lang.String">
</parameter>
</constructor>
<constructor name="BigInteger"
@@ -257975,7 +258090,7 @@
deprecated="not deprecated"
visibility="public"
>
-<parameter name="val" type="java.lang.String">
+<parameter name="value" type="java.lang.String">
</parameter>
<parameter name="radix" type="int">
</parameter>
@@ -257999,7 +258114,7 @@
deprecated="not deprecated"
visibility="public"
>
-<parameter name="val" type="byte[]">
+<parameter name="value" type="byte[]">
</parameter>
</constructor>
<method name="abs"
@@ -258023,7 +258138,7 @@
deprecated="not deprecated"
visibility="public"
>
-<parameter name="val" type="java.math.BigInteger">
+<parameter name="value" type="java.math.BigInteger">
</parameter>
</method>
<method name="and"
@@ -258036,7 +258151,7 @@
deprecated="not deprecated"
visibility="public"
>
-<parameter name="val" type="java.math.BigInteger">
+<parameter name="value" type="java.math.BigInteger">
</parameter>
</method>
<method name="andNot"
@@ -258049,7 +258164,7 @@
deprecated="not deprecated"
visibility="public"
>
-<parameter name="val" type="java.math.BigInteger">
+<parameter name="value" type="java.math.BigInteger">
</parameter>
</method>
<method name="bitCount"
@@ -258097,7 +258212,7 @@
deprecated="not deprecated"
visibility="public"
>
-<parameter name="val" type="java.math.BigInteger">
+<parameter name="value" type="java.math.BigInteger">
</parameter>
</method>
<method name="divide"
@@ -258171,7 +258286,7 @@
deprecated="not deprecated"
visibility="public"
>
-<parameter name="val" type="java.math.BigInteger">
+<parameter name="value" type="java.math.BigInteger">
</parameter>
</method>
<method name="getLowestSetBit"
@@ -258230,7 +258345,7 @@
deprecated="not deprecated"
visibility="public"
>
-<parameter name="val" type="java.math.BigInteger">
+<parameter name="value" type="java.math.BigInteger">
</parameter>
</method>
<method name="min"
@@ -258243,7 +258358,7 @@
deprecated="not deprecated"
visibility="public"
>
-<parameter name="val" type="java.math.BigInteger">
+<parameter name="value" type="java.math.BigInteger">
</parameter>
</method>
<method name="mod"
@@ -258297,7 +258412,7 @@
deprecated="not deprecated"
visibility="public"
>
-<parameter name="val" type="java.math.BigInteger">
+<parameter name="value" type="java.math.BigInteger">
</parameter>
</method>
<method name="negate"
@@ -258343,7 +258458,7 @@
deprecated="not deprecated"
visibility="public"
>
-<parameter name="val" type="java.math.BigInteger">
+<parameter name="value" type="java.math.BigInteger">
</parameter>
</method>
<method name="pow"
@@ -258371,7 +258486,7 @@
>
<parameter name="bitLength" type="int">
</parameter>
-<parameter name="rnd" type="java.util.Random">
+<parameter name="unused" type="java.util.Random">
</parameter>
</method>
<method name="remainder"
@@ -258447,7 +258562,7 @@
deprecated="not deprecated"
visibility="public"
>
-<parameter name="val" type="java.math.BigInteger">
+<parameter name="value" type="java.math.BigInteger">
</parameter>
</method>
<method name="testBit"
@@ -258497,7 +258612,7 @@
deprecated="not deprecated"
visibility="public"
>
-<parameter name="val" type="long">
+<parameter name="value" type="long">
</parameter>
</method>
<method name="xor"
@@ -258510,7 +258625,7 @@
deprecated="not deprecated"
visibility="public"
>
-<parameter name="val" type="java.math.BigInteger">
+<parameter name="value" type="java.math.BigInteger">
</parameter>
</method>
<field name="ONE"
diff --git a/core/java/android/app/Activity.java b/core/java/android/app/Activity.java
index f7ccc12..ed5af91 100644
--- a/core/java/android/app/Activity.java
+++ b/core/java/android/app/Activity.java
@@ -3898,7 +3898,14 @@
}
final void performPause() {
+ mCalled = false;
onPause();
+ if (!mCalled && getApplicationInfo().targetSdkVersion
+ >= android.os.Build.VERSION_CODES.GINGERBREAD) {
+ throw new SuperNotCalledException(
+ "Activity " + mComponent.toShortString() +
+ " did not call through to super.onPause()");
+ }
}
final void performUserLeaving() {
diff --git a/core/java/android/app/ActivityThread.java b/core/java/android/app/ActivityThread.java
index c96d562..c07e3d3 100644
--- a/core/java/android/app/ActivityThread.java
+++ b/core/java/android/app/ActivityThread.java
@@ -3106,7 +3106,7 @@
(ApplicationInfo.FLAG_SYSTEM |
ApplicationInfo.FLAG_UPDATED_SYSTEM_APP)) != 0 &&
!"user".equals(Build.TYPE)) {
- StrictMode.setThreadBlockingPolicy(
+ StrictMode.setThreadPolicy(
StrictMode.DISALLOW_DISK_WRITE |
StrictMode.DISALLOW_DISK_READ |
StrictMode.DISALLOW_NETWORK |
diff --git a/core/java/android/app/ContextImpl.java b/core/java/android/app/ContextImpl.java
index 2870c50..7b35e7f 100644
--- a/core/java/android/app/ContextImpl.java
+++ b/core/java/android/app/ContextImpl.java
@@ -2840,6 +2840,11 @@
}
}
+ public void startCommit() {
+ // TODO: implement
+ commit();
+ }
+
public boolean commit() {
boolean returnValue;
@@ -2914,7 +2919,7 @@
public Editor edit() {
return new EditorImpl();
}
-
+
private FileOutputStream createFileOutputStream(File file) {
FileOutputStream str = null;
try {
diff --git a/core/java/android/content/SharedPreferences.java b/core/java/android/content/SharedPreferences.java
index a15e29e..f1b1490 100644
--- a/core/java/android/content/SharedPreferences.java
+++ b/core/java/android/content/SharedPreferences.java
@@ -151,14 +151,47 @@
* {@link SharedPreferences} object it is editing. This atomically
* performs the requested modifications, replacing whatever is currently
* in the SharedPreferences.
- *
+ *
* <p>Note that when two editors are modifying preferences at the same
* time, the last one to call commit wins.
- *
+ *
+ * <p>If you don't care about the return value and you're
+ * using this from your application's main thread, consider
+ * using {@link #startCommit} instead.
+ *
* @return Returns true if the new values were successfully written
* to persistent storage.
*/
boolean commit();
+
+ /**
+ * Commit your preferences changes back from this Editor to the
+ * {@link SharedPreferences} object it is editing. This atomically
+ * performs the requested modifications, replacing whatever is currently
+ * in the SharedPreferences.
+ *
+ * <p>Note that when two editors are modifying preferences at the same
+ * time, the last one to call commit wins.
+ *
+ * <p>Unlike {@link #commit}, which writes its preferences out
+ * to persistent storage synchronously, {@link #startCommit}
+ * commits its changes to the in-memory
+ * {@link SharedPreferences} immediately but starts an
+ * asynchronous commit to disk and you won't be notified of
+ * any failures. If another editor on this
+ * {@link SharedPreferences} does a regular {@link #commit}
+ * while a {@link #startCommit} is still outstanding, the
+ * {@link #commit} will block until all async commits are
+ * completed as well as the commit itself.
+ *
+ * <p>If you call this from an {@link android.app.Activity},
+ * the base class will wait for any async commits to finish in
+ * its {@link android.app.Activity#onPause}.</p>
+ *
+ * @return Returns true if the new values were successfully written
+ * to persistent storage.
+ */
+ void startCommit();
}
/**
diff --git a/core/java/android/hardware/Sensor.java b/core/java/android/hardware/Sensor.java
index b49a409..f2b907b 100644
--- a/core/java/android/hardware/Sensor.java
+++ b/core/java/android/hardware/Sensor.java
@@ -77,6 +77,27 @@
public static final int TYPE_PROXIMITY = 8;
/**
+ * A constant describing a gravity sensor type.
+ * See {@link android.hardware.SensorEvent SensorEvent}
+ * for more details.
+ */
+ public static final int TYPE_GRAVITY = 9;
+
+ /**
+ * A constant describing a linear acceleration sensor type.
+ * See {@link android.hardware.SensorEvent SensorEvent}
+ * for more details.
+ */
+ public static final int TYPE_LINEAR_ACCELERATION = 10;
+
+ /**
+ * A constant describing a rotation vector sensor type.
+ * See {@link android.hardware.SensorEvent SensorEvent}
+ * for more details.
+ */
+ public static final int TYPE_ROTATION_VECTOR = 11;
+
+ /**
* A constant describing all sensor types.
*/
public static final int TYPE_ALL = -1;
diff --git a/core/java/android/hardware/SensorEvent.java b/core/java/android/hardware/SensorEvent.java
index 70519ff..6212e1b 100644
--- a/core/java/android/hardware/SensorEvent.java
+++ b/core/java/android/hardware/SensorEvent.java
@@ -133,6 +133,16 @@
* All values are in micro-Tesla (uT) and measure the ambient magnetic field
* in the X, Y and Z axis.
*
+ * <h4>{@link android.hardware.Sensor#TYPE_GYROSCOPE Sensor.TYPE_GYROSCOPE}:</h4>
+ * All values are in radians/second and measure the rate of rotation
+ * around the X, Y and Z axis. The coordinate system is the same as is
+ * used for the acceleration sensor. Rotation is positive in the counter-clockwise
+ * direction. That is, an observer looking from some positive location on the x, y.
+ * or z axis at a device positioned on the origin would report positive rotation
+ * if the device appeared to be rotating counter clockwise. Note that this is the
+ * standard mathematical definition of positive rotation and does not agree with the
+ * definition of roll given earlier.
+ *
* <h4>{@link android.hardware.Sensor#TYPE_LIGHT Sensor.TYPE_LIGHT}:</h4>
*
* <ul>
@@ -155,6 +165,27 @@
* the <i>far</i> state and a lesser value in the <i>near</i> state.
* </p>
*
+ * <h4>{@link android.hardware.Sensor#TYPE_GRAVITY Sensor.TYPE_GRAVITY}:</h4>
+ * A three dimensional vector indicating the direction and magnitude of gravity. Units
+ * are m/s^2. The coordinate system is the same as is used by the acceleration sensor.
+ *
+ * <h4>{@link android.hardware.Sensor#TYPE_LINEAR_ACCELERATION Sensor.TYPE_LINEAR_ACCELERATION}:</h4>
+ * A three dimensional vector indicating acceleration along each device axis, not including
+ * gravity. All values have units of m/s^2. The coordinate system is the same as is used by the
+ * acceleration sensor.
+ *
+ * <h4>{@link android.hardware.Sensor#TYPE_ROTATION_VECTOR Sensor.TYPE_ROTATION_VECTOR}:</h4>
+ * The rotation vector represents the orientation of the device as a combination of an angle
+ * and an axis, in which the device has rotated through an angle theta around an axis
+ * <x, y, z>. The three elements of the rotation vector are
+ * <x*sin(theta/2), y*sin(theta/2), z*sin(theta/2)>, such that the magnitude of the rotation
+ * vector is equal to sin(theta/2), and the direction of the rotation vector is equal to the
+ * direction of the axis of rotation. The three elements of the rotation vector are equal to
+ * the last three components of a unit quaternion
+ * <cos(theta/2), x*sin(theta/2), y*sin(theta/2), z*sin(theta/2)>. Elements of the rotation
+ * vector are unitless. The x,y, and z axis are defined in the same way as the acceleration
+ * sensor.
+ *
* <h4>{@link android.hardware.Sensor#TYPE_ORIENTATION
* Sensor.TYPE_ORIENTATION}:</h4> All values are angles in degrees.
*
@@ -201,6 +232,7 @@
* @see SensorEvent
* @see GeomagneticField
*/
+
public final float[] values;
/**
diff --git a/core/java/android/hardware/SensorManager.java b/core/java/android/hardware/SensorManager.java
index d2c3eaa..0068724 100644
--- a/core/java/android/hardware/SensorManager.java
+++ b/core/java/android/hardware/SensorManager.java
@@ -34,11 +34,19 @@
import java.util.List;
/**
+ * <p>
* SensorManager lets you access the device's {@link android.hardware.Sensor
* sensors}. Get an instance of this class by calling
* {@link android.content.Context#getSystemService(java.lang.String)
* Context.getSystemService()} with the argument
* {@link android.content.Context#SENSOR_SERVICE}.
+ * </p>
+ * <p>
+ * Always make sure to disable sensors you don't need, especially when your
+ * activity is paused. Failing to do so can drain the battery in just a few
+ * hours. Note that the system will <i>not</i> disable sensors automatically when
+ * the screen turns off.
+ * </p>
*
* <pre class="prettyprint">
* public class SensorActivity extends Activity, implements SensorEventListener {
@@ -48,13 +56,22 @@
* public SensorActivity() {
* mSensorManager = (SensorManager)getSystemService(SENSOR_SERVICE);
* mAccelerometer = mSensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
+ * }
+ *
+ * protected void onResume() {
+ * super.onResume();
* mSensorManager.registerListener(this, mAccelerometer, SensorManager.SENSOR_DELAY_NORMAL);
* }
*
+ * protected void onPause() {
+ * super.onPause();
+ * mSensorManager.unregisterListener(this);
+ * }
+ *
* public void onAccuracyChanged(Sensor sensor, int accuracy) {
* }
*
- * public abstract void onSensorChanged(SensorEvent event) {
+ * public void onSensorChanged(SensorEvent event) {
* }
* }
* </pre>
@@ -1769,6 +1786,183 @@
}
+ /** Helper function to compute the angle change between two rotation matrices.
+ * Given a current rotation matrix (R) and a previous rotation matrix
+ * (prevR) computes the rotation around the x,y, and z axes which
+ * transforms prevR to R.
+ * outputs a 3 element vector containing the x,y, and z angle
+ * change at indexes 0, 1, and 2 respectively.
+ * <p> Each input matrix is either as a 3x3 or 4x4 row-major matrix
+ * depending on the length of the passed array:
+ * <p>If the array length is 9, then the array elements represent this matrix
+ * <pre>
+ * / R[ 0] R[ 1] R[ 2] \
+ * | R[ 3] R[ 4] R[ 5] |
+ * \ R[ 6] R[ 7] R[ 8] /
+ *</pre>
+ * <p>If the array length is 16, then the array elements represent this matrix
+ * <pre>
+ * / R[ 0] R[ 1] R[ 2] R[ 3] \
+ * | R[ 4] R[ 5] R[ 6] R[ 7] |
+ * | R[ 8] R[ 9] R[10] R[11] |
+ * \ R[12] R[13] R[14] R[15] /
+ *</pre>
+ * @param R current rotation matrix
+ * @param prevR previous rotation matrix
+ * @param angleChange an array of floats in which the angle change is stored
+ */
+
+ public static void getAngleChange( float[] angleChange, float[] R, float[] prevR) {
+ float rd1=0,rd4=0, rd6=0,rd7=0, rd8=0;
+ float ri0=0,ri1=0,ri2=0,ri3=0,ri4=0,ri5=0,ri6=0,ri7=0,ri8=0;
+ float pri0=0, pri1=0, pri2=0, pri3=0, pri4=0, pri5=0, pri6=0, pri7=0, pri8=0;
+ int i, j, k;
+
+ if(R.length == 9) {
+ ri0 = R[0];
+ ri1 = R[1];
+ ri2 = R[2];
+ ri3 = R[3];
+ ri4 = R[4];
+ ri5 = R[5];
+ ri6 = R[6];
+ ri7 = R[7];
+ ri8 = R[8];
+ } else if(R.length == 16) {
+ ri0 = R[0];
+ ri1 = R[1];
+ ri2 = R[2];
+ ri3 = R[4];
+ ri4 = R[5];
+ ri5 = R[6];
+ ri6 = R[8];
+ ri7 = R[9];
+ ri8 = R[10];
+ }
+
+ if(prevR.length == 9) {
+ pri0 = R[0];
+ pri1 = R[1];
+ pri2 = R[2];
+ pri3 = R[3];
+ pri4 = R[4];
+ pri5 = R[5];
+ pri6 = R[6];
+ pri7 = R[7];
+ pri8 = R[8];
+ } else if(prevR.length == 16) {
+ pri0 = R[0];
+ pri1 = R[1];
+ pri2 = R[2];
+ pri3 = R[4];
+ pri4 = R[5];
+ pri5 = R[6];
+ pri6 = R[8];
+ pri7 = R[9];
+ pri8 = R[10];
+ }
+
+ // calculate the parts of the rotation difference matrix we need
+ // rd[i][j] = pri[0][i] * ri[0][j] + pri[1][i] * ri[1][j] + pri[2][i] * ri[2][j];
+
+ rd1 = pri0 * ri1 + pri3 * ri4 + pri6 * ri7; //rd[0][1]
+ rd4 = pri1 * ri1 + pri4 * ri4 + pri7 * ri7; //rd[1][1]
+ rd6 = pri2 * ri0 + pri5 * ri3 + pri8 * ri6; //rd[2][0]
+ rd7 = pri2 * ri1 + pri5 * ri4 + pri8 * ri7; //rd[2][1]
+ rd8 = pri2 * ri2 + pri5 * ri5 + pri8 * ri8; //rd[2][2]
+
+ angleChange[0] = (float)Math.atan2(rd1, rd4);
+ angleChange[1] = (float)Math.asin(-rd7);
+ angleChange[2] = (float)Math.atan2(-rd6, rd8);
+
+ }
+
+ /** Helper function to convert a rotation vector to a rotation matrix.
+ * Given a rotation vector (presumably from a ROTATION_VECTOR sensor), returns a
+ * 9 or 16 element rotation matrix in the array R. R must have length 9 or 16.
+ * If R.length == 9, the following matrix is returned:
+ * <pre>
+ * / R[ 0] R[ 1] R[ 2] \
+ * | R[ 3] R[ 4] R[ 5] |
+ * \ R[ 6] R[ 7] R[ 8] /
+ *</pre>
+ * If R.length == 16, the following matrix is returned:
+ * <pre>
+ * / R[ 0] R[ 1] R[ 2] 0 \
+ * | R[ 4] R[ 5] R[ 6] 0 |
+ * | R[ 8] R[ 9] R[10] 0 |
+ * \ 0 0 0 1 /
+ *</pre>
+ * @param rotationVector the rotation vector to convert
+ * @param R an array of floats in which to store the rotation matrix
+ */
+ public static void getRotationMatrixFromVector(float[] R, float[] rotationVector) {
+ float q0 = (float)Math.sqrt(1 - rotationVector[0]*rotationVector[0] -
+ rotationVector[1]*rotationVector[1] -
+ rotationVector[2]*rotationVector[2]);
+ float q1 = rotationVector[0];
+ float q2 = rotationVector[1];
+ float q3 = rotationVector[2];
+
+ float sq_q1 = 2 * q1 * q1;
+ float sq_q2 = 2 * q2 * q2;
+ float sq_q3 = 2 * q3 * q3;
+ float q1_q2 = 2 * q1 * q2;
+ float q3_q0 = 2 * q3 * q0;
+ float q1_q3 = 2 * q1 * q3;
+ float q2_q0 = 2 * q2 * q0;
+ float q2_q3 = 2 * q2 * q3;
+ float q1_q0 = 2 * q1 * q0;
+
+ if(R.length == 9) {
+ R[0] = 1 - sq_q2 - sq_q3;
+ R[1] = q1_q2 - q3_q0;
+ R[2] = q1_q3 + q2_q0;
+
+ R[3] = q1_q2 + q3_q0;
+ R[4] = 1 - sq_q1 - sq_q3;
+ R[5] = q2_q3 - q1_q0;
+
+ R[6] = q1_q3 - q2_q0;
+ R[7] = q2_q3 + q1_q0;
+ R[8] = 1 - sq_q1 - sq_q2;
+ } else if (R.length == 16) {
+ R[0] = 1 - sq_q2 - sq_q3;
+ R[1] = q1_q2 - q3_q0;
+ R[2] = q1_q3 + q2_q0;
+ R[3] = 0.0f;
+
+ R[4] = q1_q2 + q3_q0;
+ R[5] = 1 - sq_q1 - sq_q3;
+ R[6] = q2_q3 - q1_q0;
+ R[7] = 0.0f;
+
+ R[8] = q1_q3 - q2_q0;
+ R[9] = q2_q3 + q1_q0;
+ R[10] = 1 - sq_q1 - sq_q2;
+ R[11] = 0.0f;
+
+ R[12] = R[13] = R[14] = 0.0f;
+ R[15] = 1.0f;
+ }
+ }
+
+ /** Helper function to convert a rotation vector to a normalized quaternion.
+ * Given a rotation vector (presumably from a ROTATION_VECTOR sensor), returns a normalized
+ * quaternion in the array Q. The quaternion is stored as [w, x, y, z]
+ * @param rv the rotation vector to convert
+ * @param Q an array of floats in which to store the computed quaternion
+ */
+ public static void getQuaternionFromVector(float[] Q, float[] rv) {
+ float w = (float)Math.sqrt(1 - rv[0]*rv[0] - rv[1]*rv[1] - rv[2]*rv[2]);
+ //In this case, the w component of the quaternion is known to be a positive number
+
+ Q[0] = w;
+ Q[1] = rv[0];
+ Q[2] = rv[1];
+ Q[3] = rv[2];
+ }
+
private static native void nativeClassInit();
private static native int sensors_module_init();
diff --git a/core/java/android/os/StrictMode.java b/core/java/android/os/StrictMode.java
index ac12e10..7f7b02b 100644
--- a/core/java/android/os/StrictMode.java
+++ b/core/java/android/os/StrictMode.java
@@ -114,7 +114,7 @@
*
* @param policyMask a bitmask of DISALLOW_* and PENALTY_* values.
*/
- public static void setThreadBlockingPolicy(final int policyMask) {
+ public static void setThreadPolicy(final int policyMask) {
// In addition to the Java-level thread-local in Dalvik's
// BlockGuard, we also need to keep a native thread-local in
// Binder in order to propagate the value across Binder calls,
@@ -164,11 +164,43 @@
*
* @return the bitmask of all the DISALLOW_* and PENALTY_* bits currently enabled
*/
- public static int getThreadBlockingPolicy() {
+ public static int getThreadPolicy() {
return BlockGuard.getThreadPolicy().getPolicyMask();
}
/**
+ * Updates the current thread's policy mask to allow reading &
+ * writing to disk.
+ *
+ * @return the old policy mask, to be passed to setThreadPolicy to
+ * restore the policy.
+ */
+ public static int allowThreadDiskWrites() {
+ int oldPolicy = getThreadPolicy();
+ int newPolicy = oldPolicy & ~(DISALLOW_DISK_WRITE | DISALLOW_DISK_READ);
+ if (newPolicy != oldPolicy) {
+ setThreadPolicy(newPolicy);
+ }
+ return oldPolicy;
+ }
+
+ /**
+ * Updates the current thread's policy mask to allow reading from
+ * disk.
+ *
+ * @return the old policy mask, to be passed to setThreadPolicy to
+ * restore the policy.
+ */
+ public static int allowThreadDiskReads() {
+ int oldPolicy = getThreadPolicy();
+ int newPolicy = oldPolicy & ~(DISALLOW_DISK_READ);
+ if (newPolicy != oldPolicy) {
+ setThreadPolicy(newPolicy);
+ }
+ return oldPolicy;
+ }
+
+ /**
* Parses the BlockGuard policy mask out from the Exception's
* getMessage() String value. Kinda gross, but least
* invasive. :/
@@ -413,13 +445,13 @@
if (violationMaskSubset != 0) {
int violationBit = parseViolationFromMessage(info.crashInfo.exceptionMessage);
violationMaskSubset |= violationBit;
- final int savedPolicy = getThreadBlockingPolicy();
+ final int savedPolicy = getThreadPolicy();
try {
// First, remove any policy before we call into the Activity Manager,
// otherwise we'll infinite recurse as we try to log policy violations
// to disk, thus violating policy, thus requiring logging, etc...
// We restore the current policy below, in the finally block.
- setThreadBlockingPolicy(0);
+ setThreadPolicy(0);
ActivityManagerNative.getDefault().handleApplicationStrictModeViolation(
RuntimeInit.getApplicationObject(),
@@ -429,7 +461,7 @@
Log.e(TAG, "RemoteException trying to handle StrictMode violation", e);
} finally {
// Restore the policy.
- setThreadBlockingPolicy(savedPolicy);
+ setThreadPolicy(savedPolicy);
}
}
@@ -487,7 +519,7 @@
new LogStackTrace().printStackTrace(new PrintWriter(sw));
String ourStack = sw.toString();
- int policyMask = getThreadBlockingPolicy();
+ int policyMask = getThreadPolicy();
boolean currentlyGathering = (policyMask & PENALTY_GATHER) != 0;
int numViolations = p.readInt();
diff --git a/core/java/android/pim/vcard/VCardEntry.java b/core/java/android/pim/vcard/VCardEntry.java
index 7c7e9b8..97d3fbc 100644
--- a/core/java/android/pim/vcard/VCardEntry.java
+++ b/core/java/android/pim/vcard/VCardEntry.java
@@ -954,7 +954,7 @@
}
}
if (type < 0) {
- type = Phone.TYPE_HOME;
+ type = Im.TYPE_HOME;
}
addIm(protocol, null, type, propValue, isPrimary);
} else if (propName.equals(VCardConstants.PROPERTY_NOTE)) {
@@ -1195,12 +1195,14 @@
builder.withValue(Data.MIMETYPE, Im.CONTENT_ITEM_TYPE);
builder.withValue(Im.TYPE, imData.type);
builder.withValue(Im.PROTOCOL, imData.protocol);
+ builder.withValue(Im.DATA, imData.data);
if (imData.protocol == Im.PROTOCOL_CUSTOM) {
builder.withValue(Im.CUSTOM_PROTOCOL, imData.customProtocol);
}
if (imData.isPrimary) {
builder.withValue(Data.IS_PRIMARY, 1);
}
+ operationList.add(builder.build());
}
}
diff --git a/core/java/android/provider/MediaStore.java b/core/java/android/provider/MediaStore.java
index 40ed980..d20e89d 100644
--- a/core/java/android/provider/MediaStore.java
+++ b/core/java/android/provider/MediaStore.java
@@ -249,6 +249,8 @@
private static final int MICRO_KIND = 3;
private static final String[] PROJECTION = new String[] {_ID, MediaColumns.DATA};
static final int DEFAULT_GROUP_ID = 0;
+ private static final Object sThumbBufLock = new Object();
+ private static byte[] sThumbBuf;
private static Bitmap getMiniThumbFromFile(Cursor c, Uri baseUri, ContentResolver cr, BitmapFactory.Options options) {
Bitmap bitmap = null;
@@ -321,11 +323,15 @@
long magic = thumbFile.getMagic(origId);
if (magic != 0) {
if (kind == MICRO_KIND) {
- byte[] data = new byte[MiniThumbFile.BYTES_PER_MINTHUMB];
- if (thumbFile.getMiniThumbFromFile(origId, data) != null) {
- bitmap = BitmapFactory.decodeByteArray(data, 0, data.length);
- if (bitmap == null) {
- Log.w(TAG, "couldn't decode byte array.");
+ synchronized (sThumbBufLock) {
+ if (sThumbBuf == null) {
+ sThumbBuf = new byte[MiniThumbFile.BYTES_PER_MINTHUMB];
+ }
+ if (thumbFile.getMiniThumbFromFile(origId, sThumbBuf) != null) {
+ bitmap = BitmapFactory.decodeByteArray(sThumbBuf, 0, sThumbBuf.length);
+ if (bitmap == null) {
+ Log.w(TAG, "couldn't decode byte array.");
+ }
}
}
return bitmap;
@@ -357,11 +363,15 @@
// Assuming thumbnail has been generated, at least original image exists.
if (kind == MICRO_KIND) {
- byte[] data = new byte[MiniThumbFile.BYTES_PER_MINTHUMB];
- if (thumbFile.getMiniThumbFromFile(origId, data) != null) {
- bitmap = BitmapFactory.decodeByteArray(data, 0, data.length);
- if (bitmap == null) {
- Log.w(TAG, "couldn't decode byte array.");
+ synchronized (sThumbBufLock) {
+ if (sThumbBuf == null) {
+ sThumbBuf = new byte[MiniThumbFile.BYTES_PER_MINTHUMB];
+ }
+ if (thumbFile.getMiniThumbFromFile(origId, sThumbBuf) != null) {
+ bitmap = BitmapFactory.decodeByteArray(sThumbBuf, 0, sThumbBuf.length);
+ if (bitmap == null) {
+ Log.w(TAG, "couldn't decode byte array.");
+ }
}
}
} else if (kind == MINI_KIND) {
diff --git a/core/java/android/text/method/ArrowKeyMovementMethod.java b/core/java/android/text/method/ArrowKeyMovementMethod.java
index 79a0c37..3fe14f9 100644
--- a/core/java/android/text/method/ArrowKeyMovementMethod.java
+++ b/core/java/android/text/method/ArrowKeyMovementMethod.java
@@ -287,8 +287,7 @@
// Offset the current touch position (from controller to cursor)
final float x = event.getX() + mCursorController.getOffsetX();
final float y = event.getY() + mCursorController.getOffsetY();
- int offset = widget.getOffset((int) x, (int) y);
- mCursorController.updatePosition(offset);
+ mCursorController.updatePosition((int) x, (int) y);
return true;
case MotionEvent.ACTION_UP:
@@ -320,25 +319,9 @@
public void onTakeFocus(TextView view, Spannable text, int dir) {
if ((dir & (View.FOCUS_FORWARD | View.FOCUS_DOWN)) != 0) {
- Layout layout = view.getLayout();
-
- if (layout == null) {
- /*
- * This shouldn't be null, but do something sensible if it is.
- */
+ if (view.getLayout() == null) {
+ // This shouldn't be null, but do something sensible if it is.
Selection.setSelection(text, text.length());
- } else {
- /*
- * Put the cursor at the end of the first line, which is
- * either the last offset if there is only one line, or the
- * offset before the first character of the second line
- * if there is more than one line.
- */
- if (layout.getLineCount() == 1) {
- Selection.setSelection(text, text.length());
- } else {
- Selection.setSelection(text, layout.getLineStart(1) - 1);
- }
}
} else {
Selection.setSelection(text, text.length());
diff --git a/core/java/android/view/ViewDebug.java b/core/java/android/view/ViewDebug.java
index 402443c..7b6991f 100644
--- a/core/java/android/view/ViewDebug.java
+++ b/core/java/android/view/ViewDebug.java
@@ -1138,22 +1138,24 @@
final View captureView = findView(root, parameter);
Bitmap b = performViewCapture(captureView, false);
-
- if (b != null) {
- BufferedOutputStream out = null;
- try {
- out = new BufferedOutputStream(clientStream, 32 * 1024);
- b.compress(Bitmap.CompressFormat.PNG, 100, out);
- out.flush();
- } finally {
- if (out != null) {
- out.close();
- }
- b.recycle();
- }
- } else {
+
+ if (b == null) {
Log.w("View", "Failed to create capture bitmap!");
- clientStream.close();
+ // Send an empty one so that it doesn't get stuck waiting for
+ // something.
+ b = Bitmap.createBitmap(1, 1, Bitmap.Config.ARGB_8888);
+ }
+
+ BufferedOutputStream out = null;
+ try {
+ out = new BufferedOutputStream(clientStream, 32 * 1024);
+ b.compress(Bitmap.CompressFormat.PNG, 100, out);
+ out.flush();
+ } finally {
+ if (out != null) {
+ out.close();
+ }
+ b.recycle();
}
}
diff --git a/core/java/android/webkit/WebView.java b/core/java/android/webkit/WebView.java
index 3e0187d..f8e60ce 100644
--- a/core/java/android/webkit/WebView.java
+++ b/core/java/android/webkit/WebView.java
@@ -3338,7 +3338,8 @@
setUpSelect();
if (mNativeClass != 0 && nativeWordSelection(x, y)) {
nativeSetExtendSelection();
- getWebChromeClient().onSelectionStart(this);
+ WebChromeClient client = getWebChromeClient();
+ if (client != null) client.onSelectionStart(this);
return true;
}
notifySelectDialogDismissed();
@@ -4126,7 +4127,8 @@
*/
public void selectionDone() {
if (mSelectingText) {
- getWebChromeClient().onSelectionDone(this);
+ WebChromeClient client = getWebChromeClient();
+ if (client != null) client.onSelectionDone(this);
invalidate(); // redraw without selection
notifySelectDialogDismissed();
}
diff --git a/core/java/android/widget/TextView.java b/core/java/android/widget/TextView.java
index 73b1d6d..2f76bd0 100644
--- a/core/java/android/widget/TextView.java
+++ b/core/java/android/widget/TextView.java
@@ -6469,6 +6469,13 @@
if (!mFrozenWithFocus || (selStart < 0 || selEnd < 0)) {
boolean selMoved = mSelectionMoved;
+ if (mSelectionModifierCursorController != null) {
+ final int touchOffset =
+ ((SelectionModifierCursorController) mSelectionModifierCursorController).
+ getMinTouchOffset();
+ Selection.setSelection((Spannable) mText, touchOffset);
+ }
+
if (mMovement != null) {
mMovement.onTakeFocus(this, (Spannable) mText, direction);
}
@@ -6680,13 +6687,14 @@
if (isTextEditable()) {
if (action == MotionEvent.ACTION_UP && isFocused() && !mScrolled) {
InputMethodManager imm = (InputMethodManager)
- getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
+ getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
final int newSelStart = getSelectionStart();
final int newSelEnd = getSelectionEnd();
CommitSelectionReceiver csr = null;
- if (newSelStart != oldSelStart || newSelEnd != oldSelEnd) {
+ if (newSelStart != oldSelStart || newSelEnd != oldSelEnd ||
+ didTouchFocusSelect()) {
csr = new CommitSelectionReceiver(oldSelStart, oldSelEnd,
newSelStart, newSelEnd);
}
@@ -7475,7 +7483,7 @@
/**
* Update the controller's position.
*/
- public void updatePosition(int offset);
+ public void updatePosition(int x, int y);
/**
* The controller and the cursor's positions can be link by a fixed offset,
@@ -7510,7 +7518,7 @@
// Vertical extension of the touch region
int mTopExtension, mBottomExtension;
// Position of the virtual finger position on screen
- int mHopSpotVertcalPosition;
+ int mHotSpotVerticalPosition;
Handle(Drawable drawable) {
mDrawable = drawable;
@@ -7523,8 +7531,7 @@
final int lineTop = mLayout.getLineTop(line);
final int lineBottom = mLayout.getLineBottom(line);
- mHopSpotVertcalPosition = lineTop + (bottom ? (3 * (lineBottom - lineTop)) / 4 :
- (lineBottom - lineTop) / 4);
+ mHotSpotVerticalPosition = lineTop;
final Rect bounds = sCursorControllerTempRect;
bounds.left = (int) (mLayout.getPrimaryHorizontal(offset) - drawableWidth / 2.0);
@@ -7544,7 +7551,7 @@
int boundTopBefore = bounds.top;
convertFromViewportToContentCoordinates(bounds);
- mHopSpotVertcalPosition += bounds.top - boundTopBefore;
+ mHotSpotVerticalPosition += bounds.top - boundTopBefore;
mDrawable.setBounds(bounds);
postInvalidate();
}
@@ -7570,7 +7577,7 @@
void postInvalidateDelayed(long delay) {
final Rect bounds = mDrawable.getBounds();
TextView.this.postInvalidateDelayed(delay, bounds.left, bounds.top,
- bounds.right, bounds.bottom);
+ bounds.right, bounds.bottom);
}
}
@@ -7595,7 +7602,7 @@
public void show() {
updateDrawablePosition();
- // Has to be done after updatePosition, so that previous position invalidate
+ // Has to be done after updateDrawablePosition, so that previous position invalidate
// in only done if necessary.
mIsVisible = true;
}
@@ -7620,7 +7627,7 @@
time -= DELAY_BEFORE_FADE_OUT;
if (time <= FADE_OUT_DURATION) {
final int alpha = (int)
- ((255.0 * (FADE_OUT_DURATION - time)) / FADE_OUT_DURATION);
+ ((255.0 * (FADE_OUT_DURATION - time)) / FADE_OUT_DURATION);
mHandle.mDrawable.setAlpha(alpha);
mHandle.postInvalidateDelayed(30);
} else {
@@ -7632,12 +7639,14 @@
}
}
- public void updatePosition(int offset) {
- if (offset == getSelectionStart()) {
- return; // No change, no need to redraw
+ public void updatePosition(int x, int y) {
+ final int previousOffset = getSelectionStart();
+ int offset = getHysteresisOffset(x, y, previousOffset);
+
+ if (offset != previousOffset) {
+ Selection.setSelection((Spannable) mText, offset);
+ updateDrawablePosition();
}
- Selection.setSelection((Spannable) mText, offset);
- updateDrawablePosition();
}
private void updateDrawablePosition() {
@@ -7683,7 +7692,7 @@
final Rect bounds = mHandle.mDrawable.getBounds();
mOffsetX = (bounds.left + bounds.right) / 2.0f - x;
- mOffsetY = mHandle.mHopSpotVertcalPosition - y;
+ mOffsetY = mHandle.mHotSpotVerticalPosition - y;
mOnDownTimerStart = event.getEventTime();
}
@@ -7738,7 +7747,7 @@
public void show() {
updateDrawablesPositions();
- // Has to be done after updatePosition, so that previous position invalidate
+ // Has to be done after updateDrawablePositions, so that previous position invalidate
// in only done if necessary.
mIsVisible = true;
mFadeOutTimerStart = -1;
@@ -7780,10 +7789,13 @@
}
}
- public void updatePosition(int offset) {
+ public void updatePosition(int x, int y) {
int selectionStart = getSelectionStart();
int selectionEnd = getSelectionEnd();
+ final int previousOffset = mStartIsDragged ? selectionStart : selectionEnd;
+ int offset = getHysteresisOffset(x, y, previousOffset);
+
// Handle the case where start and end are swapped, making sure start <= end
if (mStartIsDragged) {
if (offset <= selectionEnd) {
@@ -7865,7 +7877,7 @@
final Handle draggedHandle = mStartIsDragged ? mStartHandle : mEndHandle;
final Rect bounds = draggedHandle.mDrawable.getBounds();
mOffsetX = (bounds.left + bounds.right) / 2.0f - x;
- mOffsetY = draggedHandle.mHopSpotVertcalPosition - y;
+ mOffsetY = draggedHandle.mHotSpotVerticalPosition - y;
((ArrowKeyMovementMethod)mMovement).setCursorController(this);
}
@@ -7935,6 +7947,15 @@
stopTextSelectionMode();
}
+ private int getOffsetForHorizontal(int line, int x) {
+ x -= getTotalPaddingLeft();
+ // Clamp the position to inside of the view.
+ x = Math.max(0, x);
+ x = Math.min(getWidth() - getTotalPaddingRight() - 1, x);
+ x += getScrollX();
+ return getLayout().getOffsetForHorizontal(line, x);
+ }
+
/**
* Get the offset character closest to the specified absolute position.
*
@@ -7946,32 +7967,44 @@
* @hide
*/
public int getOffset(int x, int y) {
- x -= getTotalPaddingLeft();
+ if (getLayout() == null) return -1;
+
y -= getTotalPaddingTop();
-
// Clamp the position to inside of the view.
- if (x < 0) {
- x = 0;
- } else if (x >= (getWidth() - getTotalPaddingRight())) {
- x = getWidth()-getTotalPaddingRight() - 1;
- }
- if (y < 0) {
- y = 0;
- } else if (y >= (getHeight() - getTotalPaddingBottom())) {
- y = getHeight()-getTotalPaddingBottom() - 1;
- }
-
- x += getScrollX();
+ y = Math.max(0, y);
+ y = Math.min(getHeight() - getTotalPaddingBottom() - 1, y);
y += getScrollY();
- Layout layout = getLayout();
- if (layout != null) {
- final int line = layout.getLineForVertical(y);
- final int offset = layout.getOffsetForHorizontal(line, x);
- return offset;
- } else {
- return -1;
+ final int line = getLayout().getLineForVertical(y);
+ final int offset = getOffsetForHorizontal(line, x);
+ return offset;
+ }
+
+ int getHysteresisOffset(int x, int y, int previousOffset) {
+ final Layout layout = getLayout();
+ if (layout == null) return -1;
+
+ y -= getTotalPaddingTop();
+ // Clamp the position to inside of the view.
+ y = Math.max(0, y);
+ y = Math.min(getHeight() - getTotalPaddingBottom() - 1, y);
+ y += getScrollY();
+
+ int line = getLayout().getLineForVertical(y);
+
+ final int previousLine = layout.getLineForOffset(previousOffset);
+ final int previousLineTop = layout.getLineTop(previousLine);
+ final int previousLineBottom = layout.getLineBottom(previousLine);
+ final int hysteresisThreshold = (previousLineBottom - previousLineTop) / 2;
+
+ // If new line is just before or after previous line and y position is less than
+ // hysteresisThreshold away from previous line, keep cursor on previous line.
+ if (((line == previousLine + 1) && ((y - previousLineBottom) < hysteresisThreshold)) ||
+ ((line == previousLine - 1) && ((previousLineTop - y) < hysteresisThreshold))) {
+ line = previousLine;
}
+
+ return getOffsetForHorizontal(line, x);
}
@ViewDebug.ExportedProperty
diff --git a/core/java/com/android/internal/widget/LockPatternUtils.java b/core/java/com/android/internal/widget/LockPatternUtils.java
index dbbd286..c788605 100644
--- a/core/java/com/android/internal/widget/LockPatternUtils.java
+++ b/core/java/com/android/internal/widget/LockPatternUtils.java
@@ -19,6 +19,7 @@
import android.app.admin.DevicePolicyManager;
import android.content.ContentResolver;
import android.content.Context;
+import android.os.FileObserver;
import android.os.RemoteException;
import android.os.ServiceManager;
import android.os.SystemClock;
@@ -33,6 +34,7 @@
import com.android.internal.telephony.ITelephony;
import com.google.android.collect.Lists;
+import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.RandomAccessFile;
@@ -40,6 +42,7 @@
import java.security.SecureRandom;
import java.util.Arrays;
import java.util.List;
+import java.util.concurrent.atomic.AtomicBoolean;
/**
* Utilities for the lock patten and its settings.
@@ -48,8 +51,9 @@
private static final String TAG = "LockPatternUtils";
- private static final String LOCK_PATTERN_FILE = "/system/gesture.key";
- private static final String LOCK_PASSWORD_FILE = "/system/password.key";
+ private static final String SYSTEM_DIRECTORY = "/system/";
+ private static final String LOCK_PATTERN_FILE = "gesture.key";
+ private static final String LOCK_PASSWORD_FILE = "password.key";
/**
* The maximum number of incorrect attempts before the user is prevented
@@ -98,6 +102,10 @@
private static String sLockPatternFilename;
private static String sLockPasswordFilename;
+ private static final AtomicBoolean sHaveNonZeroPatternFile = new AtomicBoolean(false);
+ private static final AtomicBoolean sHaveNonZeroPasswordFile = new AtomicBoolean(false);
+ private static FileObserver sPasswordObserver;
+
public DevicePolicyManager getDevicePolicyManager() {
if (mDevicePolicyManager == null) {
mDevicePolicyManager =
@@ -115,14 +123,31 @@
public LockPatternUtils(Context context) {
mContext = context;
mContentResolver = context.getContentResolver();
- // Initialize the location of gesture lock file
- if (sLockPatternFilename == null) {
- sLockPatternFilename = android.os.Environment.getDataDirectory()
- .getAbsolutePath() + LOCK_PATTERN_FILE;
- sLockPasswordFilename = android.os.Environment.getDataDirectory()
- .getAbsolutePath() + LOCK_PASSWORD_FILE;
- }
+ // Initialize the location of gesture & PIN lock files
+ if (sLockPatternFilename == null) {
+ String dataSystemDirectory =
+ android.os.Environment.getDataDirectory().getAbsolutePath() +
+ SYSTEM_DIRECTORY;
+ sLockPatternFilename = dataSystemDirectory + LOCK_PATTERN_FILE;
+ sLockPasswordFilename = dataSystemDirectory + LOCK_PASSWORD_FILE;
+ sHaveNonZeroPatternFile.set(new File(sLockPatternFilename).length() > 0);
+ sHaveNonZeroPasswordFile.set(new File(sLockPasswordFilename).length() > 0);
+ int fileObserverMask = FileObserver.CLOSE_WRITE | FileObserver.DELETE |
+ FileObserver.MOVED_TO | FileObserver.CREATE;
+ sPasswordObserver = new FileObserver(dataSystemDirectory, fileObserverMask) {
+ public void onEvent(int event, String path) {
+ if (LOCK_PATTERN_FILE.equals(path)) {
+ Log.d(TAG, "lock pattern file changed");
+ sHaveNonZeroPatternFile.set(new File(sLockPatternFilename).length() > 0);
+ } else if (LOCK_PASSWORD_FILE.equals(path)) {
+ Log.d(TAG, "lock password file changed");
+ sHaveNonZeroPasswordFile.set(new File(sLockPasswordFilename).length() > 0);
+ }
+ }
+ };
+ sPasswordObserver.startWatching();
+ }
}
public int getRequestedMinimumPasswordLength() {
@@ -202,31 +227,11 @@
}
/**
- * Checks to see if the given file exists and contains any data. Returns true if it does,
- * false otherwise.
- * @param filename
- * @return true if file exists and is non-empty.
- */
- private boolean nonEmptyFileExists(String filename) {
- try {
- // Check if we can read a byte from the file
- RandomAccessFile raf = new RandomAccessFile(filename, "r");
- raf.readByte();
- raf.close();
- return true;
- } catch (FileNotFoundException fnfe) {
- return false;
- } catch (IOException ioe) {
- return false;
- }
- }
-
- /**
* Check to see if the user has stored a lock pattern.
* @return Whether a saved pattern exists.
*/
public boolean savedPatternExists() {
- return nonEmptyFileExists(sLockPatternFilename);
+ return sHaveNonZeroPatternFile.get();
}
/**
@@ -234,7 +239,7 @@
* @return Whether a saved pattern exists.
*/
public boolean savedPasswordExists() {
- return nonEmptyFileExists(sLockPasswordFilename);
+ return sHaveNonZeroPasswordFile.get();
}
/**
diff --git a/core/jni/AndroidRuntime.cpp b/core/jni/AndroidRuntime.cpp
index 407d2e7..62a4495 100644
--- a/core/jni/AndroidRuntime.cpp
+++ b/core/jni/AndroidRuntime.cpp
@@ -506,7 +506,7 @@
static void readLocale(char* language, char* region)
{
char propLang[PROPERTY_VALUE_MAX], propRegn[PROPERTY_VALUE_MAX];
-
+
property_get("persist.sys.language", propLang, "");
property_get("persist.sys.country", propRegn, "");
if (*propLang == 0 && *propRegn == 0) {
@@ -710,6 +710,33 @@
LOGW("dalvik.vm.gc.overwritefree should be 'true' or 'false'");
}
+ /* enable heap verification before each gc */
+ property_get("dalvik.vm.gc.preverify", propBuf, "false");
+ if (strcmp(propBuf, "true") == 0) {
+ opt.optionString = "-Xgc:preverify";
+ mOptions.add(opt);
+ } else if (strcmp(propBuf, "false") != 0) {
+ LOGW("dalvik.vm.gc.preverify should be 'true' or 'false'");
+ }
+
+ /* enable heap verification after each gc */
+ property_get("dalvik.vm.gc.postverify", propBuf, "false");
+ if (strcmp(propBuf, "true") == 0) {
+ opt.optionString = "-Xgc:postverify";
+ mOptions.add(opt);
+ } else if (strcmp(propBuf, "false") != 0) {
+ LOGW("dalvik.vm.gc.postverify should be 'true' or 'false'");
+ }
+
+ /* enable card table verification for partial gc */
+ property_get("dalvik.vm.gc.verifycardtable", propBuf, "false");
+ if (strcmp(propBuf, "true") == 0) {
+ opt.optionString = "-Xgc:verifycardtable";
+ mOptions.add(opt);
+ } else if (strcmp(propBuf, "false") != 0) {
+ LOGW("dalvik.vm.gc.verifycardtable should be 'true' or 'false'");
+ }
+
/* enable debugging; set suspend=y to pause during VM init */
#ifdef HAVE_ANDROID_OS
/* use android ADB transport */
@@ -757,16 +784,6 @@
}
#if defined(WITH_JIT)
- /* Minimal profile threshold to trigger JIT compilation */
- char jitThresholdBuf[sizeof("-Xjitthreshold:") + PROPERTY_VALUE_MAX];
- property_get("dalvik.vm.jit.threshold", propBuf, "");
- if (strlen(propBuf) > 0) {
- strcpy(jitThresholdBuf, "-Xjitthreshold:");
- strcat(jitThresholdBuf, propBuf);
- opt.optionString = jitThresholdBuf;
- mOptions.add(opt);
- }
-
/* Force interpreter-only mode for selected opcodes. Eg "1-0a,3c,f1-ff" */
char jitOpBuf[sizeof("-Xjitop:") + PROPERTY_VALUE_MAX];
property_get("dalvik.vm.jit.op", propBuf, "");
@@ -777,16 +794,6 @@
mOptions.add(opt);
}
- /*
- * Reverse the polarity of dalvik.vm.jit.op and force interpreter-only
- * for non-selected opcodes.
- */
- property_get("dalvik.vm.jit.includeop", propBuf, "");
- if (strlen(propBuf) > 0) {
- opt.optionString = "-Xincludeselectedop";
- mOptions.add(opt);
- }
-
/* Force interpreter-only mode for selected methods */
char jitMethodBuf[sizeof("-Xjitmethod:") + PROPERTY_VALUE_MAX];
property_get("dalvik.vm.jit.method", propBuf, "");
@@ -796,37 +803,6 @@
opt.optionString = jitMethodBuf;
mOptions.add(opt);
}
-
- /*
- * Reverse the polarity of dalvik.vm.jit.method and force interpreter-only
- * for non-selected methods.
- */
- property_get("dalvik.vm.jit.includemethod", propBuf, "");
- if (strlen(propBuf) > 0) {
- opt.optionString = "-Xincludeselectedmethod";
- mOptions.add(opt);
- }
-
- /*
- * Enable profile collection on JIT'ed code.
- */
- property_get("dalvik.vm.jit.profile", propBuf, "");
- if (strlen(propBuf) > 0) {
- opt.optionString = "-Xjitprofile";
- mOptions.add(opt);
- }
-
- /*
- * Disable optimizations by setting the corresponding bit to 1.
- */
- char jitOptBuf[sizeof("-Xjitdisableopt:") + PROPERTY_VALUE_MAX];
- property_get("dalvik.vm.jit.disableopt", propBuf, "");
- if (strlen(propBuf) > 0) {
- strcpy(jitOptBuf, "-Xjitdisableopt:");
- strcat(jitOptBuf, propBuf);
- opt.optionString = jitOptBuf;
- mOptions.add(opt);
- }
#endif
if (executionMode == kEMIntPortable) {
diff --git a/core/tests/coretests/src/android/pim/vcard/ExportTestResolver.java b/core/tests/coretests/src/android/pim/vcard/ExportTestResolver.java
index 5968e83..951d0d8 100644
--- a/core/tests/coretests/src/android/pim/vcard/ExportTestResolver.java
+++ b/core/tests/coretests/src/android/pim/vcard/ExportTestResolver.java
@@ -24,6 +24,7 @@
import android.provider.ContactsContract.Contacts;
import android.provider.ContactsContract.Data;
import android.provider.ContactsContract.RawContacts;
+import android.test.mock.MockContentProvider;
import android.test.mock.MockContentResolver;
import android.test.mock.MockCursor;
@@ -44,6 +45,10 @@
public ContactEntry addInputContactEntry() {
return mProvider.buildInputEntry();
}
+
+ public ExportTestProvider getProvider() {
+ return mProvider;
+ }
}
/* package */ class MockEntityIterator implements EntityIterator {
diff --git a/core/tests/coretests/src/android/pim/vcard/ImportTestResolver.java b/core/tests/coretests/src/android/pim/vcard/ImportTestResolver.java
index c3f6f79..1563da9 100644
--- a/core/tests/coretests/src/android/pim/vcard/ImportTestResolver.java
+++ b/core/tests/coretests/src/android/pim/vcard/ImportTestResolver.java
@@ -19,8 +19,6 @@
import android.content.ContentProviderResult;
import android.content.ContentValues;
import android.net.Uri;
-import android.provider.ContactsContract.Data;
-import android.provider.ContactsContract.RawContacts;
import android.provider.ContactsContract.CommonDataKinds.Email;
import android.provider.ContactsContract.CommonDataKinds.Event;
import android.provider.ContactsContract.CommonDataKinds.GroupMembership;
@@ -34,6 +32,9 @@
import android.provider.ContactsContract.CommonDataKinds.StructuredName;
import android.provider.ContactsContract.CommonDataKinds.StructuredPostal;
import android.provider.ContactsContract.CommonDataKinds.Website;
+import android.provider.ContactsContract.Data;
+import android.provider.ContactsContract.RawContacts;
+import android.test.mock.MockContentProvider;
import android.test.mock.MockContentResolver;
import android.text.TextUtils;
@@ -45,10 +46,10 @@
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
+import java.util.Map.Entry;
import java.util.Set;
import java.util.SortedMap;
import java.util.TreeMap;
-import java.util.Map.Entry;
/* package */ class ImportTestResolver extends MockContentResolver {
final ImportTestProvider mProvider;
diff --git a/core/tests/coretests/src/android/pim/vcard/VCardExporterTests.java b/core/tests/coretests/src/android/pim/vcard/VCardExporterTests.java
index 2de0464..2962a926 100644
--- a/core/tests/coretests/src/android/pim/vcard/VCardExporterTests.java
+++ b/core/tests/coretests/src/android/pim/vcard/VCardExporterTests.java
@@ -438,14 +438,26 @@
.put(Phone.TYPE, Phone.TYPE_CUSTOM)
.put(Phone.LABEL, "invalid");
PropertyNodesVerifierElem elem = mVerifier.addPropertyNodesVerifierElemWithEmptyName();
- elem.addExpectedNode("TEL", "1", new TypeSet("MODEM"))
- .addExpectedNode("TEL", "2", new TypeSet("MSG"))
- .addExpectedNode("TEL", "3", new TypeSet("BBS"))
- .addExpectedNode("TEL", "4", new TypeSet("VIDEO"))
- .addExpectedNode("TEL", "5", new TypeSet("VOICE"))
- .addExpectedNode("TEL", "6", new TypeSet("CELL"))
- .addExpectedNode("TEL", "7", new TypeSet("CELL"))
- .addExpectedNode("TEL", "8", new TypeSet("X-invalid"));
+ if (VCardConfig.isV30(vcardType)) {
+ // vCard 3.0 accepts "invalid". Also stop using toUpper()
+ elem.addExpectedNode("TEL", "1", new TypeSet("Modem"))
+ .addExpectedNode("TEL", "2", new TypeSet("MSG"))
+ .addExpectedNode("TEL", "3", new TypeSet("BBS"))
+ .addExpectedNode("TEL", "4", new TypeSet("VIDEO"))
+ .addExpectedNode("TEL", "5", new TypeSet("VOICE"))
+ .addExpectedNode("TEL", "6", new TypeSet("CELL"))
+ .addExpectedNode("TEL", "7", new TypeSet("CELL"))
+ .addExpectedNode("TEL", "8", new TypeSet("invalid"));
+ } else {
+ elem.addExpectedNode("TEL", "1", new TypeSet("MODEM"))
+ .addExpectedNode("TEL", "2", new TypeSet("MSG"))
+ .addExpectedNode("TEL", "3", new TypeSet("BBS"))
+ .addExpectedNode("TEL", "4", new TypeSet("VIDEO"))
+ .addExpectedNode("TEL", "5", new TypeSet("VOICE"))
+ .addExpectedNode("TEL", "6", new TypeSet("CELL"))
+ .addExpectedNode("TEL", "7", new TypeSet("CELL"))
+ .addExpectedNode("TEL", "8", new TypeSet("X-invalid"));
+ }
}
public void testPhoneTypeHandlingV21() {
diff --git a/core/tests/coretests/src/android/pim/vcard/VCardTestsBase.java b/core/tests/coretests/src/android/pim/vcard/VCardTestsBase.java
index 0857e0c..9c6003f 100644
--- a/core/tests/coretests/src/android/pim/vcard/VCardTestsBase.java
+++ b/core/tests/coretests/src/android/pim/vcard/VCardTestsBase.java
@@ -16,101 +16,14 @@
package android.pim.vcard;
-import android.content.ContentProvider;
-import android.content.ContentProviderOperation;
-import android.content.ContentProviderResult;
import android.content.ContentValues;
-import android.content.EntityIterator;
-import android.content.res.AssetFileDescriptor;
-import android.database.Cursor;
-import android.database.CursorWindow;
-import android.database.IBulkCursor;
-import android.database.IContentObserver;
-import android.net.Uri;
-import android.os.IBinder;
-import android.os.ParcelFileDescriptor;
-import android.os.RemoteException;
-import android.pim.vcard.VCardConfig;
import android.test.AndroidTestCase;
-import android.util.Log;
-
-import java.util.ArrayList;
-
-/**
- * Almost a dead copy of android.test.mock.MockContentProvider, but different in that this
- * class extends ContentProvider, not implementing IContentProvider,
- * so that MockContentResolver is able to accept this class :(
- */
-class MockContentProvider extends ContentProvider {
- @Override
- public boolean onCreate() {
- return true;
- }
-
- @Override
- public int bulkInsert(Uri url, ContentValues[] initialValues) {
- throw new UnsupportedOperationException("unimplemented mock method");
- }
-
- @SuppressWarnings("unused")
- public IBulkCursor bulkQuery(Uri url, String[] projection, String selection,
- String[] selectionArgs, String sortOrder, IContentObserver observer,
- CursorWindow window) throws RemoteException {
- throw new UnsupportedOperationException("unimplemented mock method");
- }
-
- @Override
- @SuppressWarnings("unused")
- public int delete(Uri url, String selection, String[] selectionArgs) {
- throw new UnsupportedOperationException("unimplemented mock method");
- }
-
- @Override
- public String getType(Uri url) {
- throw new UnsupportedOperationException("unimplemented mock method");
- }
-
- @Override
- public Uri insert(Uri url, ContentValues initialValues) {
- throw new UnsupportedOperationException("unimplemented mock method");
- }
-
- @Override
- public ParcelFileDescriptor openFile(Uri url, String mode) {
- throw new UnsupportedOperationException("unimplemented mock method");
- }
-
- @Override
- public AssetFileDescriptor openAssetFile(Uri uri, String mode) {
- throw new UnsupportedOperationException("unimplemented mock method");
- }
-
- @Override
- public ContentProviderResult[] applyBatch(ArrayList<ContentProviderOperation> operations) {
- throw new UnsupportedOperationException("unimplemented mock method");
- }
-
- @Override
- public Cursor query(Uri url, String[] projection, String selection, String[] selectionArgs,
- String sortOrder) {
- throw new UnsupportedOperationException("unimplemented mock method");
- }
-
- @Override
- public int update(Uri url, ContentValues values, String selection, String[] selectionArgs) {
- throw new UnsupportedOperationException("unimplemented mock method");
- }
-
- public IBinder asBinder() {
- throw new UnsupportedOperationException("unimplemented mock method");
- }
-}
/**
* BaseClass for vCard unit tests with utility classes.
* Please do not add each unit test here.
*/
-/* package */ class VCardTestsBase extends AndroidTestCase {
+public class VCardTestsBase extends AndroidTestCase {
public static final int V21 = VCardConfig.VCARD_TYPE_V21_GENERIC_UTF8;
public static final int V30 = VCardConfig.VCARD_TYPE_V30_GENERIC_UTF8;
diff --git a/core/tests/coretests/src/android/pim/vcard/VCardVerifier.java b/core/tests/coretests/src/android/pim/vcard/VCardVerifier.java
index bfc3158..3cb5b9b 100644
--- a/core/tests/coretests/src/android/pim/vcard/VCardVerifier.java
+++ b/core/tests/coretests/src/android/pim/vcard/VCardVerifier.java
@@ -31,6 +31,7 @@
import android.pim.vcard.exception.VCardException;
import android.test.AndroidTestCase;
import android.test.mock.MockContext;
+import android.util.Log;
import java.io.ByteArrayInputStream;
import java.io.IOException;
@@ -51,6 +52,8 @@
}
/* package */ class VCardVerifier {
+ private static final String LOG_TAG = "VCardVerifier";
+
private class VCardVerifierInternal implements VCardComposer.OneEntryHandler {
public boolean onInit(Context context) {
return true;
@@ -267,10 +270,13 @@
final ContentResolver resolver,
final Uri uri, final String selection,
final String[] selectionArgs, final String sortOrder) {
- final ContentProvider provider =
- resolver.acquireContentProviderClient(uri).getLocalContentProvider();
- return ((ExportTestProvider)provider).queryEntities(
- uri, selection, selectionArgs, sortOrder);
+ if (ExportTestResolver.class.equals(resolver.getClass())) {
+ return ((ExportTestResolver)resolver).getProvider().queryEntities(
+ uri, selection, selectionArgs, sortOrder);
+ }
+
+ Log.e(LOG_TAG, "Unexpected provider given.");
+ return null;
}
private Method getMockGetEntityIteratorMethod()
@@ -285,18 +291,19 @@
composer.addHandler(mLineVerifier);
composer.addHandler(mVCardVerifierInternal);
if (!composer.init(VCardComposer.CONTACTS_TEST_CONTENT_URI, null, null, null)) {
- mTestCase.fail("init() failed. Reason: " + composer.getErrorReason());
+ AndroidTestCase.fail("init() failed. Reason: " + composer.getErrorReason());
}
- mTestCase.assertFalse(composer.isAfterLast());
+ AndroidTestCase.assertFalse(composer.isAfterLast());
try {
while (!composer.isAfterLast()) {
try {
final Method mockGetEntityIteratorMethod = getMockGetEntityIteratorMethod();
- mTestCase.assertTrue(
- composer.createOneEntry(getMockGetEntityIteratorMethod()));
+ AndroidTestCase.assertNotNull(mockGetEntityIteratorMethod);
+ AndroidTestCase.assertTrue(
+ composer.createOneEntry(mockGetEntityIteratorMethod));
} catch (Exception e) {
e.printStackTrace();
- mTestCase.fail();
+ AndroidTestCase.fail();
}
}
} finally {
diff --git a/docs/html/guide/guide_toc.cs b/docs/html/guide/guide_toc.cs
index d0318cf..35ce17e 100644
--- a/docs/html/guide/guide_toc.cs
+++ b/docs/html/guide/guide_toc.cs
@@ -220,9 +220,16 @@
<li><a style="color:gray;">Accelerometer</a></li>
</ul>
</li> -->
- <li><a href="<?cs var:toroot ?>guide/topics/location/index.html">
- <span class="en">Location and Maps</span>
- </a></li>
+ <li class="toggle-list">
+ <div><a href="<?cs var:toroot ?>guide/topics/location/index.html">
+ <span class="en">Location and Maps</span>
+ </a></div>
+ <ul>
+ <li><a href="<?cs var:toroot ?>guide/topics/location/obtaining-user-location.html">
+ <span class="en">Obtaining User Location</span>
+ </a> <span class="new">new!</span></li>
+ </ul>
+ </li>
<!--<li class="toggle-list">
<div><a style="color:gray;">Wireless Controls</a></div>
<ul>
diff --git a/docs/html/guide/topics/fundamentals.jd b/docs/html/guide/topics/fundamentals.jd
index f780e7c..6d6abd8 100644
--- a/docs/html/guide/topics/fundamentals.jd
+++ b/docs/html/guide/topics/fundamentals.jd
@@ -770,9 +770,9 @@
</p>
<p>
-For more on launch modes, see the description of the
-<code><a href="{@docRoot}guide/topics/manifest/activity-element.html"><activity></a></code>
-element.
+For more on launch modes, see the description of the <code><a
+href="{@docRoot}guide/topics/manifest/activity-element.html#lmode"><activity></a></code>
+element.
</p>
diff --git a/docs/html/guide/topics/location/index.jd b/docs/html/guide/topics/location/index.jd
index e988ecb..5f98902 100644
--- a/docs/html/guide/topics/location/index.jd
+++ b/docs/html/guide/topics/location/index.jd
@@ -4,94 +4,63 @@
<div id="qv-wrapper">
<div id="qv">
- <h2>Location and Maps quickview</h2>
+ <h2>Quickview</h2>
<ul>
- <li>Android provides a location framework that your application can use to determine the device's location and bearing and register for updates.</li>
- <li>A Google Maps external library is available that lets you display and manage Maps data.</li>
+ <li>Android provides a location framework that your application can use to determine the
+device's location and bearing and register for updates</li>
+ <li>A Google Maps external library is available that lets you display and manage Maps data</li>
</ul>
- <h2>In this document</h2>
+
+ <h2>Topics</h2>
<ol>
- <li><a href="#location">Location Services</a></li>
- <li><a href="#maps">Google Maps External Library</a></li>
+ <li><a href="{@docRoot}guide/topics/location/obtaining-user-location.html">Obtaining User
+Location</a></li>
</ol>
+
<h2>See Also</h2>
<ol>
- <li><a href="http://code.google.com/android/add-ons/google-apis/index.html">Google APIs add-on download»</a></li>
+ <li><a
+href="http://code.google.com/android/add-ons/google-apis/maps-overview.html">Google
+Maps External Library »</a></li>
</ol>
</div>
</div>
-<p>Location- and maps-based applications and services are compelling for mobile device users. You can build these capabilities into your applications using the classes of the {@link android.location} package and the Google Maps external library. The sections below provide details. </p>
+<p>Location and maps-based applications are compelling for mobile device users. You
+can build these capabilities into your applications using the classes of the {@link
+android.location} package and the Google Maps external library. The sections below provide details.
+</p>
<h2 id="location">Location Services</h2>
<p>Android gives your applications access to the location services supported by
-the device through the classes in the <code>android.location</code> package. The
+the device through the classes in the {@code android.location} package. The
central component of the location framework is the
-{@link android.location.LocationManager} system service, which provides an API to
-determine location and bearing if the underlying device (if it supports location
-capabilities). </p>
+{@link android.location.LocationManager} system service, which provides APIs to
+determine location and bearing of the underlying device (if available). </p>
-<p>As with other system services, you do not instantiate a LocationManager directly.
-Rather, you request an LocationManager instance from the system by calling
-{@link android.content.Context#getSystemService(String) getSystemService(Context.LOCATION_SERVICE)}.
-The method returns a handle to a new LocationManager instance.</p>
+<p>As with other system services, you do not instantiate a {@link android.location.LocationManager}
+directly. Rather, you request an instance from the system by calling
+{@link android.content.Context#getSystemService(String)
+getSystemService(Context.LOCATION_SERVICE)}. The method returns a handle to a new {@link
+android.location.LocationManager} instance.</p>
-<p>Once your application has a handle to a LocationManager instance, your application
-will be able to do three things:</p>
+<p>Once your application has a {@link android.location.LocationManager}, your application
+is able to do three things:</p>
<ul>
- <li>Query for the list of all LocationProviders known to the
- LocationManager for its last known location.</li>
- <li>Register/unregister for periodic updates of current location from a
- LocationProvider (specified either by Criteria or name).</li>
- <li>Register/unregister for a given Intent to be fired if the device comes
- within a given proximity (specified by radius in meters) of a given
- lat/long.</li>
+ <li>Query for the list of all {@link android.location.LocationProvider}s for the last known
+user location.</li>
+ <li>Register/unregister for periodic updates of the user's current location from a
+ location provider (specified either by criteria or name).</li>
+ <li>Register/unregister for a given {@link android.content.Intent} to be fired if the device
+comes within a given proximity (specified by radius in meters) of a given lat/long.</li>
</ul>
-<p>However, during initial development in the emulator, you may not have access to real
-data from a real location provider (Network or GPS). In that case, it may be necessary to
-spoof some data for your application using a mock location provider.</p>
+<p>For more information, read the guide to <a
+href="{@docRoot}guide/topics/location/obtaining-user-location.html">Obtaining User
+Location</a>.</p>
-<p class="note"><strong>Note:</strong> If you've used mock LocationProviders in
-previous versions of the SDK, you can no longer provide canned LocationProviders
-in the /system/etc/location directory. These directories will be wiped during boot-up.
-Please follow the new procedures outlined below.</p>
-
-<h3>Providing Mock Location Data</h3>
-
-<p>When testing your application on the Android emulator, there are a couple different
-ways to send it some mock location data: you can use the DDMS tool or the "geo" command
-option in the emulator console.</p>
-
-<h4 id="ddms">Using DDMS</h4>
-<p>With the DDMS tool, you can simulate location data a few different ways:</p>
-<ul>
- <li>Manually send individual longitude/latitude coordinates to the device.</li>
- <li>Use a GPX file describing a route for playback to the device.</li>
- <li>Use a KML file describing individual placemarks for sequenced playback to the device.</li>
-</ul>
-<p>For more information on using DDMS to spoof location data, see the
-<a href="{@docRoot}guide/developing/tools/ddms.html#emulator-control">Using DDMS guide</a>.
-
-<h4 id="geo">Using the "geo" command in the emulator console</h4>
-<p>Launch your application in the Android emulator and open a terminal/console in
-your SDK's <code>/tools</code> directory. Connect to the emulator console. Now you can use:</p>
-<ul><li><code>geo fix</code> to send a fixed geo-location.
- <p>This command accepts a longitude and latitude in decimal degrees, and
- an optional altitude in meters. For example:</p>
- <pre>geo fix -121.45356 46.51119 4392</pre>
- </li>
- <li><code>geo nmea</code> to send an NMEA 0183 sentence.
- <p>This command accepts a single NMEA sentence of type '$GPGGA' (fix data) or '$GPRMC' (transit data).
- For example:</p>
- <pre>geo nmea $GPRMC,081836,A,3751.65,S,14507.36,E,000.0,360.0,130998,011.3,E*62</pre>
- </li>
-</ul>
-
-<p>For information about how to connect to the emulator console, see
-<a href="{@docRoot}guide/developing/tools/emulator.html#console">Using the Emulator Console</a>.</p>
<h2 id="maps">Google Maps External Library</h2>
@@ -128,9 +97,9 @@
<p style="margin-left:2em;"><a
href="http://code.google.com/android/add-ons/google-apis">http://code.google.com/android/add-ons/google-apis</a></p>
-<p>For your convenience, the Google APIs add-on is also included in the Android
-SDK. <!-- To learn now to use the Maps external library in your application, see
-[[Using External Libraries]].--></p>
+<p>For your convenience, the Google APIs add-on is also available as a downloadable component from
+the Android SDK and AVD Manager (see <a href="{@docRoot}sdk/adding-components.html">Adding SDK
+Components</a>).</p>
<p class="note"><strong>Note:</strong> In order to display Google Maps data in a
MapView, you must register with the Google Maps service and obtain a Maps API
diff --git a/docs/html/guide/topics/location/obtaining-user-location.jd b/docs/html/guide/topics/location/obtaining-user-location.jd
new file mode 100644
index 0000000..bc782d2
--- /dev/null
+++ b/docs/html/guide/topics/location/obtaining-user-location.jd
@@ -0,0 +1,454 @@
+page.title=Obtaining User Location
+parent.title=Location and Maps
+parent.link=index.html
+@jd:body
+
+<div id="qv-wrapper">
+<div id="qv">
+
+ <h2>Quickview</h2>
+ <ul>
+ <li>The Network Location Provider provides good location data without using GPS</li>
+ <li>Obtaining user location can consume a lot of battery, so be careful how
+long you listen for updates</li>
+ </ul>
+ <h2>In this document</h2>
+ <ol>
+ <li><a href="#Challenges">Challenges in Determining User Location</a></li>
+ <li><a href="#Updates">Requesting Location Updates</a>
+ <ol>
+ <li><a href="#Permission">Requesting User Permissions</a></li>
+ </ol>
+ </li>
+ <li><a href="#BestPerformance">Defining a Model for the Best Performance</a>
+ <ol>
+ <li><a href="#Flow">Flow for obtaining user location</a></li>
+ <li><a href="#StartListening">Deciding when to start listening for updates</a></li>
+ <li><a href="#FastFix">Getting a fast fix with the last known location</a></li>
+ <li><a href="#StopListening">Deciding when to stop listening for updates</a></li>
+ <li><a href="#BestEstimate">Maintaining a current best estimate</a></li>
+ <li><a href="#Adjusting">Adjusting the model to save battery and data exchange</a></li>
+ </ol>
+ </li>
+ <li><a href="#MockData">Providing Mock Location Data</a></li>
+ </ol>
+ <h2>Key classes</h2>
+ <ol>
+ <li>{@link android.location.LocationManager}</li>
+ <li>{@link android.location.LocationListener}</li>
+ </ol>
+</div>
+</div>
+
+ <p>Knowing where the user is allows your application to be smarter and deliver
+better information to the user. When developing a location-aware application for Android, you can
+utilize GPS and Android's Network Location Provider to acquire the user location. Although
+GPS is most accurate, it only works outdoors, it quickly consumes battery power, and doesn't return
+the location as quickly as users want. Android's Network Location Provider determines user location
+using cell tower and Wi-Fi signals, providing location information in a way that
+works indoors and outdoors, responds faster, and uses less battery power. To obtain the user
+location in your application, you can use both GPS and the Network Location Provider, or just
+one.</p>
+
+
+<h2 id="Challenges">Challenges in Determining User Location</h2>
+
+<p>Obtaining user location from a mobile device can be complicated. There are several reasons
+why a location reading (regardless of the source) can contain errors and be inaccurate.
+Some sources of error in the user location include:</p>
+
+<ul>
+ <li><b>Multitude of location sources</b>
+ <p>GPS, Cell-ID, and Wi-Fi can each provide a clue to users location. Determining which to use
+and trust is a matter of trade-offs in accuracy, speed, and battery-efficiency.</p>
+ </li>
+ <li><b>User movement</b>
+ <p>Because the user location changes, you must account for movement by re-estimating user
+location every so often.</p>
+ </li>
+ <li><b>Varying accuracy</b>
+ <p>Location estimates coming from each location source are not consistent in their
+accuracy. A location obtained 10 seconds ago from one source might be more accurate than the newest
+location from another or same source.</p>
+ </li>
+</ul>
+
+ <p>These problems can make it difficult to obtain a reliable user location reading. This
+document provides information to help you meet these challenges to obtain a reliable location
+reading. It also provides ideas that you can use in your
+application to provide the user with an accurate and responsive geo-location experience.</p>
+
+
+<h2 id="Updates">Requesting Location Updates</h2>
+
+ <p>Before addressing some of the location errors described above, here is an introduction to
+how you can obtain user location on Android.</p>
+
+ <p>Getting user location in Android works by means of callback. You indicate that you'd
+like to receive location updates from the {@link android.location.LocationManager} ("Location
+Manager") by calling {@link android.location.LocationManager#requestLocationUpdates
+requestLocationUpdates()}, passing it a
+{@link android.location.LocationListener}. Your {@link android.location.LocationListener} must
+implement several callback methods that the Location Manager calls when the user location
+changes or when the status of the service changes.</p>
+
+<p>For example, the following code shows how to define a {@link android.location.LocationListener}
+and request location updates:
+ </p>
+
+<pre>
+// Acquire a reference to the system Location Manager
+LocationManager locationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
+
+// Define a listener that responds to location updates
+LocationListener locationListener = new LocationListener() {
+ public void onLocationChanged(Location location) {
+ // Called when a new location is found by the network location provider.
+ makeUseOfNewLocation(location);
+ }
+
+ public void onStatusChanged(String provider, int status, Bundle extras) {}
+
+ public void onProviderEnabled(String provider) {}
+
+ public void onProviderDisabled(String provider) {}
+ };
+
+// Register the listener with the Location Manager to receive location updates
+locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, locationListener);
+</pre>
+
+ <p>The first parameter in {@link
+android.location.LocationManager#requestLocationUpdates requestLocationUpdates()} is the type of
+location provider to use (in this case, the Network Location Provider for cell tower and Wi-Fi
+based location). You can control the frequency at which your listener receives updates
+with the second and third parameter—the second is the minimum time interval between
+notifications and the third is the minimum change in distance between notifications—setting
+both to zero requests location notifications as frequently as possible. The last parameter is your
+{@link android.location.LocationListener}, which receives callbacks for location updates.</p>
+
+<p>To request location updates from the GPS provider,
+substitute <code>GPS_PROVIDER</code> for <code>NETWORK_PROVIDER</code>. You can also request
+location updates from both the GPS and the Network Location Provider by calling {@link
+android.location.LocationManager#requestLocationUpdates requestLocationUpdates()} twice—once
+for <code>NETWORK_PROVIDER</code> and once for <code>GPS_PROVIDER</code>.</p>
+
+
+<h3 id="Permission">Requesting User Permissions</h3>
+
+<p>In order to receive location updates from <code>NETWORK_PROVIDER</code> or
+<code>GPS_PROVIDER</code>, you must request user permission by declaring either the {@code
+ACCESS_COARSE_LOCATION} or {@code ACCESS_FINE_LOCATION} permission, respectively, in your Android
+manifest file. For example:</p>
+
+<pre>
+<manifest ... >
+ <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
+ ...
+</manifest>
+</pre>
+
+<p>Without these permissions, your application will fail at runtime when requesting
+location updates.</p>
+
+<p class="note"><strong>Note:</strong> If you are using both <code>NETWORK_PROVIDER</code> and
+<code>GPS_PROVIDER</code>, then you need to request only the {@code ACCESS_FINE_LOCATION}
+permission, because it includes permission for both providers. (Permission for {@code
+ACCESS_COARSE_LOCATION} includes permission only for <code>NETWORK_PROVIDER</code>.)</p>
+
+
+<h2 id="BestPerformance">Defining a Model for the Best Performance</h2>
+
+ <p>Location-based applications are now commonplace, but due to the less than optimal
+accuracy, user movement, the multitude of methods to obtain the location, and the desire to conserve
+battery, getting user location is complicated. To overcome the obstacles of obtaining a good user
+location while preserving battery power, you must define a consistent model that specifies how your
+application obtains the user location. This model includes when you start and stop listening for
+updates and when to use cached location data.</p>
+
+
+ <h3 id="Flow">Flow for obtaining user location</h3>
+
+ <p>Here's the typical flow of procedures for obtaining the user location:</p>
+
+ <ol>
+ <li>Start application.</li>
+ <li>Sometime later, start listening for updates from desired location providers.</li>
+ <li>Maintain a "current best estimate" of location by filtering out new, but less accurate
+fixes.</li>
+ <li>Stop listening for location updates.</li>
+ <li>Take advantage of the last best location estimate.</li>
+ </ol>
+
+ <p>Figure 1 demonstrates this model in a timeline that visualizes the period in which an
+application is listening for location updates and the events that occur during that time.</p>
+
+<img src="{@docRoot}images/location/getting-location.png" alt="" />
+<p class="img-caption"><strong>Figure 1.</strong> A timeline representing the window in which an
+application listens for location updates.</p>
+
+ <p>This model of a window—during which location updates are received—frames many of
+the decisions you need to make when adding location-based services to your application.</p>
+
+
+ <h3 id="StartListening">Deciding when to start listening for updates</h3>
+
+ <p>You might want to start listening for location updates as soon as your application starts, or
+only after users activate a certain feature. Be aware that long windows of listening for location
+fixes can consume a lot of battery power, but short periods might not allow for sufficient
+accuracy.</p>
+
+ <p>As demonstrated above, you can begin listening for updates by calling {@link
+android.location.LocationManager#requestLocationUpdates requestLocationUpdates()}:</p>
+
+<pre>
+LocationProvider locationProvider = LocationManager.NETWORK_PROVIDER;
+// Or, use GPS location data:
+// LocationProvider locationProvider = LocationManager.GPS_PROVIDER;
+
+locationManager.requestLocationUpdates(locationProvider, 0, 0, locationListener);
+</pre>
+
+
+ <h3 id="FastFix">Getting a fast fix with the last known location</h3>
+
+ <p>The time it takes for your location listener to receive the first location fix is often too
+long for users wait. Until a more accurate location is provided to your location listener, you
+should utilize a cached location by calling {@link
+android.location.LocationManager#getLastKnownLocation}:</p>
+<pre>
+LocationProvider locationProvider = LocationManager.NETWORK_PROVIDER;
+// Or use LocationManager.GPS_PROVIDER
+
+Location lastKnownLocation = locationManager.getLastKnownLocation(locationProvider);
+</pre>
+
+
+ <h3 id="StopListening">Deciding when to stop listening for updates</h3>
+
+ <p>The logic of deciding when new fixes are no longer necessary might range from very simple to
+very complex depending on your application. A short gap between when the location is acquired and
+when the location is used, improves the accuracy of the estimate. Always beware that listening for a
+long time consumes a lot of battery power, so as soon as you have the information you need, you
+should stop
+listening for updates by calling {@link android.location.LocationManager#removeUpdates}:</p>
+<pre>
+// Remove the listener you previously added
+locationManager.removeUpdates(locationListener);
+</pre>
+
+
+ <h3 id="BestEstimate">Maintaining a current best estimate</h3>
+
+ <p>You might expect that the most recent location fix is the most accurate.
+However, because the accuracy of a location fix varies, the most recent fix is not always the best.
+You should include logic for choosing location fixes based on several criteria. The criteria also
+varies depending on the use-cases of the application and field testing.</p>
+
+ <p>Here are a few steps you can take to validate the accuracy of a location fix:</p>
+ <ul>
+ <li>Check if the location retrieved is significantly newer than the previous estimate.</li>
+ <li>Check if the accuracy claimed by the location is better or worse than the previous
+estimate.</li>
+ <li>Check which provider the new location is from and determine if you trust it more.</li>
+ </ul>
+
+ <p>An elaborate example of this logic can look something like this:</p>
+
+<pre>
+private static final int TWO_MINUTES = 1000 * 60 * 2;
+
+/** Determines whether one Location reading is better than the current Location fix
+ * @param location The new Location that you want to evaluate
+ * @param currentBestLocation The current Location fix, to which you want to compare the new one
+ */
+protected boolean isBetterLocation(Location location, Location currentBestLocation) {
+ if (currentBestLocation == null) {
+ // A new location is always better than no location
+ return true;
+ }
+
+ // Check whether the new location fix is newer or older
+ long timeDelta = location.getTime() - currentBestLocation.getTime();
+ boolean isSignificantlyNewer = timeDelta > TWO_MINUTES;
+ boolean isSignificantlyOlder = timeDelta < -TWO_MINUTES;
+ boolean isNewer = timeDelta > 0;
+
+ // If it's been more than two minutes since the current location, use the new location
+ // because the user has likely moved
+ if (isSignificantlyNewer) {
+ return true;
+ // If the new location is more than two minutes older, it must be worse
+ } else if (isSignificantlyOlder) {
+ return false;
+ }
+
+ // Check whether the new location fix is more or less accurate
+ int accuracyDelta = (int) (location.getAccuracy() - currentBestLocation.getAccuracy());
+ boolean isLessAccurate = accuracyDelta > 0;
+ boolean isMoreAccurate = accuracyDelta < 0;
+ boolean isSignificantlyLessAccurate = accuracyDelta > 200;
+
+ // Check if the old and new location are from the same provider
+ boolean isFromSameProvider = isSameProvider(location.getProvider(),
+ currentBestLocation.getProvider());
+
+ // Determine location quality using a combination of timeliness and accuracy
+ if (isMoreAccurate) {
+ return true;
+ } else if (isNewer && !isLessAccurate) {
+ return true;
+ } else if (isNewer && !isSignificantlyLessAccurate && isFromSameProvider) {
+ return true;
+ }
+ return false;
+}
+
+/** Checks whether two providers are the same */
+private boolean isSameProvider(String provider1, String provider2) {
+ if (provider1 == null) {
+ return provider2 == null;
+ }
+ return provider1.equals(provider2);
+}
+</pre>
+
+
+ <h3 id="Adjusting">Adjusting the model to save battery and data exchange</h3>
+
+ <p>As you test your application, you might find that your model for providing good location and
+good performance needs some adjustment. Here are some things you might change to find a good
+balance between the two.</p>
+
+ <h4>Reduce the size of the window</h4>
+
+ <p>A smaller window in which you listen for location updates means less interaction with GPS and
+network location services, thus, preserving battery life. But it also allows for fewer locations
+from which to choose a best estimate.</p>
+
+ <h4>Set the location providers to return updates less frequently</h4>
+
+ <p>Reducing the rate at which new updates appear during the window can also improve battery
+efficiency, but at the cost of accuracy. The value of the trade-off depends on how your
+application is used. You can reduce the rate of updates by increasing the parameters in {@link
+android.location.LocationManager#requestLocationUpdates requestLocationUpdates()} that specify the
+interval time and minimum distance change.</p>
+
+ <h4>Restrict a set of providers</h4>
+
+ <p>Depending on the environment where your application is used or the desired level of accuracy,
+you might choose to use only the Network Location Provider or only GPS, instead of both. Interacting
+with only one of the services reduces battery usage at a potential cost of accuracy.</p>
+
+
+ <h2>Common application cases</h2>
+
+ <p>There are many reasons you might want to obtain the user location in your application. Below
+are a couple scenarios in which you can use the user location to enrich your application. Each
+scenario also describes good practices for when you should start and stop listening for the
+location, in order to get a good reading and help preserve battery life.</p>
+
+
+ <h3>Tagging user-created content with a location</h3>
+
+ <p>You might be creating an application where user-created content is tagged with a location.
+Think of users sharing their local experiences, posting a review for a restaurant, or recording some
+content that can be augmented with their current location. A model of how this
+interaction might happen, with respect to the location services, is visualized in figure 2.</p>
+
+ <img src="{@docRoot}images/location/content-tagging.png" alt="" />
+<p class="img-caption"><strong>Figure 2.</strong> A timeline representing the window in which
+the user location is obtained and listening stops when the user consumes the current location.</p>
+
+ <p>This lines up with the previous model of how user location is obtained in code (figure 1). For
+best location accuracy, you might choose to start listening for location updates when users begin
+creating
+the content or even when the application starts, then stop listening for updates when content is
+ready to be posted or recorded. You might need to consider how long a typical task of creating the
+content takes and judge if this duration allows for efficient collection of a location estimate.</p>
+
+
+ <h3>Helping the user decide on where to go</h3>
+
+ <p>You might be creating an application that attempts to provide users with a set
+of options about where to go. For example, you're looking to provide a list of nearby restaurants,
+stores, and entertainment and the order of recommendations changes depending on the user
+location.</p>
+
+ <p>To accommodate such a flow, you might choose to:</p>
+ <ul>
+ <li>Rearrange recommendations when a new best estimate is obtained</li>
+ <li>Stop listening for updates if the order of recommendations has stabilized</li>
+ </ul>
+
+ <p>This kind of model is visualized in figure 3.</p>
+
+ <img src="{@docRoot}images/location/where-to-go.png" alt="" />
+<p class="img-caption"><strong>Figure 3.</strong> A timeline representing the window in which a
+dynamic set of data is updated each time the user location updates.</p>
+
+
+
+
+<h2 id="MockData">Providing Mock Location Data</h2>
+
+<p>As you develop your application, you'll certainly need to test how well your model for obtaining
+user location works. This is most easily done using a real Android-powered device. If, however, you
+don't have a device, you can still test your location-based features by mocking location data in
+the Android emulator. There are three different ways to send your application mock location
+data: using Eclipse, DDMS, or the "geo" command in the emulator console.</p>
+
+<p class="note"><strong>Note:</strong> Providing mock location data is injected as GPS location
+data, so you must request location updates from <code>GPS_PROVIDER</code> in order for mock location
+data to work.</p>
+
+<h3 id="MockEclipse">Using Eclipse</h3>
+
+<p>Select <b>Window</b> > <b>Show View</b> > <b>Other</b> > <b>Emulator Control</b>.</p>
+
+<p>In the Emulator Control panel, enter GPS coordinates under Location Controls as individual
+lat/long coordinates, with a GPX file for route playback, or a KML file for multiple place marks.
+(Be sure that you have a device selected in the Devices panel—available from <b>Window</b>
+> <b>Show View</b> > <b>Other</b> > <b>Devices</b>.)</p>
+
+
+<h3 id="MockDdms">Using DDMS</h3>
+
+<p>With the DDMS tool, you can simulate location data a few different ways:</p>
+<ul>
+ <li>Manually send individual longitude/latitude coordinates to the device.</li>
+ <li>Use a GPX file describing a route for playback to the device.</li>
+ <li>Use a KML file describing individual place marks for sequenced playback to the device.</li>
+</ul>
+
+<p>For more information on using DDMS to spoof location data, see the
+<a href="{@docRoot}guide/developing/tools/ddms.html#emulator-control">Using DDMS guide</a>.
+
+
+<h3 id="MockGeo">Using the "geo" command in the emulator console</h3>
+
+<p>To send mock location data from the command line:</p>
+
+<ol>
+ <li>Launch your application in the Android emulator and open a terminal/console in your SDK's
+<code>/tools</code> directory.</li>
+ <li>Connect to the emulator console:
+<pre>telnet localhost <em><console-port></em></pre></li>
+ <li>Send the location data:</p>
+ <ul><li><code>geo fix</code> to send a fixed geo-location.
+ <p>This command accepts a longitude and latitude in decimal degrees, and
+ an optional altitude in meters. For example:</p>
+ <pre>geo fix -121.45356 46.51119 4392</pre>
+ </li>
+ <li><code>geo nmea</code> to send an NMEA 0183 sentence.
+ <p>This command accepts a single NMEA sentence of type '$GPGGA' (fix data) or '$GPRMC' (transit
+ data).
+ For example:</p>
+ <pre>geo nmea $GPRMC,081836,A,3751.65,S,14507.36,E,000.0,360.0,130998,011.3,E*62</pre>
+ </li>
+ </ul>
+ </li>
+</ol>
+
+<p>For information about how to connect to the emulator console, see
+<a href="{@docRoot}guide/developing/tools/emulator.html#console">Using the Emulator Console</a>.</p>
diff --git a/docs/html/guide/topics/manifest/activity-element.jd b/docs/html/guide/topics/manifest/activity-element.jd
index de8ca6d..e030a4c 100644
--- a/docs/html/guide/topics/manifest/activity-element.jd
+++ b/docs/html/guide/topics/manifest/activity-element.jd
@@ -336,10 +336,10 @@
</p></dd>
<dt><a name="lmode"></a>{@code android:launchMode}</dt>
-<dd>An instruction on how the activity should be launched. There are four modes
+<dd>An instruction on how the activity should be launched. There are four modes
that work in conjunction with activity flags ({@code FLAG_ACTIVITY_*} constants)
-in {@link android.content.Intent} objects to determine what should happen when
-the activity is called upon to handle an intent. They are:
+in {@link android.content.Intent} objects to determine what should happen when
+the activity is called upon to handle an intent. They are:</p>
<p style="margin-left: 2em">"{@code standard}"
<br>"{@code singleTop}"
@@ -351,56 +351,110 @@
</p>
<p>
-The modes fall into two main groups, with "{@code standard}" and
-"{@code singleTop}" activities on one side, and "{@code singleTask}" and
-"{@code singleInstance}" activities on the other. An activity with the
-"{@code standard}" or "{@code singleTop}" launch mode can be instantiated
-multiple times. The instances can belong to any task and can be located
-anywhere in the activity stack. Typically, they're launched into the task
-that called
+As shown in the table below, the modes fall into two main groups, with
+"{@code standard}" and "{@code singleTop}" activities on one side, and
+"{@code singleTask}" and "{@code singleInstance}" activities on the other.
+An activity with the "{@code standard}" or "{@code singleTop}" launch mode
+can be instantiated multiple times. The instances can belong to any task
+and can be located anywhere in the activity stack. Typically, they're
+launched into the task that called
<code>{@link android.content.Context#startActivity startActivity()}</code>
-(unless the Intent object contains a
-<code>{@link android.content.Intent#FLAG_ACTIVITY_NEW_TASK}</code>
-instruction, in which case a different task is chosen — see the
+(unless the Intent object contains a
+<code>{@link android.content.Intent#FLAG_ACTIVITY_NEW_TASK}</code>
+instruction, in which case a different task is chosen — see the
<a href="#aff">taskAffinity</a> attribute).
</p>
<p>
-In contrast, "{@code singleTask}" and "{@code singleInstance}" activities
-can only begin a task. They are always at the root of the activity stack.
-Moreover, the device can hold only one instance of the activity at a time
+In contrast, "<code>singleTask</code>" and "<code>singleInstance</code>" activities
+can only begin a task. They are always at the root of the activity stack.
+Moreover, the device can hold only one instance of the activity at a time
— only one such task.
</p>
<p>
The "{@code standard}" and "{@code singleTop}" modes differ from each other
-in just one respect: Every time there's new intent for a "{@code standard}"
-activity, a new instance of the class is created to respond to that intent.
+in just one respect: Every time there's a new intent for a "{@code standard}"
+activity, a new instance of the class is created to respond to that intent.
Each instance handles a single intent.
-Similarly, a new instance of a "{@code singleTop}" activity may also be
-created to handle a new intent. However, if the target task already has an
-existing instance of the activity at the top of its stack, that instance
-will receive the new intent (in an
+Similarly, a new instance of a "{@code singleTop}" activity may also be
+created to handle a new intent. However, if the target task already has an
+existing instance of the activity at the top of its stack, that instance
+will receive the new intent (in an
<code>{@link android.app.Activity#onNewIntent onNewIntent()}</code> call);
a new instance is not created.
-In other circumstances — for example, if an existing instance of the
-"{@code singleTop}" activity is in the target task, but not at the top of
-the stack, or if it's at the top of a stack, but not in the target task
+In other circumstances — for example, if an existing instance of the
+"{@code singleTop}" activity is in the target task, but not at the top of
+the stack, or if it's at the top of a stack, but not in the target task
— a new instance would be created and pushed on the stack.
-</p>
+</p>
<p>
-The "{@code singleTask}" and "{@code singleInstance}" modes also differ from
-each other in only one respect: A "{@code singleTask}" activity allows other
-activities to be part of its task. It's at the root of the activity stack,
-but other activities (necessarily "{@code standard}" and "{@code singleTop}"
-activities) can be launched into the same task. A "{@code singleInstance}"
-activity, on the other hand, permits no other activities to be part of its
-task. It's the only activity in the task. If it starts another activity,
-that activity is assigned to a different task — as if {@code
+The "{@code singleTask}" and "{@code singleInstance}" modes also differ from
+each other in only one respect: A "{@code singleTask}" activity allows other
+activities to be part of its task. It's always at the root of its task, but
+other activities (necessarily "{@code standard}" and "{@code singleTop}"
+activities) can be launched into that task. A "{@code singleInstance}"
+activity, on the other hand, permits no other activities to be part of its task.
+It's the only activity in the task. If it starts another activity, that
+activity is assigned to a different task — as if {@code
FLAG_ACTIVITY_NEW_TASK} was in the intent.
</p>
+<table>
+<tr>
+<th>Use Cases</th>
+<th>Launch Mode</th>
+<th>Multiple Instances?</th>
+<th>Comments</th>
+</tr>
+<tr>
+<td rowspan="2" style="width:20%;">Normal launches for most activities</td>
+<td>"<code>standard</code>"</td>
+<td>Yes</td>
+<td>Default. The system always creates a new instance of the activity in the
+target task and routes the intent to it.</td>
+</tr>
+<tr>
+<td>"<code>singleTop</code>"</td>
+<td>Conditionally</td>
+<td>If an instance of the activity already exists at the top of the target task,
+the system routes the intent to that instance through a call to its {@link
+android.app.Activity#onNewIntent onNewIntent()} method, rather than creating a
+new instance of the activity.</td>
+</tr>
+<tr>
+<td rowspan="2">Specialized launches<br>
+<em>(not recommended for general use)</em></td>
+<td>"<code>singleTask</code>"</td>
+<td>No</td>
+<td>The system creates the activity at the root of a new task and routes the
+intent to it. However, if an instance of the activity already exists, the system
+routes the intent to existing instance through a call to its {@link
+android.app.Activity#onNewIntent onNewIntent()} method, rather than creating a
+new one.</td>
+</tr>
+<tr>
+<td>"<code>singleInstance</code>"</td>
+<td>No</td>
+<td>Same as "<code>singleTask"</code>, except that the system doesn't launch any
+other activities into the task holding the instance. The activity is always the
+single and only member of its task.</td>
+</tr>
+</table>
+
+<p>As shown in the table above, <code>standard</code> is the default mode and is
+appropriate for most types of activities. <code>SingleTop</code> is also a
+common and useful launch mode for many types of activities. The other modes
+— <code>singleTask</code> and <code>singleInstance</code> — are
+<span style="color:red">not appropriate for most applications</span>,
+since they result in an interaction model that is likely to be unfamiliar to
+users and is very different from most other applications.
+
+<p>Regardless of the launch mode that you choose, make sure to test the usability
+of the activity during launch and when navigating back to it from
+other activities and tasks using the BACK key. </p>
+
<p>For more information on launch modes and their interaction with Intent
flags, see the
<a href="{@docRoot}guide/topics/fundamentals.html#acttask">Activities and
diff --git a/docs/html/images/location/content-tagging.png b/docs/html/images/location/content-tagging.png
new file mode 100644
index 0000000..d58bfee
--- /dev/null
+++ b/docs/html/images/location/content-tagging.png
Binary files differ
diff --git a/docs/html/images/location/getting-location.png b/docs/html/images/location/getting-location.png
new file mode 100644
index 0000000..a5905ec
--- /dev/null
+++ b/docs/html/images/location/getting-location.png
Binary files differ
diff --git a/docs/html/images/location/where-to-go.png b/docs/html/images/location/where-to-go.png
new file mode 100644
index 0000000..59f5983
--- /dev/null
+++ b/docs/html/images/location/where-to-go.png
Binary files differ
diff --git a/include/media/EffectPresetReverbApi.h b/include/media/EffectPresetReverbApi.h
index 53205bb..a3f094c 100644
--- a/include/media/EffectPresetReverbApi.h
+++ b/include/media/EffectPresetReverbApi.h
@@ -43,7 +43,8 @@
REVERB_PRESET_LARGEROOM,
REVERB_PRESET_MEDIUMHALL,
REVERB_PRESET_LARGEHALL,
- REVERB_PRESET_PLATE
+ REVERB_PRESET_PLATE,
+ REVERB_PRESET_LAST = REVERB_PRESET_PLATE
} t_reverb_presets;
#if __cplusplus
diff --git a/include/media/stagefright/DataSource.h b/include/media/stagefright/DataSource.h
index 6f7dc38..9d2cff6 100644
--- a/include/media/stagefright/DataSource.h
+++ b/include/media/stagefright/DataSource.h
@@ -28,6 +28,7 @@
namespace android {
+struct AMessage;
class String8;
class DataSource : public RefBase {
@@ -59,10 +60,14 @@
////////////////////////////////////////////////////////////////////////////
- bool sniff(String8 *mimeType, float *confidence);
+ bool sniff(String8 *mimeType, float *confidence, sp<AMessage> *meta);
+ // The sniffer can optionally fill in "meta" with an AMessage containing
+ // a dictionary of values that helps the corresponding extractor initialize
+ // its state without duplicating effort already exerted by the sniffer.
typedef bool (*SnifferFunc)(
- const sp<DataSource> &source, String8 *mimeType, float *confidence);
+ const sp<DataSource> &source, String8 *mimeType,
+ float *confidence, sp<AMessage> *meta);
static void RegisterSniffer(SnifferFunc func);
static void RegisterDefaultSniffers();
diff --git a/include/media/stagefright/MPEG4Writer.h b/include/media/stagefright/MPEG4Writer.h
index de82b38..2412f6a 100644
--- a/include/media/stagefright/MPEG4Writer.h
+++ b/include/media/stagefright/MPEG4Writer.h
@@ -40,6 +40,7 @@
virtual status_t stop();
virtual status_t pause();
virtual bool reachedEOS();
+ virtual status_t dump(int fd, const Vector<String16>& args);
void beginBox(const char *fourcc);
void writeInt8(int8_t x);
diff --git a/include/media/stagefright/MediaWriter.h b/include/media/stagefright/MediaWriter.h
index 151bf16..5cc8dcf 100644
--- a/include/media/stagefright/MediaWriter.h
+++ b/include/media/stagefright/MediaWriter.h
@@ -44,6 +44,10 @@
mListener = listener;
}
+ virtual status_t dump(int fd, const Vector<String16>& args) {
+ return OK;
+ }
+
protected:
virtual ~MediaWriter() {}
int64_t mMaxFileSizeLimitBytes;
diff --git a/include/private/surfaceflinger/SharedBufferStack.h b/include/private/surfaceflinger/SharedBufferStack.h
index 1eb178e..d016dfa 100644
--- a/include/private/surfaceflinger/SharedBufferStack.h
+++ b/include/private/surfaceflinger/SharedBufferStack.h
@@ -54,11 +54,6 @@
// ----------------------------------------------------------------------------
-// 4 * (11 + 7 + (1 + 2*NUM_RECT_MAX) * NUM_BUFFER_MAX) * NUM_LAYERS_MAX
-// 4 * (11 + 7 + (1 + 2*7)*16) * 31
-// 1032 * 31
-// = ~27 KiB (31992)
-
class SharedBufferStack
{
friend class SharedClient;
@@ -85,7 +80,7 @@
};
struct FlatRegion { // 52 bytes = 4 * (1 + 2*N)
- static const unsigned int NUM_RECT_MAX = 6;
+ static const unsigned int NUM_RECT_MAX = 5;
uint32_t count;
SmallRect rects[NUM_RECT_MAX];
};
@@ -93,13 +88,18 @@
struct BufferData {
FlatRegion dirtyRegion;
SmallRect crop;
+ uint8_t transform;
+ uint8_t reserved[3];
};
SharedBufferStack();
void init(int32_t identity);
status_t setDirtyRegion(int buffer, const Region& reg);
status_t setCrop(int buffer, const Rect& reg);
+ status_t setTransform(int buffer, uint8_t transform);
Region getDirtyRegion(int buffer) const;
+ Rect getCrop(int buffer) const;
+ uint32_t getTransform(int buffer) const;
// these attributes are part of the conditions/updates
volatile int32_t head; // server's current front buffer
@@ -117,7 +117,7 @@
int32_t reserved32[1];
Statistics stats;
int32_t reserved;
- BufferData buffers[NUM_BUFFER_MAX]; // 960 bytes
+ BufferData buffers[NUM_BUFFER_MAX]; // 1024 bytes
};
// ----------------------------------------------------------------------------
@@ -206,7 +206,7 @@
bool needNewBuffer(int buffer) const;
status_t setDirtyRegion(int buffer, const Region& reg);
status_t setCrop(int buffer, const Rect& reg);
-
+ status_t setTransform(int buffer, uint32_t transform);
class SetBufferCountCallback {
friend class SharedBufferClient;
@@ -275,6 +275,8 @@
status_t reallocateAllExcept(int buffer);
int32_t getQueuedCount() const;
Region getDirtyRegion(int buffer) const;
+ Rect getCrop(int buffer) const;
+ uint32_t getTransform(int buffer) const;
status_t resize(int newNumBuffers);
diff --git a/include/surfaceflinger/Surface.h b/include/surfaceflinger/Surface.h
index 294c867..7c5a39b 100644
--- a/include/surfaceflinger/Surface.h
+++ b/include/surfaceflinger/Surface.h
@@ -216,6 +216,7 @@
int dispatch_crop(va_list args);
int dispatch_set_buffer_count(va_list args);
int dispatch_set_buffers_geometry(va_list args);
+ int dispatch_set_buffers_transform(va_list args);
void setUsage(uint32_t reqUsage);
int connect(int api);
@@ -223,6 +224,7 @@
int crop(Rect const* rect);
int setBufferCount(int bufferCount);
int setBuffersGeometry(int w, int h, int format);
+ int setBuffersTransform(int transform);
/*
* private stuff...
@@ -278,6 +280,7 @@
Rect mSwapRectangle;
int mConnected;
Rect mNextBufferCrop;
+ uint32_t mNextBufferTransform;
BufferInfo mBufferInfo;
// protected by mSurfaceLock. These are also used from lock/unlock
diff --git a/include/ui/egl/android_natives.h b/include/ui/egl/android_natives.h
index ca89b06..d59d72b 100644
--- a/include/ui/egl/android_natives.h
+++ b/include/ui/egl/android_natives.h
@@ -85,6 +85,7 @@
NATIVE_WINDOW_SET_CROP,
NATIVE_WINDOW_SET_BUFFER_COUNT,
NATIVE_WINDOW_SET_BUFFERS_GEOMETRY,
+ NATIVE_WINDOW_SET_BUFFERS_TRANSFORM,
};
/* parameter for NATIVE_WINDOW_[DIS]CONNECT */
@@ -92,6 +93,20 @@
NATIVE_WINDOW_API_EGL = 1
};
+/* parameter for NATIVE_WINDOW_SET_BUFFERS_TRANSFORM */
+enum {
+ /* flip source image horizontally */
+ NATIVE_WINDOW_TRANSFORM_FLIP_H = HAL_TRANSFORM_FLIP_H ,
+ /* flip source image vertically */
+ NATIVE_WINDOW_TRANSFORM_FLIP_V = HAL_TRANSFORM_FLIP_V,
+ /* rotate source image 90 degrees clock-wise */
+ NATIVE_WINDOW_TRANSFORM_ROT_90 = HAL_TRANSFORM_ROT_90,
+ /* rotate source image 180 degrees */
+ NATIVE_WINDOW_TRANSFORM_ROT_180 = HAL_TRANSFORM_ROT_180,
+ /* rotate source image 270 degrees clock-wise */
+ NATIVE_WINDOW_TRANSFORM_ROT_270 = HAL_TRANSFORM_ROT_270,
+};
+
struct ANativeWindow
{
#ifdef __cplusplus
@@ -196,6 +211,7 @@
* NATIVE_WINDOW_SET_CROP
* NATIVE_WINDOW_SET_BUFFER_COUNT
* NATIVE_WINDOW_SET_BUFFERS_GEOMETRY
+ * NATIVE_WINDOW_SET_BUFFERS_TRANSFORM
*
*/
@@ -298,6 +314,19 @@
w, h, format);
}
+/*
+ * native_window_set_buffers_transform(..., int transform)
+ * All buffers queued after this call will be displayed transformed according
+ * to the transform parameter specified.
+ */
+static inline int native_window_set_buffers_transform(
+ ANativeWindow* window,
+ int transform)
+{
+ return window->perform(window, NATIVE_WINDOW_SET_BUFFERS_TRANSFORM,
+ transform);
+}
+
// ---------------------------------------------------------------------------
/* FIXME: this is legacy for pixmaps */
diff --git a/libs/surfaceflinger_client/SharedBufferStack.cpp b/libs/surfaceflinger_client/SharedBufferStack.cpp
index 156a7db..4ad9f86 100644
--- a/libs/surfaceflinger_client/SharedBufferStack.cpp
+++ b/libs/surfaceflinger_client/SharedBufferStack.cpp
@@ -75,6 +75,14 @@
return NO_ERROR;
}
+status_t SharedBufferStack::setTransform(int buffer, uint8_t transform)
+{
+ if (uint32_t(buffer) >= NUM_BUFFER_MAX)
+ return BAD_INDEX;
+ buffers[buffer].transform = transform;
+ return NO_ERROR;
+}
+
status_t SharedBufferStack::setDirtyRegion(int buffer, const Region& dirty)
{
if (uint32_t(buffer) >= NUM_BUFFER_MAX)
@@ -137,6 +145,26 @@
return res;
}
+Rect SharedBufferStack::getCrop(int buffer) const
+{
+ Rect res(-1, -1);
+ if (uint32_t(buffer) >= NUM_BUFFER_MAX)
+ return res;
+ res.left = buffers[buffer].crop.l;
+ res.top = buffers[buffer].crop.t;
+ res.right = buffers[buffer].crop.r;
+ res.bottom = buffers[buffer].crop.b;
+ return res;
+}
+
+uint32_t SharedBufferStack::getTransform(int buffer) const
+{
+ if (uint32_t(buffer) >= NUM_BUFFER_MAX)
+ return 0;
+ return buffers[buffer].transform;
+}
+
+
// ----------------------------------------------------------------------------
SharedBufferBase::SharedBufferBase(SharedClient* sharedClient,
@@ -433,6 +461,12 @@
return stack.setCrop(buf, crop);
}
+status_t SharedBufferClient::setTransform(int buf, uint32_t transform)
+{
+ SharedBufferStack& stack( *mSharedStack );
+ return stack.setTransform(buf, uint8_t(transform));
+}
+
status_t SharedBufferClient::setDirtyRegion(int buf, const Region& reg)
{
SharedBufferStack& stack( *mSharedStack );
@@ -549,6 +583,18 @@
return stack.getDirtyRegion(buf);
}
+Rect SharedBufferServer::getCrop(int buf) const
+{
+ SharedBufferStack& stack( *mSharedStack );
+ return stack.getCrop(buf);
+}
+
+uint32_t SharedBufferServer::getTransform(int buf) const
+{
+ SharedBufferStack& stack( *mSharedStack );
+ return stack.getTransform(buf);
+}
+
/*
* NOTE: this is not thread-safe on the server-side, meaning
* 'head' cannot move during this operation. The client-side
diff --git a/libs/surfaceflinger_client/Surface.cpp b/libs/surfaceflinger_client/Surface.cpp
index 5ab72cd..cb76091 100644
--- a/libs/surfaceflinger_client/Surface.cpp
+++ b/libs/surfaceflinger_client/Surface.cpp
@@ -422,8 +422,10 @@
const_cast<int&>(ANativeWindow::maxSwapInterval) = 1;
const_cast<uint32_t&>(ANativeWindow::flags) = 0;
+ mNextBufferTransform = 0;
mConnected = 0;
mSwapRectangle.makeInvalid();
+ mNextBufferCrop = Rect(0,0);
// two buffers by default
mBuffers.setCapacity(2);
mBuffers.insertAt(0, 2);
@@ -631,6 +633,7 @@
}
int32_t bufIdx = getBufferIndex(GraphicBuffer::getSelf(buffer));
+ mSharedBufferClient->setTransform(bufIdx, mNextBufferTransform);
mSharedBufferClient->setCrop(bufIdx, mNextBufferCrop);
mSharedBufferClient->setDirtyRegion(bufIdx, mDirtyRegion);
err = mSharedBufferClient->queue(bufIdx);
@@ -685,6 +688,9 @@
case NATIVE_WINDOW_SET_BUFFERS_GEOMETRY:
res = dispatch_set_buffers_geometry( args );
break;
+ case NATIVE_WINDOW_SET_BUFFERS_TRANSFORM:
+ res = dispatch_set_buffers_transform( args );
+ break;
default:
res = NAME_NOT_FOUND;
break;
@@ -719,6 +725,11 @@
return setBuffersGeometry(w, h, f);
}
+int Surface::dispatch_set_buffers_transform(va_list args) {
+ int transform = va_arg(args, int);
+ return setBuffersTransform(transform);
+}
+
void Surface::setUsage(uint32_t reqUsage)
{
Mutex::Autolock _l(mSurfaceLock);
@@ -765,6 +776,10 @@
int Surface::crop(Rect const* rect)
{
+ // empty/invalid rects are not allowed
+ if (rect->isEmpty())
+ return BAD_VALUE;
+
Mutex::Autolock _l(mSurfaceLock);
// TODO: validate rect size
mNextBufferCrop = *rect;
@@ -804,6 +819,13 @@
return NO_ERROR;
}
+int Surface::setBuffersTransform(int transform)
+{
+ Mutex::Autolock _l(mSurfaceLock);
+ mNextBufferTransform = transform;
+ return NO_ERROR;
+}
+
// ----------------------------------------------------------------------------
int Surface::getConnectedApi() const
diff --git a/media/libeffects/lvm/lib/Android.mk b/media/libeffects/lvm/lib/Android.mk
index a944212..ff34707 100644
--- a/media/libeffects/lvm/lib/Android.mk
+++ b/media/libeffects/lvm/lib/Android.mk
@@ -122,3 +122,58 @@
$(LOCAL_PATH)/StereoWidening/lib
include $(BUILD_STATIC_LIBRARY)
+
+# Reverb library
+include $(CLEAR_VARS)
+
+LOCAL_ARM_MODE := arm
+
+LOCAL_SRC_FILES:= \
+ Reverb/src/LVREV_ApplyNewSettings.c \
+ Reverb/src/LVREV_ClearAudioBuffers.c \
+ Reverb/src/LVREV_GetControlParameters.c \
+ Reverb/src/LVREV_GetInstanceHandle.c \
+ Reverb/src/LVREV_GetMemoryTable.c \
+ Reverb/src/LVREV_Process.c \
+ Reverb/src/LVREV_SetControlParameters.c \
+ Reverb/src/LVREV_Tables.c \
+ Common/src/Abs_32.c \
+ Common/src/InstAlloc.c \
+ Common/src/LoadConst_16.c \
+ Common/src/LoadConst_32.c \
+ Common/src/From2iToMono_32.c \
+ Common/src/Mult3s_32x16.c \
+ Common/src/FO_1I_D32F32C31_TRC_WRA_01.c \
+ Common/src/FO_1I_D32F32Cll_TRC_WRA_01_Init.c \
+ Common/src/DelayAllPass_Sat_32x16To32.c \
+ Common/src/Copy_16.c \
+ Common/src/Mac3s_Sat_32x16.c \
+ Common/src/DelayWrite_32.c \
+ Common/src/Shift_Sat_v32xv32.c \
+ Common/src/Add2_Sat_32x32.c \
+ Common/src/JoinTo2i_32x32.c \
+ Common/src/MonoTo2I_32.c \
+ Common/src/LVM_FO_HPF.c \
+ Common/src/LVM_FO_LPF.c \
+ Common/src/LVM_Polynomial.c \
+ Common/src/LVM_Power10.c \
+ Common/src/LVM_GetOmega.c \
+ Common/src/MixSoft_2St_D32C31_SAT.c \
+ Common/src/MixSoft_1St_D32C31_WRA.c \
+ Common/src/MixInSoft_D32C31_SAT.c \
+ Common/src/LVM_Mixer_TimeConstant.c \
+ Common/src/Core_MixHard_2St_D32C31_SAT.c \
+ Common/src/Core_MixSoft_1St_D32C31_WRA.c \
+ Common/src/Core_MixInSoft_D32C31_SAT.c
+
+LOCAL_MODULE:= libreverb
+
+LOCAL_PRELINK_MODULE := false
+
+LOCAL_C_INCLUDES += \
+ $(LOCAL_PATH)/Reverb/lib \
+ $(LOCAL_PATH)/Reverb/src \
+ $(LOCAL_PATH)/Common/lib \
+ $(LOCAL_PATH)/Common/src
+
+include $(BUILD_STATIC_LIBRARY)
diff --git a/media/libeffects/lvm/lib/Bass/src/LVDBE_Control.c b/media/libeffects/lvm/lib/Bass/src/LVDBE_Control.c
index 8cf84b7..4a9dc72 100755
--- a/media/libeffects/lvm/lib/Bass/src/LVDBE_Control.c
+++ b/media/libeffects/lvm/lib/Bass/src/LVDBE_Control.c
@@ -17,9 +17,9 @@
/****************************************************************************************
- $Author: nxp007753 $
- $Revision: 1315 $
- $Date: 2010-07-23 11:52:08 +0200 (Fri, 23 Jul 2010) $
+ $Author: beq06068 $
+ $Revision: 1401 $
+ $Date: 2010-08-03 09:52:22 +0200 (Tue, 03 Aug 2010) $
*****************************************************************************************/
@@ -128,7 +128,7 @@
(void *)&pInstance->pData->HPFTaps, /* Destination Cast to void: \
no dereferencing in function*/
sizeof(pInstance->pData->HPFTaps)/sizeof(LVM_INT16)); /* Number of words */
- BQ_2I_D32F32Cll_TRC_WRA_01_Init(&pInstance->pCoef->HPFInstance, /* Initialise the filter */
+ BQ_2I_D32F32Cll_TRC_WRA_01_Init(&pInstance->pCoef->HPFInstance, /* Initialise the filter */
&pInstance->pData->HPFTaps,
(BQ_C32_Coefs_t *)&LVDBE_HPF_Table[Offset]);
@@ -140,7 +140,7 @@
(void *)&pInstance->pData->BPFTaps, /* Destination Cast to void:\
no dereferencing in function*/
sizeof(pInstance->pData->BPFTaps)/sizeof(LVM_INT16)); /* Number of words */
- BP_1I_D32F32Cll_TRC_WRA_02_Init(&pInstance->pCoef->BPFInstance, /* Initialise the filter */
+ BP_1I_D32F32Cll_TRC_WRA_02_Init(&pInstance->pCoef->BPFInstance, /* Initialise the filter */
&pInstance->pData->BPFTaps,
(BP_C32_Coefs_t *)&LVDBE_BPF_Table[Offset]);
@@ -317,6 +317,7 @@
{
LVDBE_Instance_t *pInstance =(LVDBE_Instance_t *)hInstance;
+ LVMixer3_2St_st *pBypassMixer_Instance = &pInstance->pData->BypassMixer;
/*
@@ -339,6 +340,14 @@
{
LVDBE_SetAGC(pInstance, /* Instance pointer */
pParams); /* New parameters */
+
+ LVC_Mixer_SetTimeConstant(&pBypassMixer_Instance->MixerStream[0],
+ LVDBE_BYPASS_MIXER_TC,pParams->SampleRate,2);
+
+ LVC_Mixer_SetTimeConstant(&pBypassMixer_Instance->MixerStream[1],
+ LVDBE_BYPASS_MIXER_TC,pParams->SampleRate,2);
+
+
}
@@ -356,17 +365,13 @@
if (pInstance->Params.OperatingMode==LVDBE_ON && pParams->OperatingMode==LVDBE_OFF)
{
- LVDBE_Params_t Params = *pParams; /* make local copy of params */
- Params.EffectLevel = 0; /* zero effect level before switching off module*/
- pInstance->bTransitionOnToOff = LVM_TRUE; /* Set the CallBack */
- LVDBE_SetAGC(pInstance, /* Instance pointer */
- &Params); /* New parameters */
+ LVC_Mixer_SetTarget(&pInstance->pData->BypassMixer.MixerStream[0],0);
+ LVC_Mixer_SetTarget(&pInstance->pData->BypassMixer.MixerStream[1],0x00007FFF);
}
if (pInstance->Params.OperatingMode==LVDBE_OFF && pParams->OperatingMode==LVDBE_ON)
{
- pInstance->bTransitionOnToOff = LVM_FALSE; /* Set the CallBack */
- LVDBE_SetAGC(pInstance, /* Instance pointer */
- pParams); /* New parameters */
+ LVC_Mixer_SetTarget(&pInstance->pData->BypassMixer.MixerStream[0],0x00007FFF);
+ LVC_Mixer_SetTarget(&pInstance->pData->BypassMixer.MixerStream[1],0);
}
/*
diff --git a/media/libeffects/lvm/lib/Bass/src/LVDBE_Init.c b/media/libeffects/lvm/lib/Bass/src/LVDBE_Init.c
index 75869c7..95c421d 100755
--- a/media/libeffects/lvm/lib/Bass/src/LVDBE_Init.c
+++ b/media/libeffects/lvm/lib/Bass/src/LVDBE_Init.c
@@ -17,9 +17,9 @@
/****************************************************************************************
- $Author: nxp007753 $
- $Revision: 1081 $
- $Date: 2010-07-05 11:48:44 +0200 (Mon, 05 Jul 2010) $
+ $Author: beq06068 $
+ $Revision: 1399 $
+ $Date: 2010-08-03 08:16:00 +0200 (Tue, 03 Aug 2010) $
*****************************************************************************************/
@@ -160,6 +160,7 @@
LVDBE_Instance_t *pInstance;
LVMixer3_1St_st *pMixer_Instance;
+ LVMixer3_2St_st *pBypassMixer_Instance;
LVM_INT16 i;
LVM_INT32 MixGain;
@@ -227,7 +228,7 @@
/*
* Initialise the filters
*/
- LVDBE_SetFilters(pInstance, /* Set the filter taps and coefficients */
+ LVDBE_SetFilters(pInstance, /* Set the filter taps and coefficients */
&pInstance->Params);
@@ -236,7 +237,8 @@
*/
LVDBE_SetAGC(pInstance, /* Set the AGC gain */
&pInstance->Params);
- pInstance->pData->AGCInstance.AGC_Gain = pInstance->pData->AGCInstance.AGC_MaxGain; /* Default to the bass boost setting */
+ pInstance->pData->AGCInstance.AGC_Gain = pInstance->pData->AGCInstance.AGC_MaxGain;
+ /* Default to the bass boost setting */
/*
@@ -245,7 +247,8 @@
LVDBE_SetVolume(pInstance, /* Set the Volume */
&pInstance->Params);
- pInstance->pData->AGCInstance.Volume = pInstance->pData->AGCInstance.Target; /* Initialise as the target */
+ pInstance->pData->AGCInstance.Volume = pInstance->pData->AGCInstance.Target;
+ /* Initialise as the target */
pMixer_Instance = &pInstance->pData->BypassVolume;
MixGain = LVC_Mixer_GetTarget(&pMixer_Instance->MixerStream[0]);
@@ -258,9 +261,31 @@
pMixer_Instance->MixerStream[0].CallbackSet = 0;
/*
- * Initialise the clicks minimisation variable
+ * Initialise the clicks minimisation BypassMixer
*/
- pInstance->bTransitionOnToOff = LVM_FALSE;
+
+ pBypassMixer_Instance = &pInstance->pData->BypassMixer;
+
+ /*
+ * Setup the mixer gain for the processed path
+ */
+ pBypassMixer_Instance->MixerStream[0].CallbackParam = 0;
+ pBypassMixer_Instance->MixerStream[0].pCallbackHandle = LVM_NULL;
+ pBypassMixer_Instance->MixerStream[0].pCallBack = LVM_NULL;
+ pBypassMixer_Instance->MixerStream[0].CallbackSet=0;
+ LVC_Mixer_Init(&pBypassMixer_Instance->MixerStream[0],0,0);
+ LVC_Mixer_SetTimeConstant(&pBypassMixer_Instance->MixerStream[0],
+ LVDBE_BYPASS_MIXER_TC,pInstance->Params.SampleRate,2);
+ /*
+ * Setup the mixer gain for the unprocessed path
+ */
+ pBypassMixer_Instance->MixerStream[1].CallbackParam = 0;
+ pBypassMixer_Instance->MixerStream[1].pCallbackHandle = LVM_NULL;
+ pBypassMixer_Instance->MixerStream[1].pCallBack = LVM_NULL;
+ pBypassMixer_Instance->MixerStream[1].CallbackSet=0;
+ LVC_Mixer_Init(&pBypassMixer_Instance->MixerStream[1],0x00007FFF,0x00007FFF);
+ LVC_Mixer_SetTimeConstant(&pBypassMixer_Instance->MixerStream[1],
+ LVDBE_BYPASS_MIXER_TC,pInstance->Params.SampleRate,2);
return(LVDBE_SUCCESS);
}
diff --git a/media/libeffects/lvm/lib/Bass/src/LVDBE_Private.h b/media/libeffects/lvm/lib/Bass/src/LVDBE_Private.h
index 3e09cf4..df32873 100755
--- a/media/libeffects/lvm/lib/Bass/src/LVDBE_Private.h
+++ b/media/libeffects/lvm/lib/Bass/src/LVDBE_Private.h
@@ -17,9 +17,9 @@
/****************************************************************************************
- $Author: nxp007753 $
- $Revision: 1081 $
- $Date: 2010-07-05 11:48:44 +0200 (Mon, 05 Jul 2010) $
+ $Author: beq06068 $
+ $Revision: 1399 $
+ $Date: 2010-08-03 08:16:00 +0200 (Tue, 03 Aug 2010) $
*****************************************************************************************/
@@ -75,6 +75,8 @@
#define LVDBE_SCRATCHBUFFERS_INPLACE 4 /* Number of buffers required for inplace processing */
#define LVDBE_MIXER_TC 5 /* Mixer time */
+#define LVDBE_BYPASS_MIXER_TC 100 /* Bypass mixer time */
+
/****************************************************************************************/
/* */
@@ -92,6 +94,7 @@
Biquad_2I_Order2_Taps_t HPFTaps; /* High pass filter taps */
Biquad_1I_Order2_Taps_t BPFTaps; /* Band pass filter taps */
LVMixer3_1St_st BypassVolume; /* Bypass volume scaler */
+ LVMixer3_2St_st BypassMixer; /* Bypass Mixer for Click Removal */
} LVDBE_Data_t;
@@ -115,9 +118,6 @@
/* Data and coefficient pointers */
LVDBE_Data_t *pData; /* Instance data */
LVDBE_Coef_t *pCoef; /* Instance coefficients */
-
- LVM_INT32 bTransitionOnToOff;
-
} LVDBE_Instance_t;
diff --git a/media/libeffects/lvm/lib/Bass/src/LVDBE_Process.c b/media/libeffects/lvm/lib/Bass/src/LVDBE_Process.c
index 35eec07..04032c0 100755
--- a/media/libeffects/lvm/lib/Bass/src/LVDBE_Process.c
+++ b/media/libeffects/lvm/lib/Bass/src/LVDBE_Process.c
@@ -17,9 +17,9 @@
/****************************************************************************************
- $Author: nxp007753 $
- $Revision: 1081 $
- $Date: 2010-07-05 11:48:44 +0200 (Mon, 05 Jul 2010) $
+ $Author: beq06068 $
+ $Revision: 1400 $
+ $Date: 2010-08-03 09:22:37 +0200 (Tue, 03 Aug 2010) $
*****************************************************************************************/
@@ -89,10 +89,16 @@
LVDBE_Instance_t *pInstance =(LVDBE_Instance_t *)hInstance;
LVM_INT32 *pScratch = (LVM_INT32 *)pInstance->MemoryTable.Region[LVDBE_MEMREGION_SCRATCH].pBaseAddress;
- LVM_INT32 *pMono = (LVM_INT32 *)pOutData;
+ LVM_INT32 *pMono;
LVM_INT16 *pInput = (LVM_INT16 *)pInData;
+ /* Scratch for Volume Control starts at offset of 2*NumSamples short values from pScratch */
+ LVM_INT16 *pScratchVol = (LVM_INT16 *)(&pScratch[NumSamples]);
+
+ /* Scratch for Mono path starts at offset of 2*NumSamples 32-bit values from pScratch */
+ pMono = &pScratch[2*NumSamples];
+
/*
* Check the number of samples is not too large
*/
@@ -104,18 +110,20 @@
/*
* Check if the algorithm is enabled
*/
- if ((pInstance->Params.OperatingMode != LVDBE_OFF) ||
- (pInstance->bTransitionOnToOff == LVM_TRUE))
+ /* DBE path is processed when DBE is ON or during On/Off transitions */
+ if ((pInstance->Params.OperatingMode == LVDBE_ON)||
+ (LVC_Mixer_GetCurrent(&pInstance->pData->BypassMixer.MixerStream[0])
+ !=LVC_Mixer_GetTarget(&pInstance->pData->BypassMixer.MixerStream[0])))
{
/*
* Convert 16-bit samples to 32-bit and scale
* (For a 16-bit implementation apply headroom loss here)
*/
- Int16LShiftToInt32_16x32(pInput, /* Source 16-bit data */
- pScratch, /* Destination 32-bit data */
- (LVM_INT16)(2*NumSamples), /* Left and right */
- LVDBE_SCALESHIFT); /* Shift scale */
+ Int16LShiftToInt32_16x32(pInput, /* Source 16-bit data */
+ pScratch, /* Dest. 32-bit data */
+ (LVM_INT16)(2*NumSamples), /* Left and right */
+ LVDBE_SCALESHIFT); /* Shift scale */
/*
@@ -123,61 +131,54 @@
*/
if (pInstance->Params.HPFSelect == LVDBE_HPF_ON)
{
- BQ_2I_D32F32C30_TRC_WRA_01(&pInstance->pCoef->HPFInstance, /* Filter instance */
- (LVM_INT32 *)pScratch, /* Source */
- (LVM_INT32 *)pScratch, /* Destination */
- (LVM_INT16)NumSamples); /* Number of samples */
+ BQ_2I_D32F32C30_TRC_WRA_01(&pInstance->pCoef->HPFInstance,/* Filter instance */
+ (LVM_INT32 *)pScratch, /* Source */
+ (LVM_INT32 *)pScratch, /* Destination */
+ (LVM_INT16)NumSamples); /* Number of samples */
}
/*
* Create the mono stream
*/
- From2iToMono_32(pScratch, /* Stereo source */
- pMono, /* Mono destination */
- (LVM_INT16)NumSamples); /* Number of samples */
+ From2iToMono_32(pScratch, /* Stereo source */
+ pMono, /* Mono destination */
+ (LVM_INT16)NumSamples); /* Number of samples */
/*
* Apply the band pass filter
*/
- BP_1I_D32F32C30_TRC_WRA_02(&pInstance->pCoef->BPFInstance, /* Filter instance */
- (LVM_INT32 *)pMono, /* Source */
- (LVM_INT32 *)pMono, /* Destination */
- (LVM_INT16)NumSamples); /* Number of samples */
+ BP_1I_D32F32C30_TRC_WRA_02(&pInstance->pCoef->BPFInstance, /* Filter instance */
+ (LVM_INT32 *)pMono, /* Source */
+ (LVM_INT32 *)pMono, /* Destination */
+ (LVM_INT16)NumSamples); /* Number of samples */
/*
* Apply the AGC and mix
*/
- AGC_MIX_VOL_2St1Mon_D32_WRA(&pInstance->pData->AGCInstance, /* Instance pointer */
- pScratch, /* Stereo source */
- pMono, /* Mono band pass source */
- pScratch, /* Stereo destination */
- NumSamples); /* Number of samples */
-
- if(pInstance->bTransitionOnToOff == LVM_TRUE)
- {
- if ((pInstance->pData->AGCInstance.AGC_Gain == pInstance->pData->AGCInstance.AGC_Target)&&
- (pInstance->pData->AGCInstance.AGC_Gain == 0))
- {
- pInstance->bTransitionOnToOff = LVM_FALSE;
- }
- }
-
-
+ AGC_MIX_VOL_2St1Mon_D32_WRA(&pInstance->pData->AGCInstance, /* Instance pointer */
+ pScratch, /* Stereo source */
+ pMono, /* Mono band pass source */
+ pScratch, /* Stereo destination */
+ NumSamples); /* Number of samples */
/*
* Convert 32-bit samples to 16-bit and saturate
* (Not required for 16-bit implemenations)
*/
- Int32RShiftToInt16_Sat_32x16(pScratch, /* Source 32-bit data */
- pOutData, /* Destination 16-bit data */
- (LVM_INT16)(2*NumSamples), /* Left and right */
- LVDBE_SCALESHIFT); /* Shift scale */
+ Int32RShiftToInt16_Sat_32x16(pScratch, /* Source 32-bit data */
+ (LVM_INT16 *)pScratch, /* Dest. 16-bit data */
+ (LVM_INT16)(2*NumSamples), /* Left and right */
+ LVDBE_SCALESHIFT); /* Shift scale */
}
- else
+
+ /* Bypass Volume path is processed when DBE is OFF or during On/Off transitions */
+ if ((pInstance->Params.OperatingMode == LVDBE_OFF)||
+ (LVC_Mixer_GetCurrent(&pInstance->pData->BypassMixer.MixerStream[1])
+ !=LVC_Mixer_GetTarget(&pInstance->pData->BypassMixer.MixerStream[1])))
{
/*
@@ -186,11 +187,20 @@
*/
LVC_MixSoft_1St_D16C31_SAT(&pInstance->pData->BypassVolume,
pInData,
- pOutData,
- (LVM_INT16)(2*NumSamples)); /* Left and right */
+ pScratchVol,
+ (LVM_INT16)(2*NumSamples)); /* Left and right */
}
+ /*
+ * Mix DBE processed path and bypass volume path
+ */
+ LVC_MixSoft_2St_D16C31_SAT(&pInstance->pData->BypassMixer,
+ (LVM_INT16 *) pScratch,
+ pScratchVol,
+ pOutData,
+ (LVM_INT16)(2*NumSamples));
+
return(LVDBE_SUCCESS);
}
diff --git a/media/libeffects/lvm/lib/Bundle/src/LVM_Control.c b/media/libeffects/lvm/lib/Bundle/src/LVM_Control.c
index 922f77d..cec7501 100755
--- a/media/libeffects/lvm/lib/Bundle/src/LVM_Control.c
+++ b/media/libeffects/lvm/lib/Bundle/src/LVM_Control.c
@@ -18,8 +18,8 @@
/****************************************************************************************
$Author: nxp007753 $
- $Revision: 1316 $
- $Date: 2010-07-23 11:53:24 +0200 (Fri, 23 Jul 2010) $
+ $Revision: 1331 $
+ $Date: 2010-07-27 12:26:23 +0200 (Tue, 27 Jul 2010) $
*****************************************************************************************/
diff --git a/media/libeffects/lvm/lib/Reverb/lib/LVREV.h b/media/libeffects/lvm/lib/Reverb/lib/LVREV.h
new file mode 100755
index 0000000..4c32db0
--- /dev/null
+++ b/media/libeffects/lvm/lib/Reverb/lib/LVREV.h
@@ -0,0 +1,321 @@
+/*
+ * Copyright (C) 2004-2010 NXP Software
+ * Copyright (C) 2010 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.
+ */
+
+/************************************************************************/
+/* */
+/* Project:: */
+/* $Author: beq03888 $*/
+/* $Revision: 1204 $*/
+/* $Date: 2010-07-14 08:55:43 +0200 (Wed, 14 Jul 2010) $*/
+/* */
+/************************************************************************/
+
+/****************************************************************************************/
+/* */
+/* Header file for the application layer interface of the LVREV module */
+/* */
+/* This files includes all definitions, types, structures and function prototypes */
+/* required by the calling layer. All other types, structures and functions are */
+/* private. */
+/* */
+/****************************************************************************************/
+
+#ifndef __LVREV_H__
+#define __LVREV_H__
+
+#ifdef __cplusplus
+extern "C" {
+#endif /* __cplusplus */
+
+
+/****************************************************************************************/
+/* */
+/* Includes */
+/* */
+/****************************************************************************************/
+#include "LVM_Types.h"
+
+
+/****************************************************************************************/
+/* */
+/* Definitions */
+/* */
+/****************************************************************************************/
+/* General */
+#define LVREV_BLOCKSIZE_MULTIPLE 1 /* Processing block size multiple */
+#define LVREV_MAX_T60 7000 /* Maximum decay time is 7000ms */
+
+/* Memory table*/
+#define LVREV_NR_MEMORY_REGIONS 4 /* Number of memory regions */
+
+
+/****************************************************************************************/
+/* */
+/* Types */
+/* */
+/****************************************************************************************/
+/* Instance handle */
+typedef void *LVREV_Handle_t;
+
+
+/* Status return values */
+typedef enum
+{
+ LVREV_SUCCESS = 0, /* Successful return from a routine */
+ LVREV_NULLADDRESS = 1, /* NULL allocation address */
+ LVREV_OUTOFRANGE = 2, /* Out of range control parameter */
+ LVREV_INVALIDNUMSAMPLES = 3, /* Invalid number of samples */
+ LVREV_RETURNSTATUS_DUMMY = LVM_MAXENUM
+} LVREV_ReturnStatus_en;
+
+
+/* Reverb delay lines */
+typedef enum
+{
+ LVREV_DELAYLINES_1 = 1, /* One delay line */
+ LVREV_DELAYLINES_2 = 2, /* Two delay lines */
+ LVREV_DELAYLINES_4 = 4, /* Four delay lines */
+ LVREV_DELAYLINES_DUMMY = LVM_MAXENUM
+} LVREV_NumDelayLines_en;
+
+
+/****************************************************************************************/
+/* */
+/* Structures */
+/* */
+/****************************************************************************************/
+
+/* Memory table containing the region definitions */
+typedef struct
+{
+ LVM_MemoryRegion_st Region[LVREV_NR_MEMORY_REGIONS]; /* One definition for each region */
+} LVREV_MemoryTable_st;
+
+
+/* Control Parameter structure */
+typedef struct
+{
+ /* General parameters */
+ LVM_Mode_en OperatingMode; /* Operating mode */
+ LVM_Fs_en SampleRate; /* Sample rate */
+ LVM_Format_en SourceFormat; /* Source data format */
+
+ /* Parameters for REV */
+ LVM_UINT16 Level; /* Level, 0 to 100 representing percentage of reverb */
+ LVM_UINT16 LPF; /* Low pass filter, in Hz */
+ LVM_UINT16 HPF; /* High pass filter, in Hz */
+ LVM_UINT16 T60; /* Decay time constant, in ms */
+ LVM_UINT16 Density; /* Echo density, 0 to 100 for minimum to maximum density */
+ LVM_UINT16 Damping; /* Damping */
+ LVM_UINT16 RoomSize; /* Simulated room size, 1 to 100 for minimum to maximum size */
+
+} LVREV_ControlParams_st;
+
+
+/* Instance Parameter structure */
+typedef struct
+{
+ /* General */
+ LVM_UINT16 MaxBlockSize; /* Maximum processing block size */
+
+ /* Reverb */
+ LVM_Format_en SourceFormat; /* Source data formats to support */
+ LVREV_NumDelayLines_en NumDelays; /* The number of delay lines, 1, 2 or 4 */
+
+} LVREV_InstanceParams_st;
+
+
+/****************************************************************************************/
+/* */
+/* Function Prototypes */
+/* */
+/****************************************************************************************/
+
+/****************************************************************************************/
+/* */
+/* FUNCTION: LVREV_GetMemoryTable */
+/* */
+/* DESCRIPTION: */
+/* This function is used to obtain the LVREV module memory requirements to support */
+/* memory allocation. It can also be used to return the memory base address provided */
+/* during memory allocation to support freeing of memory when the LVREV module is no */
+/* longer required. It is called in two ways: */
+/* */
+/* hInstance = NULL Returns the memory requirements */
+/* hInstance = Instance handle Returns the memory requirements and allocated */
+/* base addresses. */
+/* */
+/* When this function is called with hInstance = NULL the memory base address pointers */
+/* will be NULL on return. */
+/* */
+/* When the function is called for freeing memory, hInstance = Instance Handle the */
+/* memory table returns the allocated memory and base addresses used during */
+/* initialisation. */
+/* */
+/* PARAMETERS: */
+/* hInstance Instance Handle */
+/* pMemoryTable Pointer to an empty memory table */
+/* pInstanceParams Pointer to the instance parameters */
+/* */
+/* RETURNS: */
+/* LVREV_SUCCESS Succeeded */
+/* LVREV_NULLADDRESS When pMemoryTable is NULL */
+/* LVREV_NULLADDRESS When requesting memory requirements and pInstanceParams */
+/* is NULL */
+/* */
+/* NOTES: */
+/* 1. This function may be interrupted by the LVREV_Process function */
+/* */
+/****************************************************************************************/
+LVREV_ReturnStatus_en LVREV_GetMemoryTable(LVREV_Handle_t hInstance,
+ LVREV_MemoryTable_st *pMemoryTable,
+ LVREV_InstanceParams_st *pInstanceParams);
+
+
+/****************************************************************************************/
+/* */
+/* FUNCTION: LVREV_GetInstanceHandle */
+/* */
+/* DESCRIPTION: */
+/* This function is used to create a LVREV module instance. It returns the created */
+/* instance handle through phInstance. All parameters are set to invalid values, the */
+/* LVREV_SetControlParameters function must be called with a set of valid control */
+/* parameters before the LVREV_Process function can be called. */
+/* */
+/* The memory allocation must be provided by the application by filling in the memory */
+/* region base addresses in the memory table before calling this function. */
+/* */
+/* PARAMETERS: */
+/* phInstance Pointer to the instance handle */
+/* pMemoryTable Pointer to the memory definition table */
+/* pInstanceParams Pointer to the instance parameters */
+/* */
+/* RETURNS: */
+/* LVREV_SUCCESS Succeeded */
+/* LVREV_NULLADDRESS When phInstance or pMemoryTable or pInstanceParams is NULL */
+/* LVREV_NULLADDRESS When one of the memory regions has a NULL pointer */
+/* */
+/* NOTES: */
+/* */
+/****************************************************************************************/
+LVREV_ReturnStatus_en LVREV_GetInstanceHandle(LVREV_Handle_t *phInstance,
+ LVREV_MemoryTable_st *pMemoryTable,
+ LVREV_InstanceParams_st *pInstanceParams);
+
+
+/****************************************************************************************/
+/* */
+/* FUNCTION: LVXX_GetControlParameters */
+/* */
+/* DESCRIPTION: */
+/* Request the LVREV module control parameters. The current parameter set is returned */
+/* via the parameter pointer. */
+/* */
+/* PARAMETERS: */
+/* hInstance Instance handle */
+/* pControlParams Pointer to an empty parameter structure */
+/* */
+/* RETURNS: */
+/* LVREV_SUCCESS Succeeded */
+/* LVREV_NULLADDRESS When hInstance or pControlParams is NULL */
+/* */
+/* NOTES: */
+/* 1. This function may be interrupted by the LVREV_Process function */
+/* */
+/****************************************************************************************/
+LVREV_ReturnStatus_en LVREV_GetControlParameters(LVREV_Handle_t hInstance,
+ LVREV_ControlParams_st *pControlParams);
+
+
+/****************************************************************************************/
+/* */
+/* FUNCTION: LVREV_SetControlParameters */
+/* */
+/* DESCRIPTION: */
+/* Sets or changes the LVREV module parameters. */
+/* */
+/* PARAMETERS: */
+/* hInstance Instance handle */
+/* pNewParams Pointer to a parameter structure */
+/* */
+/* RETURNS: */
+/* LVREV_SUCCESS Succeeded */
+/* LVREV_NULLADDRESS When hInstance or pNewParams is NULL */
+/* */
+/* NOTES: */
+/* 1. This function may be interrupted by the LVREV_Process function */
+/* */
+/****************************************************************************************/
+LVREV_ReturnStatus_en LVREV_SetControlParameters(LVREV_Handle_t hInstance,
+ LVREV_ControlParams_st *pNewParams);
+
+
+/****************************************************************************************/
+/* */
+/* FUNCTION: LVREV_ClearAudioBuffers */
+/* */
+/* DESCRIPTION: */
+/* This function is used to clear the internal audio buffers of the module. */
+/* */
+/* PARAMETERS: */
+/* hInstance Instance handle */
+/* */
+/* RETURNS: */
+/* LVREV_SUCCESS Initialisation succeeded */
+/* LVREV_NULLADDRESS Instance is NULL */
+/* */
+/* NOTES: */
+/* 1. This function must not be interrupted by the LVREV_Process function */
+/* */
+/****************************************************************************************/
+LVREV_ReturnStatus_en LVREV_ClearAudioBuffers(LVREV_Handle_t hInstance);
+
+
+/****************************************************************************************/
+/* */
+/* FUNCTION: LVREV_Process */
+/* */
+/* DESCRIPTION: */
+/* Process function for the LVREV module. */
+/* */
+/* PARAMETERS: */
+/* hInstance Instance handle */
+/* pInData Pointer to the input data */
+/* pOutData Pointer to the output data */
+/* NumSamples Number of samples in the input buffer */
+/* */
+/* RETURNS: */
+/* LVREV_SUCCESS Succeeded */
+/* LVREV_INVALIDNUMSAMPLES NumSamples was larger than the maximum block size */
+/* */
+/* NOTES: */
+/* 1. The input and output buffers must be 32-bit aligned */
+/* */
+/****************************************************************************************/
+LVREV_ReturnStatus_en LVREV_Process(LVREV_Handle_t hInstance,
+ const LVM_INT32 *pInData,
+ LVM_INT32 *pOutData,
+ const LVM_UINT16 NumSamples);
+
+
+#ifdef __cplusplus
+}
+#endif /* __cplusplus */
+
+#endif /* __LVREV_H__ */
+
+/* End of file */
diff --git a/media/libeffects/lvm/lib/Reverb/src/LVREV_ApplyNewSettings.c b/media/libeffects/lvm/lib/Reverb/src/LVREV_ApplyNewSettings.c
new file mode 100755
index 0000000..0026652
--- /dev/null
+++ b/media/libeffects/lvm/lib/Reverb/src/LVREV_ApplyNewSettings.c
@@ -0,0 +1,656 @@
+/*
+ * Copyright (C) 2004-2010 NXP Software
+ * Copyright (C) 2010 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.
+ */
+
+/****************************************************************************************/
+/* */
+/* Project:: */
+/* $Author: nxp007753 $ */
+/* $Revision: 1316 $ */
+/* $Date: 2010-07-23 11:53:24 +0200 (Fri, 23 Jul 2010) $ */
+/* */
+/****************************************************************************************/
+
+/****************************************************************************************/
+/* */
+/* Includes */
+/* */
+/****************************************************************************************/
+#include "LVREV_Private.h"
+#include "Filter.h"
+
+/****************************************************************************************/
+/* */
+/* FUNCTION: LVREV_ApplyNewSettings */
+/* */
+/* DESCRIPTION: */
+/* Applies the new control parameters */
+/* */
+/* PARAMETERS: */
+/* pPrivate Pointer to the instance private parameters */
+/* */
+/* RETURNS: */
+/* LVREV_Success Succeeded */
+/* LVREV_NULLADDRESS When pPrivate is NULL */
+/* */
+/* NOTES: */
+/* */
+/****************************************************************************************/
+
+LVREV_ReturnStatus_en LVREV_ApplyNewSettings (LVREV_Instance_st *pPrivate)
+{
+
+ LVM_Mode_en OperatingMode;
+ LVM_INT32 NumberOfDelayLines;
+
+
+ /* Check for NULL pointer */
+ if(pPrivate == LVM_NULL)
+ {
+ return LVREV_NULLADDRESS;
+ }
+
+ OperatingMode = pPrivate->NewParams.OperatingMode;
+
+ if(pPrivate->InstanceParams.NumDelays == LVREV_DELAYLINES_4)
+ {
+ NumberOfDelayLines = 4;
+ }
+ else if(pPrivate->InstanceParams.NumDelays == LVREV_DELAYLINES_2)
+ {
+ NumberOfDelayLines = 2;
+ }
+ else
+ {
+ NumberOfDelayLines = 1;
+ }
+
+ /*
+ * Update the high pass filter coefficients
+ */
+ if((pPrivate->NewParams.HPF != pPrivate->CurrentParams.HPF) ||
+ (pPrivate->NewParams.SampleRate != pPrivate->CurrentParams.SampleRate) ||
+ (pPrivate->bFirstControl == LVM_TRUE))
+ {
+ LVM_INT32 Omega;
+ FO_C32_Coefs_t Coeffs;
+
+ Omega = LVM_GetOmega(pPrivate->NewParams.HPF, pPrivate->NewParams.SampleRate);
+ LVM_FO_HPF(Omega, &Coeffs);
+ FO_1I_D32F32Cll_TRC_WRA_01_Init( &pPrivate->pFastCoef->HPCoefs, &pPrivate->pFastData->HPTaps, &Coeffs);
+ LoadConst_32(0,
+ (void *)&pPrivate->pFastData->HPTaps, /* Destination Cast to void: no dereferencing in function*/
+ sizeof(Biquad_1I_Order1_Taps_t)/sizeof(LVM_INT32));
+ }
+
+
+ /*
+ * Update the low pass filter coefficients
+ */
+ if((pPrivate->NewParams.LPF != pPrivate->CurrentParams.LPF) ||
+ (pPrivate->NewParams.SampleRate != pPrivate->CurrentParams.SampleRate) ||
+ (pPrivate->bFirstControl == LVM_TRUE))
+ {
+ LVM_INT32 Omega;
+ FO_C32_Coefs_t Coeffs;
+
+
+ Coeffs.A0 = 0x7FFFFFFF;
+ Coeffs.A1 = 0;
+ Coeffs.B1 = 0;
+ if(pPrivate->NewParams.LPF <= (LVM_FsTable[pPrivate->NewParams.SampleRate] >> 1))
+ {
+ Omega = LVM_GetOmega(pPrivate->NewParams.LPF, pPrivate->NewParams.SampleRate);
+
+ /*
+ * Do not apply filter if w =2*pi*fc/fs >= 2.9
+ */
+ if(Omega<=LVREV_2_9_INQ29)
+ {
+ LVM_FO_LPF(Omega, &Coeffs);
+ }
+ }
+ FO_1I_D32F32Cll_TRC_WRA_01_Init( &pPrivate->pFastCoef->LPCoefs, &pPrivate->pFastData->LPTaps, &Coeffs);
+ LoadConst_32(0,
+ (void *)&pPrivate->pFastData->LPTaps, /* Destination Cast to void: no dereferencing in function*/
+ sizeof(Biquad_1I_Order1_Taps_t)/sizeof(LVM_INT32));
+ }
+
+
+ /*
+ * Calculate the room size parameter
+ */
+ if( pPrivate->NewParams.RoomSize != pPrivate->CurrentParams.RoomSize)
+ {
+ /* Room size range is 10ms to 200ms
+ * 0% -- 10ms
+ * 50% -- 65ms
+ * 100% -- 120ms
+ */
+ pPrivate->RoomSizeInms = 10 + (((pPrivate->NewParams.RoomSize*11) + 5)/10);
+ }
+
+
+ /*
+ * Update the T delay number of samples and the all pass delay number of samples
+ */
+ if( (pPrivate->NewParams.RoomSize != pPrivate->CurrentParams.RoomSize) ||
+ (pPrivate->NewParams.SampleRate != pPrivate->CurrentParams.SampleRate) ||
+ (pPrivate->bFirstControl == LVM_TRUE))
+ {
+
+ LVM_UINT32 Temp;
+ LVM_INT32 APDelaySize;
+ LVM_INT32 Fs = LVM_GetFsFromTable(pPrivate->NewParams.SampleRate);
+ LVM_UINT32 DelayLengthSamples = (LVM_UINT32)(Fs * pPrivate->RoomSizeInms);
+ LVM_INT16 i;
+ LVM_INT16 ScaleTable[] = {LVREV_T_3_Power_minus0_on_4, LVREV_T_3_Power_minus1_on_4, LVREV_T_3_Power_minus2_on_4, LVREV_T_3_Power_minus3_on_4};
+ LVM_INT16 MaxT_Delay[] = {LVREV_MAX_T0_DELAY, LVREV_MAX_T1_DELAY, LVREV_MAX_T2_DELAY, LVREV_MAX_T3_DELAY};
+ LVM_INT16 MaxAP_Delay[] = {LVREV_MAX_AP0_DELAY, LVREV_MAX_AP1_DELAY, LVREV_MAX_AP2_DELAY, LVREV_MAX_AP3_DELAY};
+
+
+ /*
+ * For each delay line
+ */
+ for (i=0; i<NumberOfDelayLines; i++)
+ {
+ if (i != 0)
+ {
+ LVM_INT32 Temp1; /* to avoid QAC warning on type conversion */
+ LVM_INT32 Temp2; /* to avoid QAC warning on type conversion */
+
+ Temp2=(LVM_INT32)DelayLengthSamples;
+ MUL32x16INTO32(Temp2, ScaleTable[i], Temp1, 15)
+ Temp=(LVM_UINT32)Temp1;
+ }
+ else
+ {
+ Temp = DelayLengthSamples;
+ }
+ APDelaySize = Temp / 1500;
+
+
+ /*
+ * Set the fixed delay
+ */
+ Temp = (MaxT_Delay[i] - MaxAP_Delay[i]) * Fs / 48000;
+ pPrivate->Delay_AP[i] = pPrivate->T[i] - Temp;
+
+
+ /*
+ * Set the tap selection
+ */
+ if (pPrivate->AB_Selection)
+ {
+ /* Smooth from tap A to tap B */
+ pPrivate->pOffsetB[i] = &pPrivate->pDelay_T[i][pPrivate->T[i] - Temp - APDelaySize];
+ pPrivate->B_DelaySize[i] = APDelaySize;
+ pPrivate->Mixer_APTaps[i].Target1 = 0;
+ pPrivate->Mixer_APTaps[i].Target2 = 0x7fffffff;
+ }
+ else
+ {
+ /* Smooth from tap B to tap A */
+ pPrivate->pOffsetA[i] = &pPrivate->pDelay_T[i][pPrivate->T[i] - Temp - APDelaySize];
+ pPrivate->A_DelaySize[i] = APDelaySize;
+ pPrivate->Mixer_APTaps[i].Target2 = 0;
+ pPrivate->Mixer_APTaps[i].Target1 = 0x7fffffff;
+ }
+
+ /*
+ * Set the maximum block size to the smallest delay size
+ */
+ pPrivate->MaxBlkLen = Temp;
+ if (pPrivate->MaxBlkLen > pPrivate->A_DelaySize[i])
+ {
+ pPrivate->MaxBlkLen = pPrivate->A_DelaySize[i];
+ }
+ if (pPrivate->MaxBlkLen > pPrivate->B_DelaySize[i])
+ {
+ pPrivate->MaxBlkLen = pPrivate->B_DelaySize[i];
+ }
+ }
+ if (pPrivate->AB_Selection)
+ {
+ pPrivate->AB_Selection = 0;
+ }
+ else
+ {
+ pPrivate->AB_Selection = 1;
+ }
+
+
+ /*
+ * Limit the maximum block length
+ */
+ pPrivate->MaxBlkLen=pPrivate->MaxBlkLen-2; /* Just as a precausion, but no problem if we remove this line */
+ if(pPrivate->MaxBlkLen > pPrivate->InstanceParams.MaxBlockSize)
+ {
+ pPrivate->MaxBlkLen = (LVM_INT32)pPrivate->InstanceParams.MaxBlockSize;
+ }
+ }
+
+
+ /*
+ * Update the low pass filter coefficient
+ */
+ if( (pPrivate->NewParams.Damping != pPrivate->CurrentParams.Damping) ||
+ (pPrivate->NewParams.SampleRate != pPrivate->CurrentParams.SampleRate) ||
+ (pPrivate->bFirstControl == LVM_TRUE))
+ {
+
+ LVM_INT32 Temp;
+ LVM_INT32 Omega;
+ FO_C32_Coefs_t Coeffs;
+ LVM_INT16 i;
+ LVM_INT16 Damping = (LVM_INT16)((pPrivate->NewParams.Damping * 100) + 1000);
+ LVM_INT32 ScaleTable[] = {LVREV_T_3_Power_0_on_4, LVREV_T_3_Power_1_on_4, LVREV_T_3_Power_2_on_4, LVREV_T_3_Power_3_on_4};
+
+
+ /*
+ * For each filter
+ */
+ for (i=0; i<NumberOfDelayLines; i++)
+ {
+ if (i != 0)
+ {
+ MUL32x16INTO32(ScaleTable[i], Damping, Temp, 15)
+ }
+ else
+ {
+ Temp = Damping;
+ }
+ if(Temp <= (LVM_FsTable[pPrivate->NewParams.SampleRate] >> 1))
+ {
+ Omega = LVM_GetOmega((LVM_UINT16)Temp, pPrivate->NewParams.SampleRate);
+ LVM_FO_LPF(Omega, &Coeffs);
+ }
+ else
+ {
+ Coeffs.A0 = 0x7FF00000;
+ Coeffs.A1 = 0;
+ Coeffs.B1 = 0;
+ }
+ FO_1I_D32F32Cll_TRC_WRA_01_Init(&pPrivate->pFastCoef->RevLPCoefs[i], &pPrivate->pFastData->RevLPTaps[i], &Coeffs);
+ }
+ }
+
+
+ /*
+ * Update All-pass filter mixer time constants
+ */
+ if( (pPrivate->NewParams.RoomSize != pPrivate->CurrentParams.RoomSize) ||
+ (pPrivate->NewParams.SampleRate != pPrivate->CurrentParams.SampleRate) ||
+ (pPrivate->NewParams.Density != pPrivate->CurrentParams.Density))
+ {
+ LVM_INT16 i;
+ LVM_INT32 Alpha = (LVM_INT32)LVM_Mixer_TimeConstant(LVREV_ALLPASS_TC, LVM_GetFsFromTable(pPrivate->NewParams.SampleRate), 1);
+ LVM_INT32 AlphaTap = (LVM_INT32)LVM_Mixer_TimeConstant(LVREV_ALLPASS_TAP_TC, LVM_GetFsFromTable(pPrivate->NewParams.SampleRate), 1);
+
+ for (i=0; i<4; i++)
+ {
+ pPrivate->Mixer_APTaps[i].Alpha1 = AlphaTap;
+ pPrivate->Mixer_APTaps[i].Alpha2 = AlphaTap;
+ pPrivate->Mixer_SGFeedback[i].Alpha = Alpha;
+ pPrivate->Mixer_SGFeedforward[i].Alpha = Alpha;
+ }
+ }
+
+
+ /*
+ * Update the feed back gain
+ */
+ if( (pPrivate->NewParams.RoomSize != pPrivate->CurrentParams.RoomSize) ||
+ (pPrivate->NewParams.SampleRate != pPrivate->CurrentParams.SampleRate) ||
+ (pPrivate->NewParams.T60 != pPrivate->CurrentParams.T60) ||
+ (pPrivate->bFirstControl == LVM_TRUE))
+ {
+
+ LVM_INT32 G[4]; /* Feedback gain (Q7.24) */
+
+ if(pPrivate->NewParams.T60 == 0)
+ {
+ G[3] = 0;
+ G[2] = 0;
+ G[1] = 0;
+ G[0] = 0;
+ }
+ else
+ {
+ LVM_INT32 Temp1;
+ LVM_INT32 Temp2;
+ LVM_INT16 i;
+ LVM_INT16 ScaleTable[] = {LVREV_T_3_Power_minus0_on_4, LVREV_T_3_Power_minus1_on_4, LVREV_T_3_Power_minus2_on_4, LVREV_T_3_Power_minus3_on_4};
+
+
+ /*
+ * For each delay line
+ */
+ for (i=0; i<NumberOfDelayLines; i++)
+ {
+ Temp1 = (3 * pPrivate->RoomSizeInms * ScaleTable[i]) / pPrivate->NewParams.T60;
+ if(Temp1 >= (4 << 15))
+ {
+ G[i] = 0;
+ }
+ else if((Temp1 >= (2 << 15)))
+ {
+ Temp2 = LVM_Power10(-(Temp1 << 14));
+ Temp1 = LVM_Power10(-(Temp1 << 14));
+ MUL32x32INTO32(Temp1,Temp2,Temp1,24)
+ }
+ else
+ {
+ Temp1 = LVM_Power10(-(Temp1 << 15));
+ }
+ if (NumberOfDelayLines == 1)
+ {
+ G[i] = Temp1;
+ }
+ else
+ {
+ LVM_INT32 TempG;
+ MUL32x16INTO32(Temp1,ONE_OVER_SQRT_TWO,TempG,15)
+ G[i]=TempG;
+ }
+ }
+ }
+
+ /* Set up the feedback mixers for four delay lines */
+ pPrivate->FeedbackMixer[0].Target=G[0]<<7;
+ pPrivate->FeedbackMixer[1].Target=G[1]<<7;
+ pPrivate->FeedbackMixer[2].Target=G[2]<<7;
+ pPrivate->FeedbackMixer[3].Target=G[3]<<7;
+ }
+
+
+ /*
+ * Calculate the gain correction
+ */
+ if((pPrivate->NewParams.RoomSize != pPrivate->CurrentParams.RoomSize) ||
+ (pPrivate->NewParams.Level != pPrivate->CurrentParams.Level) ||
+ (pPrivate->NewParams.T60 != pPrivate->CurrentParams.T60) )
+ {
+ LVM_INT32 Index=0;
+ LVM_INT32 i=0;
+ LVM_INT32 Gain=0;
+ LVM_INT32 RoomSize=0;
+ LVM_INT32 T60;
+ LVM_INT32 Coefs[5];
+
+ if(pPrivate->NewParams.RoomSize==0)
+ {
+ RoomSize=1;
+ }
+ else
+ {
+ RoomSize=(LVM_INT32)pPrivate->NewParams.RoomSize;
+ }
+
+ if(pPrivate->NewParams.T60<100)
+ {
+ T60 = 100 * LVREV_T60_SCALE;
+ }
+ else
+ {
+ T60 = pPrivate->NewParams.T60 * LVREV_T60_SCALE;
+ }
+
+ /* Find the nearest room size in table */
+ for(i=0;i<24;i++)
+ {
+ if(RoomSize<= LVREV_GainPolyTable[i][0])
+ {
+ Index=i;
+ break;
+ }
+ }
+
+
+ if(RoomSize==LVREV_GainPolyTable[Index][0])
+ {
+ /* Take table values if the room size is in table */
+ for(i=1;i<5;i++)
+ {
+ Coefs[i-1]=LVREV_GainPolyTable[Index][i];
+ }
+ Coefs[4]=0;
+ Gain=LVM_Polynomial(3,Coefs,T60); /* Q.24 result */
+ }
+ else
+ {
+ /* Interpolate the gain between nearest room sizes */
+
+ LVM_INT32 Gain1,Gain2;
+ LVM_INT32 Tot_Dist,Dist;
+
+ Tot_Dist=LVREV_GainPolyTable[Index][0]-LVREV_GainPolyTable[Index-1][0];
+ Dist=RoomSize-LVREV_GainPolyTable[Index-1][0];
+
+
+ /* Get gain for first */
+ for(i=1;i<5;i++)
+ {
+ Coefs[i-1]=LVREV_GainPolyTable[Index-1][i];
+ }
+ Coefs[4]=0;
+
+ Gain1=LVM_Polynomial(3,Coefs,T60); /* Q.24 result */
+
+ /* Get gain for second */
+ for(i=1;i<5;i++)
+ {
+ Coefs[i-1]=LVREV_GainPolyTable[Index][i];
+ }
+ Coefs[4]=0;
+
+ Gain2=LVM_Polynomial(3,Coefs,T60); /* Q.24 result */
+
+ /* Linear Interpolate the gain */
+ Gain = Gain1+ (((Gain2-Gain1)*Dist)/(Tot_Dist));
+ }
+
+
+ /*
+ * Get the inverse of gain: Q.15
+ * Gain is mostly above one except few cases, take only gains above 1
+ */
+ if(Gain < 16777216L)
+ {
+ pPrivate->Gain= 32767;
+ }
+ else
+ {
+ pPrivate->Gain=(LVM_INT16)(LVM_MAXINT_32/(Gain>>8));
+ }
+
+
+ Index=((32767*100)/(100+pPrivate->NewParams.Level));
+ pPrivate->Gain=(LVM_INT16)((pPrivate->Gain*Index)>>15);
+ pPrivate->GainMixer.Target = pPrivate->Gain*Index;
+ }
+
+
+ /*
+ * Update the all pass comb filter coefficient
+ */
+ if( (pPrivate->NewParams.Density != pPrivate->CurrentParams.Density) ||
+ (pPrivate->bFirstControl == LVM_TRUE))
+ {
+ LVM_INT16 i;
+ LVM_INT32 b = pPrivate->NewParams.Density * LVREV_B_8_on_1000;
+
+ for (i=0;i<4; i++)
+ {
+ pPrivate->Mixer_SGFeedback[i].Target = b;
+ pPrivate->Mixer_SGFeedforward[i].Target = b;
+ }
+ }
+
+
+ /*
+ * Update the bypass mixer time constant
+ */
+ if((pPrivate->NewParams.SampleRate != pPrivate->CurrentParams.SampleRate) ||
+ (pPrivate->NewParams.SourceFormat != pPrivate->CurrentParams.SourceFormat) ||
+ (pPrivate->bFirstControl == LVM_TRUE))
+ {
+ LVM_UINT16 NumChannels = 1; /* Assume MONO format */
+ LVM_INT32 Alpha;
+
+ Alpha = (LVM_INT32)LVM_Mixer_TimeConstant(LVREV_FEEDBACKMIXER_TC, LVM_GetFsFromTable(pPrivate->NewParams.SampleRate), NumChannels);
+ pPrivate->FeedbackMixer[0].Alpha=Alpha;
+ pPrivate->FeedbackMixer[1].Alpha=Alpha;
+ pPrivate->FeedbackMixer[2].Alpha=Alpha;
+ pPrivate->FeedbackMixer[3].Alpha=Alpha;
+
+ if (pPrivate->NewParams.SourceFormat != LVM_MONO)
+ {
+ /* Stereo or Mono-in-Stereo format data */
+ NumChannels = 2;
+ }
+ pPrivate->BypassMixer.Alpha1 = (LVM_INT32)LVM_Mixer_TimeConstant(LVREV_BYPASSMIXER_TC, LVM_GetFsFromTable(pPrivate->NewParams.SampleRate), NumChannels);
+ pPrivate->BypassMixer.Alpha2 = pPrivate->BypassMixer.Alpha1;
+ pPrivate->GainMixer.Alpha = pPrivate->BypassMixer.Alpha1;
+ }
+
+
+ /*
+ * Update the bypass mixer targets
+ */
+ if( (pPrivate->NewParams.Level != pPrivate->CurrentParams.Level) &&
+ (pPrivate->NewParams.OperatingMode == LVM_MODE_ON))
+ {
+ pPrivate->BypassMixer.Target2 = ((LVM_INT32)(pPrivate->NewParams.Level * 32767)/100)<<16;
+ pPrivate->BypassMixer.Target1 = LVREV_HEADROOM << 16;
+ if ((pPrivate->NewParams.Level == 0) && (pPrivate->bFirstControl == LVM_FALSE))
+ {
+ pPrivate->BypassMixer.CallbackSet2 = LVM_TRUE;
+ }
+ if (pPrivate->NewParams.Level != 0)
+ {
+ pPrivate->bDisableReverb = LVM_FALSE;
+ }
+ }
+
+ if(pPrivate->NewParams.OperatingMode != pPrivate->CurrentParams.OperatingMode)
+ {
+ if(pPrivate->NewParams.OperatingMode == LVM_MODE_ON)
+ {
+ pPrivate->BypassMixer.Target2 = ((LVM_INT32)(pPrivate->NewParams.Level * 32767)/100)<<16;
+ pPrivate->BypassMixer.Target1 = LVREV_HEADROOM << 16;
+
+ pPrivate->BypassMixer.CallbackSet2 = LVM_FALSE;
+ OperatingMode = LVM_MODE_ON;
+ if (pPrivate->NewParams.Level == 0)
+ {
+ pPrivate->bDisableReverb = LVM_TRUE;
+ }
+ else
+ {
+ pPrivate->bDisableReverb = LVM_FALSE;
+ }
+ }
+ else if (pPrivate->bFirstControl == LVM_FALSE)
+ {
+ pPrivate->BypassMixer.Target2 = 0x00000000;
+ pPrivate->BypassMixer.Target1 = 0x7FFFFFFF;
+ pPrivate->BypassMixer.CallbackSet2 = LVM_TRUE;
+ pPrivate->GainMixer.Target = 0x03FFFFFF;
+ OperatingMode = LVM_MODE_ON;
+ }
+ else
+ {
+ OperatingMode = LVM_MODE_OFF;
+ }
+ }
+
+
+ /*
+ * If it is the first call to ApplyNew settings force the current to the target to begin immediate playback of the effect
+ */
+ if(pPrivate->bFirstControl == LVM_TRUE)
+ {
+ pPrivate->BypassMixer.Current1 = pPrivate->BypassMixer.Target1;
+ pPrivate->BypassMixer.Current2 = pPrivate->BypassMixer.Target2;
+ }
+
+
+ /*
+ * Copy the new parameters
+ */
+ pPrivate->CurrentParams = pPrivate->NewParams;
+ pPrivate->CurrentParams.OperatingMode = OperatingMode;
+
+
+ /*
+ * Update flag
+ */
+ if(pPrivate->bFirstControl == LVM_TRUE)
+ {
+ pPrivate->bFirstControl = LVM_FALSE;
+ }
+
+
+ return LVREV_SUCCESS;
+}
+
+
+/****************************************************************************************/
+/* */
+/* FUNCTION: BypassMixer_Callback */
+/* */
+/* DESCRIPTION: */
+/* Controls the On to Off operating mode transition */
+/* */
+/* PARAMETERS: */
+/* pPrivate Pointer to the instance private parameters */
+/* */
+/* RETURNS: */
+/* LVREV_Success Succeeded */
+/* LVREV_NULLADDRESS When pPrivate is NULL */
+/* */
+/* NOTES: */
+/* */
+/****************************************************************************************/
+LVM_INT32 BypassMixer_Callback (void *pCallbackData,
+ void *pGeneralPurpose,
+ LVM_INT16 GeneralPurpose )
+{
+
+ LVREV_Instance_st *pLVREV_Private = (LVREV_Instance_st *)pCallbackData;
+
+
+ /*
+ * Avoid build warnings
+ */
+ (void)pGeneralPurpose;
+ (void)GeneralPurpose;
+
+
+ /*
+ * Turn off
+ */
+ pLVREV_Private->CurrentParams.OperatingMode = LVM_MODE_OFF;
+ pLVREV_Private->bDisableReverb = LVM_TRUE;
+ LVREV_ClearAudioBuffers((LVREV_Handle_t)pCallbackData);
+
+
+ return 0;
+}
+
+/* End of file */
+
diff --git a/media/libeffects/lvm/lib/Reverb/src/LVREV_ClearAudioBuffers.c b/media/libeffects/lvm/lib/Reverb/src/LVREV_ClearAudioBuffers.c
new file mode 100755
index 0000000..b02b1a7
--- /dev/null
+++ b/media/libeffects/lvm/lib/Reverb/src/LVREV_ClearAudioBuffers.c
@@ -0,0 +1,113 @@
+/*
+ * Copyright (C) 2004-2010 NXP Software
+ * Copyright (C) 2010 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.
+ */
+
+/****************************************************************************************/
+/* */
+/* Project:: */
+/* $Author: nxp007753 $ */
+/* $Revision: 1316 $ */
+/* $Date: 2010-07-23 11:53:24 +0200 (Fri, 23 Jul 2010) $ */
+/* */
+/****************************************************************************************/
+
+/****************************************************************************************/
+/* */
+/* Includes */
+/* */
+/****************************************************************************************/
+#include "LVREV_Private.h"
+#include "VectorArithmetic.h"
+
+
+/****************************************************************************************/
+/* */
+/* FUNCTION: LVREV_ClearAudioBuffers */
+/* */
+/* DESCRIPTION: */
+/* This function is used to clear the internal audio buffers of the module. */
+/* */
+/* PARAMETERS: */
+/* hInstance Instance handle */
+/* */
+/* RETURNS: */
+/* LVREV_SUCCESS Initialisation succeeded */
+/* LVREV_NULLADDRESS Instance is NULL */
+/* */
+/* NOTES: */
+/* 1. This function must not be interrupted by the LVM_Process function */
+/* */
+/****************************************************************************************/
+LVREV_ReturnStatus_en LVREV_ClearAudioBuffers(LVREV_Handle_t hInstance)
+{
+
+ LVREV_Instance_st *pLVREV_Private = (LVREV_Instance_st *)hInstance;
+
+
+ /*
+ * Check for error conditions
+ */
+ /* Check for NULL pointers */
+ if(hInstance == LVM_NULL)
+ {
+ return LVREV_NULLADDRESS;
+ }
+
+ /*
+ * Clear all filter tap data, delay-lines and other signal related data
+ */
+
+
+ LoadConst_32(0,
+ (void *)&pLVREV_Private->pFastData->HPTaps, /* Destination Cast to void: no dereferencing in function*/
+ 2);
+ LoadConst_32(0,
+ (void *)&pLVREV_Private->pFastData->LPTaps, /* Destination Cast to void: no dereferencing in function*/
+ 2);
+
+ if((LVM_UINT16)pLVREV_Private->InstanceParams.NumDelays == LVREV_DELAYLINES_4)
+ {
+ LoadConst_32(0, (LVM_INT32 *)&pLVREV_Private->pFastData->RevLPTaps[3], 2);
+ LoadConst_32(0, (LVM_INT32 *)&pLVREV_Private->pFastData->RevLPTaps[2], 2);
+ LoadConst_32(0, (LVM_INT32 *)&pLVREV_Private->pFastData->RevLPTaps[1], 2);
+ LoadConst_32(0, (LVM_INT32 *)&pLVREV_Private->pFastData->RevLPTaps[0], 2);
+
+ LoadConst_32(0,pLVREV_Private->pDelay_T[3], (LVM_INT16)LVREV_MAX_T3_DELAY);
+ LoadConst_32(0,pLVREV_Private->pDelay_T[2], (LVM_INT16)LVREV_MAX_T2_DELAY);
+ LoadConst_32(0,pLVREV_Private->pDelay_T[1], (LVM_INT16)LVREV_MAX_T1_DELAY);
+ LoadConst_32(0,pLVREV_Private->pDelay_T[0], (LVM_INT16)LVREV_MAX_T0_DELAY);
+
+ }
+
+ if((LVM_UINT16)pLVREV_Private->InstanceParams.NumDelays >= LVREV_DELAYLINES_2)
+ {
+ LoadConst_32(0, (LVM_INT32 *)&pLVREV_Private->pFastData->RevLPTaps[1], 2);
+ LoadConst_32(0, (LVM_INT32 *)&pLVREV_Private->pFastData->RevLPTaps[0], 2);
+
+ LoadConst_32(0,pLVREV_Private->pDelay_T[1], (LVM_INT16)LVREV_MAX_T1_DELAY);
+ LoadConst_32(0,pLVREV_Private->pDelay_T[0], (LVM_INT16)LVREV_MAX_T0_DELAY);
+ }
+
+ if((LVM_UINT16)pLVREV_Private->InstanceParams.NumDelays >= LVREV_DELAYLINES_1)
+ {
+ LoadConst_32(0, (LVM_INT32 *)&pLVREV_Private->pFastData->RevLPTaps[0], 2);
+ LoadConst_32(0,pLVREV_Private->pDelay_T[0], (LVM_INT16)LVREV_MAX_T0_DELAY);
+ }
+
+ return LVREV_SUCCESS;
+}
+
+/* End of file */
diff --git a/media/libeffects/lvm/lib/Reverb/src/LVREV_GetControlParameters.c b/media/libeffects/lvm/lib/Reverb/src/LVREV_GetControlParameters.c
new file mode 100755
index 0000000..ebf145e
--- /dev/null
+++ b/media/libeffects/lvm/lib/Reverb/src/LVREV_GetControlParameters.c
@@ -0,0 +1,78 @@
+/*
+ * Copyright (C) 2004-2010 NXP Software
+ * Copyright (C) 2010 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.
+ */
+
+/****************************************************************************************/
+/* */
+/* Project:: */
+/* $Author: nxp27078 $*/
+/* $Revision: 762 $*/
+/* $Date: 2010-06-11 14:50:33 +0200 (Fri, 11 Jun 2010) $*/
+/* */
+/****************************************************************************************/
+
+/****************************************************************************************/
+/* */
+/* Includes */
+/* */
+/****************************************************************************************/
+#include "LVREV_Private.h"
+
+
+/****************************************************************************************/
+/* */
+/* FUNCTION: LVREV_GetControlParameters */
+/* */
+/* DESCRIPTION: */
+/* Request the LVREV module control parameters. The current parameter set is returned */
+/* via the parameter pointer. */
+/* */
+/* PARAMETERS: */
+/* hInstance Instance handle */
+/* pControlParams Pointer to an empty parameter structure */
+/* */
+/* RETURNS: */
+/* LVREV_Success Succeeded */
+/* LVREV_NULLADDRESS When hInstance or pControlParams is NULL */
+/* */
+/* NOTES: */
+/* 1. This function may be interrupted by the LVREV_Process function */
+/* */
+/****************************************************************************************/
+LVREV_ReturnStatus_en LVREV_GetControlParameters(LVREV_Handle_t hInstance,
+ LVREV_ControlParams_st *pControlParams)
+{
+
+ LVREV_Instance_st *pLVREV_Private = (LVREV_Instance_st *)hInstance;
+
+
+ /*
+ * Check for error conditions
+ */
+ if((hInstance == LVM_NULL) || (pControlParams == LVM_NULL))
+ {
+ return LVREV_NULLADDRESS;
+ }
+
+ /*
+ * Return the current parameters
+ */
+ *pControlParams = pLVREV_Private->NewParams;
+
+ return LVREV_SUCCESS;
+}
+
+/* End of file */
diff --git a/media/libeffects/lvm/lib/Reverb/src/LVREV_GetInstanceHandle.c b/media/libeffects/lvm/lib/Reverb/src/LVREV_GetInstanceHandle.c
new file mode 100755
index 0000000..ca1c84d
--- /dev/null
+++ b/media/libeffects/lvm/lib/Reverb/src/LVREV_GetInstanceHandle.c
@@ -0,0 +1,331 @@
+/*
+ * Copyright (C) 2004-2010 NXP Software
+ * Copyright (C) 2010 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.
+ */
+
+/****************************************************************************************/
+/* */
+/* Project:: */
+/* $Author: nxp007753 $ */
+/* $Revision: 1316 $ */
+/* $Date: 2010-07-23 11:53:24 +0200 (Fri, 23 Jul 2010) $ */
+/* */
+/****************************************************************************************/
+
+/****************************************************************************************/
+/* */
+/* Includes */
+/* */
+/****************************************************************************************/
+#include "LVREV_Private.h"
+#include "InstAlloc.h"
+
+
+/****************************************************************************************/
+/* */
+/* FUNCTION: LVREV_GetInstanceHandle */
+/* */
+/* DESCRIPTION: */
+/* This function is used to create a LVREV module instance. It returns the created */
+/* instance handle through phInstance. All parameters are set to their default, */
+/* inactive state. */
+/* */
+/* PARAMETERS: */
+/* phInstance pointer to the instance handle */
+/* pMemoryTable Pointer to the memory definition table */
+/* pInstanceParams Pointer to the instance parameters */
+/* */
+/* RETURNS: */
+/* LVREV_SUCCESS Succeeded */
+/* LVREV_NULLADDRESS When phInstance or pMemoryTable or pInstanceParams is NULL */
+/* LVREV_NULLADDRESS When one of the memory regions has a NULL pointer */
+/* */
+/* NOTES: */
+/* */
+/****************************************************************************************/
+LVREV_ReturnStatus_en LVREV_GetInstanceHandle(LVREV_Handle_t *phInstance,
+ LVREV_MemoryTable_st *pMemoryTable,
+ LVREV_InstanceParams_st *pInstanceParams)
+{
+
+ INST_ALLOC SlowData;
+ INST_ALLOC FastData;
+ INST_ALLOC FastCoef;
+ INST_ALLOC Temporary;
+ LVREV_Instance_st *pLVREV_Private;
+ LVM_INT16 i;
+ LVM_UINT16 MaxBlockSize;
+
+
+ /*
+ * Check for error conditions
+ */
+ /* Check for NULL pointers */
+ if((phInstance == LVM_NULL) || (pMemoryTable == LVM_NULL) || (pInstanceParams == LVM_NULL))
+ {
+ return LVREV_NULLADDRESS;
+ }
+ /* Check the memory table for NULL pointers */
+ for (i = 0; i < LVREV_NR_MEMORY_REGIONS; i++)
+ {
+ if (pMemoryTable->Region[i].Size!=0)
+ {
+ if (pMemoryTable->Region[i].pBaseAddress==LVM_NULL)
+ {
+ return(LVREV_NULLADDRESS);
+ }
+ }
+ }
+
+ /*
+ * Check all instance parameters are in range
+ */
+ /* Check for a non-zero block size */
+ if (pInstanceParams->MaxBlockSize == 0)
+ {
+ return LVREV_OUTOFRANGE;
+ }
+
+ /* Check for a valid number of delay lines */
+ if ((pInstanceParams->NumDelays != LVREV_DELAYLINES_1)&&
+ (pInstanceParams->NumDelays != LVREV_DELAYLINES_2)&&
+ (pInstanceParams->NumDelays != LVREV_DELAYLINES_4))
+ {
+ return LVREV_OUTOFRANGE;
+ }
+
+ /*
+ * Initialise the InstAlloc instances
+ */
+ InstAlloc_Init(&SlowData, pMemoryTable->Region[LVM_PERSISTENT_SLOW_DATA].pBaseAddress);
+ InstAlloc_Init(&FastData, pMemoryTable->Region[LVM_PERSISTENT_FAST_DATA].pBaseAddress);
+ InstAlloc_Init(&FastCoef, pMemoryTable->Region[LVM_PERSISTENT_FAST_COEF].pBaseAddress);
+ InstAlloc_Init(&Temporary, pMemoryTable->Region[LVM_TEMPORARY_FAST].pBaseAddress);
+
+ /*
+ * Zero all memory regions
+ */
+ LoadConst_16(0, (LVM_INT16 *)pMemoryTable->Region[LVM_PERSISTENT_SLOW_DATA].pBaseAddress, (LVM_INT16)((pMemoryTable->Region[LVM_PERSISTENT_SLOW_DATA].Size)/sizeof(LVM_INT16)));
+ LoadConst_16(0, (LVM_INT16 *)pMemoryTable->Region[LVM_PERSISTENT_FAST_DATA].pBaseAddress, (LVM_INT16)((pMemoryTable->Region[LVM_PERSISTENT_FAST_DATA].Size)/sizeof(LVM_INT16)));
+ LoadConst_16(0, (LVM_INT16 *)pMemoryTable->Region[LVM_PERSISTENT_FAST_COEF].pBaseAddress, (LVM_INT16)((pMemoryTable->Region[LVM_PERSISTENT_FAST_COEF].Size)/sizeof(LVM_INT16)));
+ LoadConst_16(0, (LVM_INT16 *)pMemoryTable->Region[LVM_TEMPORARY_FAST].pBaseAddress, (LVM_INT16)((pMemoryTable->Region[LVM_TEMPORARY_FAST].Size)/sizeof(LVM_INT16)));
+
+ /*
+ * Set the instance handle if not already initialised
+ */
+ if (*phInstance == LVM_NULL)
+ {
+ *phInstance = InstAlloc_AddMember(&SlowData, sizeof(LVREV_Instance_st));
+ }
+ pLVREV_Private =(LVREV_Instance_st *)*phInstance;
+ pLVREV_Private->MemoryTable = *pMemoryTable;
+
+ if(pInstanceParams->NumDelays ==LVREV_DELAYLINES_4)
+ {
+ MaxBlockSize = LVREV_MAX_AP3_DELAY;
+ }
+ else if(pInstanceParams->NumDelays ==LVREV_DELAYLINES_2)
+ {
+ MaxBlockSize = LVREV_MAX_AP1_DELAY;
+ }
+ else
+ {
+ MaxBlockSize = LVREV_MAX_AP0_DELAY;
+ }
+
+ if(MaxBlockSize>pInstanceParams->MaxBlockSize)
+ {
+ MaxBlockSize=pInstanceParams->MaxBlockSize;
+ }
+
+
+ /*
+ * Set the data, coefficient and temporary memory pointers
+ */
+ pLVREV_Private->pFastData = InstAlloc_AddMember(&FastData, sizeof(LVREV_FastData_st)); /* Fast data memory base address */
+
+ if(pInstanceParams->NumDelays == LVREV_DELAYLINES_4)
+ {
+ pLVREV_Private->pDelay_T[3] = InstAlloc_AddMember(&FastData, LVREV_MAX_T3_DELAY * sizeof(LVM_INT32));
+ pLVREV_Private->pDelay_T[2] = InstAlloc_AddMember(&FastData, LVREV_MAX_T2_DELAY * sizeof(LVM_INT32));
+ pLVREV_Private->pDelay_T[1] = InstAlloc_AddMember(&FastData, LVREV_MAX_T1_DELAY * sizeof(LVM_INT32));
+ pLVREV_Private->pDelay_T[0] = InstAlloc_AddMember(&FastData, LVREV_MAX_T0_DELAY * sizeof(LVM_INT32));
+
+ for( i = 0; i < 4; i++)
+ {
+ pLVREV_Private->pScratchDelayLine[i] = InstAlloc_AddMember(&Temporary, sizeof(LVM_INT32) * MaxBlockSize); /* Scratch for each delay line output */
+ }
+
+ LoadConst_32(0,pLVREV_Private->pDelay_T[3] ,(LVM_INT16)LVREV_MAX_T3_DELAY);
+ LoadConst_32(0,pLVREV_Private->pDelay_T[2] ,(LVM_INT16)LVREV_MAX_T2_DELAY);
+ LoadConst_32(0,pLVREV_Private->pDelay_T[1] ,(LVM_INT16)LVREV_MAX_T1_DELAY);
+ LoadConst_32(0,pLVREV_Private->pDelay_T[0] ,(LVM_INT16)LVREV_MAX_T0_DELAY);
+ }
+
+ if(pInstanceParams->NumDelays == LVREV_DELAYLINES_2)
+ {
+ pLVREV_Private->pDelay_T[1] = InstAlloc_AddMember(&FastData, LVREV_MAX_T1_DELAY * sizeof(LVM_INT32));
+ pLVREV_Private->pDelay_T[0] = InstAlloc_AddMember(&FastData, LVREV_MAX_T0_DELAY * sizeof(LVM_INT32));
+
+ for( i = 0; i < 2; i++)
+ {
+ pLVREV_Private->pScratchDelayLine[i] = InstAlloc_AddMember(&Temporary, sizeof(LVM_INT32) * MaxBlockSize); /* Scratch for each delay line output */
+ }
+
+ LoadConst_32(0,pLVREV_Private->pDelay_T[1] , (LVM_INT16)LVREV_MAX_T1_DELAY);
+ LoadConst_32(0,pLVREV_Private->pDelay_T[0] , (LVM_INT16)LVREV_MAX_T0_DELAY);
+ }
+
+ if(pInstanceParams->NumDelays == LVREV_DELAYLINES_1)
+ {
+ pLVREV_Private->pDelay_T[0] = InstAlloc_AddMember(&FastData, LVREV_MAX_T0_DELAY * sizeof(LVM_INT32));
+
+ for( i = 0; i < 1; i++)
+ {
+ pLVREV_Private->pScratchDelayLine[i] = InstAlloc_AddMember(&Temporary, sizeof(LVM_INT32) * MaxBlockSize); /* Scratch for each delay line output */
+ }
+
+ LoadConst_32(0,pLVREV_Private->pDelay_T[0] , (LVM_INT16)LVREV_MAX_T0_DELAY);
+ }
+
+ /* All-pass delay buffer addresses and sizes */
+ pLVREV_Private->T[0] = LVREV_MAX_T0_DELAY;
+ pLVREV_Private->T[1] = LVREV_MAX_T1_DELAY;
+ pLVREV_Private->T[2] = LVREV_MAX_T2_DELAY;
+ pLVREV_Private->T[3] = LVREV_MAX_T3_DELAY;
+ pLVREV_Private->AB_Selection = 1; /* Select smoothing A to B */
+
+
+ pLVREV_Private->pFastCoef = InstAlloc_AddMember(&FastCoef, sizeof(LVREV_FastCoef_st)); /* Fast coefficient memory base address */
+ pLVREV_Private->pScratch = InstAlloc_AddMember(&Temporary, sizeof(LVM_INT32) * MaxBlockSize); /* General purpose scratch */
+ pLVREV_Private->pInputSave = InstAlloc_AddMember(&Temporary, 2 * sizeof(LVM_INT32) * MaxBlockSize); /* Mono->stereo input save for end mix */
+ LoadConst_32(0, pLVREV_Private->pInputSave, (LVM_INT16)(MaxBlockSize*2));
+
+
+ /*
+ * Save the instance parameters in the instance structure
+ */
+ pLVREV_Private->InstanceParams = *pInstanceParams;
+
+
+ /*
+ * Set the parameters to invalid
+ */
+ pLVREV_Private->CurrentParams.SampleRate = LVM_FS_INVALID;
+ pLVREV_Private->CurrentParams.OperatingMode = LVM_MODE_DUMMY;
+ pLVREV_Private->CurrentParams.SourceFormat = LVM_SOURCE_DUMMY;
+
+ pLVREV_Private->bControlPending = LVM_FALSE;
+ pLVREV_Private->bFirstControl = LVM_TRUE;
+ pLVREV_Private->bDisableReverb = LVM_FALSE;
+
+
+ /*
+ * Set mixer parameters
+ */
+ pLVREV_Private->BypassMixer.CallbackParam2 = 0;
+ pLVREV_Private->BypassMixer.pCallbackHandle2 = pLVREV_Private;
+ pLVREV_Private->BypassMixer.pGeneralPurpose2 = LVM_NULL;
+ pLVREV_Private->BypassMixer.pCallBack2 = BypassMixer_Callback;
+ pLVREV_Private->BypassMixer.CallbackSet2 = LVM_FALSE;
+ pLVREV_Private->BypassMixer.Current2 = 0;
+ pLVREV_Private->BypassMixer.Target2 = 0;
+ pLVREV_Private->BypassMixer.CallbackParam1 = 0;
+ pLVREV_Private->BypassMixer.pCallbackHandle1 = LVM_NULL;
+ pLVREV_Private->BypassMixer.pGeneralPurpose1 = LVM_NULL;
+ pLVREV_Private->BypassMixer.pCallBack1 = LVM_NULL;
+ pLVREV_Private->BypassMixer.CallbackSet1 = LVM_FALSE;
+ pLVREV_Private->BypassMixer.Current1 = 0x7fffffff;
+ pLVREV_Private->BypassMixer.Target1 = 0x7fffffff;
+
+ pLVREV_Private->RoomSizeInms = 100; // 100 msec
+
+
+ /*
+ * Set the output gain mixer parameters
+ */
+ pLVREV_Private->GainMixer.CallbackParam = 0;
+ pLVREV_Private->GainMixer.pCallbackHandle = LVM_NULL;
+ pLVREV_Private->GainMixer.pGeneralPurpose = LVM_NULL;
+ pLVREV_Private->GainMixer.pCallBack = LVM_NULL;
+ pLVREV_Private->GainMixer.CallbackSet = LVM_FALSE;
+ pLVREV_Private->GainMixer.Current = 0x03ffffff;
+ pLVREV_Private->GainMixer.Target = 0x03ffffff;
+
+
+ /*
+ * Set the All-Pass Filter mixers
+ */
+ for (i=0; i<4; i++)
+ {
+ pLVREV_Private->pOffsetA[i] = pLVREV_Private->pDelay_T[i];
+ pLVREV_Private->pOffsetB[i] = pLVREV_Private->pDelay_T[i];
+ /* Delay tap selection mixer */
+ pLVREV_Private->Mixer_APTaps[i].CallbackParam2 = 0;
+ pLVREV_Private->Mixer_APTaps[i].pCallbackHandle2 = LVM_NULL;
+ pLVREV_Private->Mixer_APTaps[i].pGeneralPurpose2 = LVM_NULL;
+ pLVREV_Private->Mixer_APTaps[i].pCallBack2 = LVM_NULL;
+ pLVREV_Private->Mixer_APTaps[i].CallbackSet2 = LVM_FALSE;
+ pLVREV_Private->Mixer_APTaps[i].Current2 = 0;
+ pLVREV_Private->Mixer_APTaps[i].Target2 = 0;
+ pLVREV_Private->Mixer_APTaps[i].CallbackParam1 = 0;
+ pLVREV_Private->Mixer_APTaps[i].pCallbackHandle1 = LVM_NULL;
+ pLVREV_Private->Mixer_APTaps[i].pGeneralPurpose1 = LVM_NULL;
+ pLVREV_Private->Mixer_APTaps[i].pCallBack1 = LVM_NULL;
+ pLVREV_Private->Mixer_APTaps[i].CallbackSet1 = LVM_FALSE;
+ pLVREV_Private->Mixer_APTaps[i].Current1 = 0;
+ pLVREV_Private->Mixer_APTaps[i].Target1 = 0x7fffffff;
+ /* Feedforward mixer */
+ pLVREV_Private->Mixer_SGFeedforward[i].CallbackParam = 0;
+ pLVREV_Private->Mixer_SGFeedforward[i].pCallbackHandle = LVM_NULL;
+ pLVREV_Private->Mixer_SGFeedforward[i].pGeneralPurpose = LVM_NULL;
+ pLVREV_Private->Mixer_SGFeedforward[i].pCallBack = LVM_NULL;
+ pLVREV_Private->Mixer_SGFeedforward[i].CallbackSet = LVM_FALSE;
+ pLVREV_Private->Mixer_SGFeedforward[i].Current = 0;
+ pLVREV_Private->Mixer_SGFeedforward[i].Target = 0;
+ /* Feedback mixer */
+ pLVREV_Private->Mixer_SGFeedback[i].CallbackParam = 0;
+ pLVREV_Private->Mixer_SGFeedback[i].pCallbackHandle = LVM_NULL;
+ pLVREV_Private->Mixer_SGFeedback[i].pGeneralPurpose = LVM_NULL;
+ pLVREV_Private->Mixer_SGFeedback[i].pCallBack = LVM_NULL;
+ pLVREV_Private->Mixer_SGFeedback[i].CallbackSet = LVM_FALSE;
+ pLVREV_Private->Mixer_SGFeedback[i].Current = 0;
+ pLVREV_Private->Mixer_SGFeedback[i].Target = 0;
+ /* Feedback gain mixer */
+ pLVREV_Private->FeedbackMixer[i].CallbackParam = 0;
+ pLVREV_Private->FeedbackMixer[i].pCallbackHandle = LVM_NULL;
+ pLVREV_Private->FeedbackMixer[i].pGeneralPurpose = LVM_NULL;
+ pLVREV_Private->FeedbackMixer[i].pCallBack = LVM_NULL;
+ pLVREV_Private->FeedbackMixer[i].CallbackSet = LVM_FALSE;
+ pLVREV_Private->FeedbackMixer[i].Current = 0;
+ pLVREV_Private->FeedbackMixer[i].Target = 0;
+ }
+ /* Delay tap index */
+ pLVREV_Private->A_DelaySize[0] = LVREV_MAX_AP0_DELAY;
+ pLVREV_Private->B_DelaySize[0] = LVREV_MAX_AP0_DELAY;
+ pLVREV_Private->A_DelaySize[1] = LVREV_MAX_AP1_DELAY;
+ pLVREV_Private->B_DelaySize[1] = LVREV_MAX_AP1_DELAY;
+ pLVREV_Private->A_DelaySize[2] = LVREV_MAX_AP2_DELAY;
+ pLVREV_Private->B_DelaySize[2] = LVREV_MAX_AP2_DELAY;
+ pLVREV_Private->A_DelaySize[3] = LVREV_MAX_AP3_DELAY;
+ pLVREV_Private->B_DelaySize[3] = LVREV_MAX_AP3_DELAY;
+
+
+ LVREV_ClearAudioBuffers(*phInstance);
+
+ return LVREV_SUCCESS;
+}
+
+/* End of file */
diff --git a/media/libeffects/lvm/lib/Reverb/src/LVREV_GetMemoryTable.c b/media/libeffects/lvm/lib/Reverb/src/LVREV_GetMemoryTable.c
new file mode 100755
index 0000000..e16a3d3
--- /dev/null
+++ b/media/libeffects/lvm/lib/Reverb/src/LVREV_GetMemoryTable.c
@@ -0,0 +1,254 @@
+/*
+ * Copyright (C) 2004-2010 NXP Software
+ * Copyright (C) 2010 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.
+ */
+
+/****************************************************************************************/
+/* */
+/* Project:: */
+/* $Author: beq07716 $*/
+/* $Revision: 1007 $*/
+/* $Date: 2010-06-28 14:06:36 +0200 (Mon, 28 Jun 2010) $*/
+/* */
+/****************************************************************************************/
+
+/****************************************************************************************/
+/* */
+/* Includes */
+/* */
+/****************************************************************************************/
+#include "LVREV_Private.h"
+#include "InstAlloc.h"
+
+/****************************************************************************************/
+/* */
+/* FUNCTION: LVREV_GetMemoryTable */
+/* */
+/* DESCRIPTION: */
+/* This function is used for memory allocation and free. It can be called in */
+/* two ways: */
+/* */
+/* hInstance = NULL Returns the memory requirements */
+/* hInstance = Instance handle Returns the memory requirements and allocated */
+/* base addresses. */
+/* */
+/* When this function is called for memory allocation (hInstance=NULL) the memory */
+/* base address pointers are NULL on return. */
+/* */
+/* When the function is called for free (hInstance = Instance Handle) the memory */
+/* table returns the allocated memory and base addresses used during initialisation. */
+/* */
+/* PARAMETERS: */
+/* hInstance Instance Handle */
+/* pMemoryTable Pointer to an empty memory table */
+/* pInstanceParams Pointer to the instance parameters */
+/* */
+/* RETURNS: */
+/* LVREV_Success Succeeded */
+/* LVREV_NULLADDRESS When pMemoryTable is NULL */
+/* LVREV_NULLADDRESS When requesting memory requirements and pInstanceParams */
+/* is NULL */
+/* */
+/* NOTES: */
+/* 1. This function may be interrupted by the LVREV_Process function */
+/* */
+/****************************************************************************************/
+LVREV_ReturnStatus_en LVREV_GetMemoryTable(LVREV_Handle_t hInstance,
+ LVREV_MemoryTable_st *pMemoryTable,
+ LVREV_InstanceParams_st *pInstanceParams)
+{
+
+ INST_ALLOC SlowData;
+ INST_ALLOC FastData;
+ INST_ALLOC FastCoef;
+ INST_ALLOC Temporary;
+ LVM_INT16 i;
+ LVM_UINT16 MaxBlockSize;
+
+
+ /*
+ * Check for error conditions
+ */
+ /* Check for NULL pointer */
+ if (pMemoryTable == LVM_NULL)
+ {
+ return(LVREV_NULLADDRESS);
+ }
+
+ /*
+ * Check all instance parameters are in range
+ */
+ if (pInstanceParams != LVM_NULL)
+ {
+ /*
+ * Call for memory allocation, so check the parameters
+ */
+ /* Check for a non-zero block size */
+ if (pInstanceParams->MaxBlockSize == 0)
+ {
+ return LVREV_OUTOFRANGE;
+ }
+
+ /* Check for a valid number of delay lines */
+ if ((pInstanceParams->NumDelays != LVREV_DELAYLINES_1) &&
+ (pInstanceParams->NumDelays != LVREV_DELAYLINES_2) &&
+ (pInstanceParams->NumDelays != LVREV_DELAYLINES_4))
+ {
+ return LVREV_OUTOFRANGE;
+ }
+ }
+
+ /*
+ * Initialise the InstAlloc instances
+ */
+ InstAlloc_Init(&SlowData, (void *)LVM_NULL);
+ InstAlloc_Init(&FastData, (void *)LVM_NULL);
+ InstAlloc_Init(&FastCoef, (void *)LVM_NULL);
+ InstAlloc_Init(&Temporary, (void *)LVM_NULL);
+
+
+ /*
+ * Fill in the memory table
+ */
+ if (hInstance == LVM_NULL)
+ {
+ /*
+ * Check for null pointers
+ */
+ if (pInstanceParams == LVM_NULL)
+ {
+ return(LVREV_NULLADDRESS);
+ }
+
+
+ /*
+ * Select the maximum internal block size
+ */
+ if(pInstanceParams->NumDelays ==LVREV_DELAYLINES_4)
+ {
+ MaxBlockSize = LVREV_MAX_AP3_DELAY;
+ }
+ else if(pInstanceParams->NumDelays ==LVREV_DELAYLINES_2)
+ {
+ MaxBlockSize = LVREV_MAX_AP1_DELAY;
+ }
+ else
+ {
+ MaxBlockSize = LVREV_MAX_AP0_DELAY;
+ }
+
+ if(MaxBlockSize>pInstanceParams->MaxBlockSize)
+ {
+ MaxBlockSize=pInstanceParams->MaxBlockSize;
+ }
+
+
+ /*
+ * Slow data memory
+ */
+ InstAlloc_AddMember(&SlowData, sizeof(LVREV_Instance_st));
+ pMemoryTable->Region[LVM_PERSISTENT_SLOW_DATA].Size = InstAlloc_GetTotal(&SlowData);
+ pMemoryTable->Region[LVM_PERSISTENT_SLOW_DATA].Type = LVM_PERSISTENT_SLOW_DATA;
+ pMemoryTable->Region[LVM_PERSISTENT_SLOW_DATA].pBaseAddress = LVM_NULL;
+
+
+ /*
+ * Persistent fast data memory
+ */
+ InstAlloc_AddMember(&FastData, sizeof(LVREV_FastData_st));
+ if(pInstanceParams->NumDelays == LVREV_DELAYLINES_4)
+ {
+ InstAlloc_AddMember(&FastData, LVREV_MAX_T3_DELAY * sizeof(LVM_INT32));
+ InstAlloc_AddMember(&FastData, LVREV_MAX_T2_DELAY * sizeof(LVM_INT32));
+ InstAlloc_AddMember(&FastData, LVREV_MAX_T1_DELAY * sizeof(LVM_INT32));
+ InstAlloc_AddMember(&FastData, LVREV_MAX_T0_DELAY * sizeof(LVM_INT32));
+ }
+
+ if(pInstanceParams->NumDelays == LVREV_DELAYLINES_2)
+ {
+ InstAlloc_AddMember(&FastData, LVREV_MAX_T1_DELAY * sizeof(LVM_INT32));
+ InstAlloc_AddMember(&FastData, LVREV_MAX_T0_DELAY * sizeof(LVM_INT32));
+ }
+
+ if(pInstanceParams->NumDelays == LVREV_DELAYLINES_1)
+ {
+ InstAlloc_AddMember(&FastData, LVREV_MAX_T0_DELAY * sizeof(LVM_INT32));
+ }
+
+ pMemoryTable->Region[LVM_PERSISTENT_FAST_DATA].Size = InstAlloc_GetTotal(&FastData);
+ pMemoryTable->Region[LVM_PERSISTENT_FAST_DATA].Type = LVM_PERSISTENT_FAST_DATA;
+ pMemoryTable->Region[LVM_PERSISTENT_FAST_DATA].pBaseAddress = LVM_NULL;
+
+
+ /*
+ * Persistent fast coefficient memory
+ */
+ InstAlloc_AddMember(&FastCoef, sizeof(LVREV_FastCoef_st));
+ pMemoryTable->Region[LVM_PERSISTENT_FAST_COEF].Size = InstAlloc_GetTotal(&FastCoef);
+ pMemoryTable->Region[LVM_PERSISTENT_FAST_COEF].Type = LVM_PERSISTENT_FAST_COEF;
+ pMemoryTable->Region[LVM_PERSISTENT_FAST_COEF].pBaseAddress = LVM_NULL;
+
+
+ /*
+ * Temporary fast memory
+ */
+ InstAlloc_AddMember(&Temporary, sizeof(LVM_INT32) * MaxBlockSize); /* General purpose scratch memory */
+ InstAlloc_AddMember(&Temporary, 2*sizeof(LVM_INT32) * MaxBlockSize); /* Mono->stereo input saved for end mix */
+
+ if(pInstanceParams->NumDelays == LVREV_DELAYLINES_4)
+ {
+ for(i=0; i<4; i++)
+ {
+ InstAlloc_AddMember(&Temporary, sizeof(LVM_INT32) * MaxBlockSize); /* A Scratch buffer for each delay line */
+ }
+ }
+
+ if(pInstanceParams->NumDelays == LVREV_DELAYLINES_2)
+ {
+ for(i=0; i<2; i++)
+ {
+ InstAlloc_AddMember(&Temporary, sizeof(LVM_INT32) * MaxBlockSize); /* A Scratch buffer for each delay line */
+ }
+ }
+
+ if(pInstanceParams->NumDelays == LVREV_DELAYLINES_1)
+ {
+ for(i=0; i<1; i++)
+ {
+ InstAlloc_AddMember(&Temporary, sizeof(LVM_INT32) * MaxBlockSize); /* A Scratch buffer for each delay line */
+ }
+ }
+
+ pMemoryTable->Region[LVM_TEMPORARY_FAST].Size = InstAlloc_GetTotal(&Temporary);
+ pMemoryTable->Region[LVM_TEMPORARY_FAST].Type = LVM_TEMPORARY_FAST;
+ pMemoryTable->Region[LVM_TEMPORARY_FAST].pBaseAddress = LVM_NULL;
+
+ }
+ else
+ {
+ LVREV_Instance_st *pLVREV_Private = (LVREV_Instance_st *)hInstance;
+
+
+ /*
+ * Read back memory allocation table
+ */
+ *pMemoryTable = pLVREV_Private->MemoryTable;
+ }
+
+
+ return(LVREV_SUCCESS);
+}
+
+/* End of file */
diff --git a/media/libeffects/lvm/lib/Reverb/src/LVREV_Private.h b/media/libeffects/lvm/lib/Reverb/src/LVREV_Private.h
new file mode 100755
index 0000000..896b051
--- /dev/null
+++ b/media/libeffects/lvm/lib/Reverb/src/LVREV_Private.h
@@ -0,0 +1,198 @@
+/*
+ * Copyright (C) 2004-2010 NXP Software
+ * Copyright (C) 2010 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.
+ */
+
+/****************************************************************************************/
+/* */
+/* Project:: */
+/* $Author: nxp007753 $ */
+/* $Revision: 1316 $ */
+/* $Date: 2010-07-23 11:53:24 +0200 (Fri, 23 Jul 2010) $ */
+/* */
+/****************************************************************************************/
+
+#ifndef __LVREV_PRIVATE_H__
+#define __LVREV_PRIVATE_H__
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+
+/****************************************************************************************/
+/* */
+/* Includes */
+/* */
+/****************************************************************************************/
+#include "LVREV.h"
+#include "LVREV_Tables.h"
+#include "BIQUAD.h"
+#include "Filter.h"
+#include "VectorArithmetic.h"
+#include "Mixer.h"
+#include "LVM_Macros.h"
+
+
+/****************************************************************************************/
+/* */
+/* Defines */
+/* */
+/****************************************************************************************/
+/* General */
+#define ONE_OVER_SQRT_TWO 23170 /* 1/sqrt(2) * 2^15 */
+#define LVREV_B_8_on_1000 17179869 /* 0.8 * 2^31 */
+#define LVREV_HEADROOM 8192 /* -12dB * 2^15 */
+#define LVREV_2_9_INQ29 1583769190L /* 2.9 in Q29 format */
+#define LVREV_MIN3DB 0x5A82 /* -3dB in Q15 format */
+
+/* Intenal constants */
+#define LVREV_LP_Poly_Order 4
+#define LVREV_LP_Poly_Shift 5
+#define LVREV_T_3_Power_0_on_4 32768
+#define LVREV_T_3_Power_1_on_4 43125
+#define LVREV_T_3_Power_2_on_4 56755
+#define LVREV_T_3_Power_3_on_4 74694
+#define LVREV_T60_SCALE 306774 /*(32767/7000)<<16 */
+#define LVREV_T_3_Power_minus0_on_4 32767 /* 3^(-0/4) * 2^15 */
+#define LVREV_T_3_Power_minus1_on_4 24898 /* 3^(-1/4) * 2^15 */
+#define LVREV_T_3_Power_minus2_on_4 18919 /* 3^(-2/4) * 2^15 */
+#define LVREV_T_3_Power_minus3_on_4 14375 /* 3^(-3/4) * 2^15 */
+#define LVREV_MAX_T3_DELAY 2527 /* ((48000 * 120 * LVREV_T_3_Power_minus3_on_4) >> 15) / 1000 */
+#define LVREV_MAX_T2_DELAY 3326 /* ((48000 * 120 * LVREV_T_3_Power_minus2_on_4) >> 15) / 1000 */
+#define LVREV_MAX_T1_DELAY 4377 /* ((48000 * 120 * LVREV_T_3_Power_minus1_on_4) >> 15) / 1000 */
+#define LVREV_MAX_T0_DELAY 5760 /* ((48000 * 120 * LVREV_T_3_Power_minus0_on_4) >> 15) / 1000 */
+#define LVREV_MAX_AP3_DELAY 1685 /* ((48000 * 120 * LVREV_T_3_Power_minus3_on_4) >> 15) / 1500 */
+#define LVREV_MAX_AP2_DELAY 2218 /* ((48000 * 120 * LVREV_T_3_Power_minus2_on_4) >> 15) / 1500 */
+#define LVREV_MAX_AP1_DELAY 2918 /* ((48000 * 120 * LVREV_T_3_Power_minus1_on_4) >> 15) / 1500 */
+#define LVREV_MAX_AP0_DELAY 3840 /* ((48000 * 120 * LVREV_T_3_Power_minus0_on_4) >> 15) / 1500 */
+#define LVREV_BYPASSMIXER_TC 1000 /* Bypass mixer time constant*/
+#define LVREV_ALLPASS_TC 1000 /* All-pass filter time constant */
+#define LVREV_ALLPASS_TAP_TC 10000 /* All-pass filter dely tap change */
+#define LVREV_FEEDBACKMIXER_TC 100 /* Feedback mixer time constant*/
+#define LVREV_OUTPUTGAIN_SHIFT 5 /* Bits shift for output gain correction */
+
+/* Parameter limits */
+#define LVREV_NUM_FS 9 /* Number of supported sample rates */
+#define LVREV_MAXBLKSIZE_LIMIT 64 /* Maximum block size low limit */
+#define LVREV_MAX_LEVEL 100 /* Maximum level, 100% */
+#define LVREV_MIN_LPF_CORNER 50 /* Low pass filter limits */
+#define LVREV_MAX_LPF_CORNER 23999
+#define LVREV_MIN_HPF_CORNER 20 /* High pass filrer limits */
+#define LVREV_MAX_HPF_CORNER 1000
+#define LVREV_MAX_T60 7000 /* Maximum T60 time in ms */
+#define LVREV_MAX_DENSITY 100 /* Maximum density, 100% */
+#define LVREV_MAX_DAMPING 100 /* Maximum damping, 100% */
+#define LVREV_MAX_ROOMSIZE 100 /* Maximum room size, 100% */
+
+
+
+/****************************************************************************************/
+/* */
+/* Structures */
+/* */
+/****************************************************************************************/
+/* Fast data structure */
+typedef struct
+{
+
+ Biquad_1I_Order1_Taps_t HPTaps; /* High pass filter taps */
+ Biquad_1I_Order1_Taps_t LPTaps; /* Low pass filter taps */
+ Biquad_1I_Order1_Taps_t RevLPTaps[4]; /* Reverb low pass filters taps */
+
+} LVREV_FastData_st;
+
+
+/* Fast coefficient structure */
+typedef struct
+{
+
+ Biquad_Instance_t HPCoefs; /* High pass filter coefficients */
+ Biquad_Instance_t LPCoefs; /* Low pass filter coefficients */
+ Biquad_Instance_t RevLPCoefs[4]; /* Reverb low pass filters coefficients */
+
+} LVREV_FastCoef_st;
+
+
+/* Instance parameter structure */
+typedef struct
+{
+ /* General */
+ LVREV_InstanceParams_st InstanceParams; /* Initialisation time instance parameters */
+ LVREV_MemoryTable_st MemoryTable; /* Memory table */
+ LVREV_ControlParams_st CurrentParams; /* Parameters being used */
+ LVREV_ControlParams_st NewParams; /* New parameters from the calling application */
+ LVM_CHAR bControlPending; /* Flag to indicate new parameters are available */
+ LVM_CHAR bFirstControl; /* Flag to indicate that the control function is called for the first time */
+ LVM_CHAR bDisableReverb; /* Flag to indicate that the mix level is 0% and the reverb can be disabled */
+ LVM_INT32 RoomSizeInms; /* Room size in msec */
+ LVM_INT32 MaxBlkLen; /* Maximum block size for internal processing */
+
+ /* Aligned memory pointers */
+ LVREV_FastData_st *pFastData; /* Fast data memory base address */
+ LVREV_FastCoef_st *pFastCoef; /* Fast coefficient memory base address */
+ LVM_INT32 *pScratchDelayLine[4]; /* Delay line scratch memory */
+ LVM_INT32 *pScratch; /* Multi ussge scratch */
+ LVM_INT32 *pInputSave; /* Reverb block input save for dry/wet mixing*/
+
+ /* Feedback matrix */
+ Mix_1St_Cll_t FeedbackMixer[4]; /* Mixer for Pop and Click Supression caused by feedback Gain */
+
+ /* All-Pass Filter */
+ LVM_INT32 T[4]; /* Maximum delay size of buffer */
+ LVM_INT32 *pDelay_T[4]; /* Pointer to delay buffers */
+ LVM_INT32 Delay_AP[4]; /* Offset to AP delay buffer start */
+ LVM_INT16 AB_Selection; /* Smooth from tap A to B when 1 otherwise B to A */
+ LVM_INT32 A_DelaySize[4]; /* A delay length in samples */
+ LVM_INT32 B_DelaySize[4]; /* B delay length in samples */
+ LVM_INT32 *pOffsetA[4]; /* Offset for the A delay tap */
+ LVM_INT32 *pOffsetB[4]; /* Offset for the B delay tap */
+ Mix_2St_Cll_t Mixer_APTaps[4]; /* Smoothed AP delay mixer */
+ Mix_1St_Cll_t Mixer_SGFeedback[4]; /* Smoothed SAfeedback gain */
+ Mix_1St_Cll_t Mixer_SGFeedforward[4]; /* Smoothed AP feedforward gain */
+
+ /* Output gain */
+ Mix_2St_Cll_t BypassMixer; /* Dry/wet mixer */
+ LVM_INT16 Gain; /* Gain applied to output to maintain average signal power */
+ Mix_1St_Cll_t GainMixer; /* Gain smoothing */
+
+} LVREV_Instance_st;
+
+
+/****************************************************************************************/
+/* */
+/* Function prototypes */
+/* */
+/****************************************************************************************/
+
+LVREV_ReturnStatus_en LVREV_ApplyNewSettings(LVREV_Instance_st *pPrivate);
+
+void ReverbBlock(LVM_INT32 *pInput,
+ LVM_INT32 *pOutput,
+ LVREV_Instance_st *pPrivate,
+ LVM_UINT16 NumSamples);
+
+LVM_INT32 BypassMixer_Callback(void *pCallbackData,
+ void *pGeneralPurpose,
+ LVM_INT16 GeneralPurpose );
+
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif /** __LVREV_PRIVATE_H__ **/
+
+/* End of file */
diff --git a/media/libeffects/lvm/lib/Reverb/src/LVREV_Process.c b/media/libeffects/lvm/lib/Reverb/src/LVREV_Process.c
new file mode 100755
index 0000000..822ac8f
--- /dev/null
+++ b/media/libeffects/lvm/lib/Reverb/src/LVREV_Process.c
@@ -0,0 +1,550 @@
+/*
+ * Copyright (C) 2004-2010 NXP Software
+ * Copyright (C) 2010 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.
+ */
+
+/****************************************************************************************/
+/* */
+/* Project:: */
+/* $Author: nxp007753 $ */
+/* $Revision: 1316 $ */
+/* $Date: 2010-07-23 11:53:24 +0200 (Fri, 23 Jul 2010) $ */
+/* */
+/****************************************************************************************/
+
+/****************************************************************************************/
+/* */
+/* Includes */
+/* */
+/****************************************************************************************/
+#include "LVREV_Private.h"
+#include "VectorArithmetic.h"
+
+
+/****************************************************************************************/
+/* */
+/* FUNCTION: LVREV_Process */
+/* */
+/* DESCRIPTION: */
+/* Process function for the LVREV module. */
+/* */
+/* PARAMETERS: */
+/* hInstance Instance handle */
+/* pInData Pointer to the input data */
+/* pOutData Pointer to the output data */
+/* NumSamples Number of samples in the input buffer */
+/* */
+/* RETURNS: */
+/* LVREV_Success Succeeded */
+/* LVREV_INVALIDNUMSAMPLES NumSamples was larger than the maximum block size */
+/* LVREV_NULLADDRESS When one of hInstance, pInData or pOutData is NULL */
+/* */
+/* NOTES: */
+/* 1. The input and output buffers must be 32-bit aligned */
+/* */
+/****************************************************************************************/
+LVREV_ReturnStatus_en LVREV_Process(LVREV_Handle_t hInstance,
+ const LVM_INT32 *pInData,
+ LVM_INT32 *pOutData,
+ const LVM_UINT16 NumSamples)
+{
+ LVREV_Instance_st *pLVREV_Private = (LVREV_Instance_st *)hInstance;
+ LVM_INT32 *pInput = (LVM_INT32 *)pInData;
+ LVM_INT32 *pOutput = pOutData;
+ LVM_INT32 SamplesToProcess, RemainingSamples, format;
+
+ /*
+ * Check for error conditions
+ */
+
+ /* Check for NULL pointers */
+ if((hInstance == LVM_NULL) || (pInData == LVM_NULL) || (pOutData == LVM_NULL))
+ {
+ return LVREV_NULLADDRESS;
+ }
+
+
+ /*
+ * Apply the new controls settings if required
+ */
+ if(pLVREV_Private->bControlPending == LVM_TRUE)
+ {
+ LVREV_ReturnStatus_en errorCode;
+
+ /*
+ * Clear the pending flag and update the control settings
+ */
+ pLVREV_Private->bControlPending = LVM_FALSE;
+
+ errorCode = LVREV_ApplyNewSettings (pLVREV_Private);
+
+ if(errorCode != LVREV_SUCCESS)
+ {
+ return errorCode;
+ }
+ }
+
+ /*
+ * Trap the case where the number of samples is zero.
+ */
+ if (NumSamples == 0)
+ {
+ return LVREV_SUCCESS;
+ }
+
+ RemainingSamples = (LVM_INT32)NumSamples;
+
+ format = 1;
+ if (pLVREV_Private->CurrentParams.SourceFormat != LVM_MONO)
+ {
+ format = 2;
+ }
+
+ while (RemainingSamples!=0)
+ {
+ /*
+ * If OFF copy and reformat the data as necessary
+ */
+ if (pLVREV_Private->CurrentParams.OperatingMode == LVM_MODE_OFF)
+ {
+ if((pInput != pOutput) || (pLVREV_Private->CurrentParams.SourceFormat == LVM_MONO))
+ {
+ /*
+ * Copy the data to the output buffer
+ */
+
+ if (pLVREV_Private->CurrentParams.SourceFormat != LVM_MONO)
+ {
+ RemainingSamples = (RemainingSamples << 1); /* Stereo data */
+ }
+
+ Copy_16((LVM_INT16 *)pInput,
+ (LVM_INT16 *)pOutput,
+ (LVM_INT16)(RemainingSamples << 1));
+ }
+
+ RemainingSamples = 0;
+ }
+
+ /*
+ * Process the data
+ */
+ else
+ {
+
+ if(RemainingSamples > pLVREV_Private->MaxBlkLen)
+ {
+ SamplesToProcess = pLVREV_Private->MaxBlkLen;
+ RemainingSamples = (LVM_INT16)(RemainingSamples - SamplesToProcess);
+ }
+ else
+ {
+ SamplesToProcess = RemainingSamples;
+ RemainingSamples = 0;
+ }
+
+ ReverbBlock(pInput, pOutput, pLVREV_Private, (LVM_UINT16)SamplesToProcess);
+
+ pInput = (LVM_INT32 *)(pInput +(SamplesToProcess*format));
+ pOutput = (LVM_INT32 *)(pOutput+(SamplesToProcess*format));
+ }
+ }
+
+ return LVREV_SUCCESS;
+}
+
+
+
+/****************************************************************************************/
+/* */
+/* FUNCTION: ReverbBlock */
+/* */
+/* DESCRIPTION: */
+/* Process function for the LVREV module. */
+/* */
+/* PARAMETERS: */
+/* hInstance Instance handle */
+/* pInData Pointer to the input data */
+/* pOutData Pointer to the output data */
+/* NumSamples Number of samples in the input buffer */
+/* */
+/* RETURNS: */
+/* LVREV_Success Succeeded */
+/* LVREV_INVALIDNUMSAMPLES NumSamples was larger than the maximum block size */
+/* LVREV_NULLADDRESS When one of hInstance, pInData or pOutData is NULL */
+/* */
+/* NOTES: */
+/* 1. The input and output buffers must be 32-bit aligned */
+/* */
+/****************************************************************************************/
+
+void ReverbBlock(LVM_INT32 *pInput, LVM_INT32 *pOutput, LVREV_Instance_st *pPrivate, LVM_UINT16 NumSamples)
+{
+ LVM_INT16 j, size;
+ LVM_INT32 *pDelayLine;
+ LVM_INT32 *pDelayLineInput = pPrivate->pScratch;
+ LVM_INT32 *pScratch = pPrivate->pScratch;
+ LVM_INT32 *pIn;
+ LVM_INT32 *pTemp = pPrivate->pInputSave;
+ LVM_INT32 NumberOfDelayLines;
+
+ /******************************************************************************
+ * All calculations will go into the buffer pointed to by pTemp, this will *
+ * then be mixed with the original input to create the final output. *
+ * *
+ * When INPLACE processing is selected this must be a temporary buffer and *
+ * hence this is the worst case, so for simplicity this will ALWAYS be so *
+ * *
+ * The input buffer will remain untouched until the output of the mixer if *
+ * INPLACE processing is selected. *
+ * *
+ * The temp buffer will always be NumSamples in size regardless of MONO or *
+ * STEREO input. In the case of stereo input all processing is done in MONO *
+ * and the final output is converted to STEREO after the mixer *
+ ******************************************************************************/
+
+ if(pPrivate->InstanceParams.NumDelays == LVREV_DELAYLINES_4 )
+ {
+ NumberOfDelayLines = 4;
+ }
+ else if(pPrivate->InstanceParams.NumDelays == LVREV_DELAYLINES_2 )
+ {
+ NumberOfDelayLines = 2;
+ }
+ else
+ {
+ NumberOfDelayLines = 1;
+ }
+
+ if(pPrivate->CurrentParams.SourceFormat == LVM_MONO)
+ {
+ pIn = pInput;
+ }
+ else
+ {
+ /*
+ * Stereo to mono conversion
+ */
+
+ From2iToMono_32( pInput,
+ pTemp,
+ (LVM_INT16)NumSamples);
+
+ pIn = pTemp;
+ }
+
+ Mult3s_32x16(pIn,
+ (LVM_INT16)LVREV_HEADROOM,
+ pTemp,
+ (LVM_INT16)NumSamples);
+
+ /*
+ * High pass filter
+ */
+ FO_1I_D32F32C31_TRC_WRA_01( &pPrivate->pFastCoef->HPCoefs,
+ pTemp,
+ pTemp,
+ (LVM_INT16)NumSamples);
+ /*
+ * Low pass filter
+ */
+ FO_1I_D32F32C31_TRC_WRA_01( &pPrivate->pFastCoef->LPCoefs,
+ pTemp,
+ pTemp,
+ (LVM_INT16)NumSamples);
+
+ /*
+ * Process all delay lines
+ */
+
+ for(j = 0; j < NumberOfDelayLines; j++)
+ {
+ pDelayLine = pPrivate->pScratchDelayLine[j];
+
+ /*
+ * All-pass filter with pop and click suppression
+ */
+ /* Get the smoothed, delayed output. Put it in the output buffer */
+ MixSoft_2St_D32C31_SAT(&pPrivate->Mixer_APTaps[j],
+ pPrivate->pOffsetA[j],
+ pPrivate->pOffsetB[j],
+ pDelayLine,
+ (LVM_INT16)NumSamples);
+ /* Re-align the all pass filter delay buffer and copying the fixed delay data to the AP delay in the process */
+ Copy_16((LVM_INT16 *)&pPrivate->pDelay_T[j][NumSamples],
+ (LVM_INT16 *)pPrivate->pDelay_T[j],
+ (LVM_INT16)((pPrivate->T[j]-NumSamples) << 1)); /* 32-bit data */
+ /* Apply the smoothed feedback and save to fixed delay input (currently empty) */
+ MixSoft_1St_D32C31_WRA(&pPrivate->Mixer_SGFeedback[j],
+ pDelayLine,
+ &pPrivate->pDelay_T[j][pPrivate->T[j]-NumSamples],
+ (LVM_INT16)NumSamples);
+ /* Sum into the AP delay line */
+ Mac3s_Sat_32x16(&pPrivate->pDelay_T[j][pPrivate->T[j]-NumSamples],
+ -0x7fff, /* Invert since the feedback coefficient is negative */
+ &pPrivate->pDelay_T[j][pPrivate->Delay_AP[j]-NumSamples],
+ (LVM_INT16)NumSamples);
+ /* Apply smoothed feedforward sand save to fixed delay input (currently empty) */
+ MixSoft_1St_D32C31_WRA(&pPrivate->Mixer_SGFeedforward[j],
+ &pPrivate->pDelay_T[j][pPrivate->Delay_AP[j]-NumSamples],
+ &pPrivate->pDelay_T[j][pPrivate->T[j]-NumSamples],
+ (LVM_INT16)NumSamples);
+ /* Sum into the AP output */
+ Mac3s_Sat_32x16(&pPrivate->pDelay_T[j][pPrivate->T[j]-NumSamples],
+ 0x7fff,
+ pDelayLine,
+ (LVM_INT16)NumSamples);
+
+ /*
+ * Feedback gain
+ */
+ MixSoft_1St_D32C31_WRA(&pPrivate->FeedbackMixer[j], pDelayLine, pDelayLine, NumSamples);
+
+ /*
+ * Low pass filter
+ */
+ FO_1I_D32F32C31_TRC_WRA_01( &pPrivate->pFastCoef->RevLPCoefs[j],
+ pDelayLine,
+ pDelayLine,
+ (LVM_INT16)NumSamples);
+ }
+
+ /*
+ * Apply rotation matrix and delay samples
+ */
+ for(j = 0; j < NumberOfDelayLines; j++)
+ {
+
+ Copy_16( (LVM_INT16*)(pTemp),
+ (LVM_INT16*)(pDelayLineInput),
+ (LVM_INT16)(NumSamples << 1));
+
+ /*
+ * Rotation matrix mix
+ */
+ switch(j)
+ {
+ case 3:
+ /*
+ * Add delay line 1 and 2 contribution
+ */
+ Mac3s_Sat_32x16(pPrivate->pScratchDelayLine[1], -0x8000, pDelayLineInput, (LVM_INT16)NumSamples);
+ Mac3s_Sat_32x16(pPrivate->pScratchDelayLine[2], -0x8000, pDelayLineInput, (LVM_INT16)NumSamples);
+
+ break;
+ case 2:
+
+ /*
+ * Add delay line 0 and 3 contribution
+ */
+ Mac3s_Sat_32x16(pPrivate->pScratchDelayLine[0], -0x8000, pDelayLineInput, (LVM_INT16)NumSamples);
+ Mac3s_Sat_32x16(pPrivate->pScratchDelayLine[3], -0x8000, pDelayLineInput, (LVM_INT16)NumSamples);
+
+ break;
+ case 1:
+ if(pPrivate->InstanceParams.NumDelays == LVREV_DELAYLINES_4)
+ {
+ /*
+ * Add delay line 0 and 3 contribution
+ */
+ Mac3s_Sat_32x16(pPrivate->pScratchDelayLine[0], -0x8000, pDelayLineInput, (LVM_INT16)NumSamples);
+ Add2_Sat_32x32(pPrivate->pScratchDelayLine[3], pDelayLineInput, (LVM_INT16)NumSamples);
+
+ }
+ else
+ {
+ /*
+ * Add delay line 0 and 1 contribution
+ */
+ Mac3s_Sat_32x16(pPrivate->pScratchDelayLine[0], -0x8000, pDelayLineInput, (LVM_INT16)NumSamples);
+ Mac3s_Sat_32x16(pPrivate->pScratchDelayLine[1], -0x8000, pDelayLineInput, (LVM_INT16)NumSamples);
+
+ }
+ break;
+ case 0:
+ if(pPrivate->InstanceParams.NumDelays == LVREV_DELAYLINES_4)
+ {
+ /*
+ * Add delay line 1 and 2 contribution
+ */
+ Mac3s_Sat_32x16(pPrivate->pScratchDelayLine[1], -0x8000, pDelayLineInput, (LVM_INT16)NumSamples);
+ Add2_Sat_32x32(pPrivate->pScratchDelayLine[2], pDelayLineInput, (LVM_INT16)NumSamples);
+
+ }
+ else if(pPrivate->InstanceParams.NumDelays == LVREV_DELAYLINES_2)
+ {
+ /*
+ * Add delay line 0 and 1 contribution
+ */
+ Add2_Sat_32x32(pPrivate->pScratchDelayLine[0], pDelayLineInput, (LVM_INT16)NumSamples);
+ Mac3s_Sat_32x16(pPrivate->pScratchDelayLine[1], -0x8000, pDelayLineInput, (LVM_INT16)NumSamples);
+
+ }
+ else
+ {
+ /*
+ * Add delay line 0 contribution
+ */
+
+ /* SOURCE DESTINATION*/
+ Add2_Sat_32x32(pPrivate->pScratchDelayLine[0], pDelayLineInput, (LVM_INT16)NumSamples);
+ }
+ break;
+ default:
+ break;
+ }
+
+ /*
+ * Delay samples
+ */
+ Copy_16((LVM_INT16 *)pDelayLineInput,
+ (LVM_INT16 *)&pPrivate->pDelay_T[j][pPrivate->T[j]-NumSamples],
+ (LVM_INT16)(NumSamples << 1)); /* 32-bit data */
+
+ }
+
+
+ /*
+ * Create stereo output
+ */
+ switch(pPrivate->InstanceParams.NumDelays)
+ {
+ case LVREV_DELAYLINES_4:
+ Add2_Sat_32x32(pPrivate->pScratchDelayLine[3],
+ pPrivate->pScratchDelayLine[0],
+ (LVM_INT16)NumSamples);
+ Add2_Sat_32x32(pPrivate->pScratchDelayLine[2],
+ pPrivate->pScratchDelayLine[1],
+ (LVM_INT16)NumSamples);
+
+ if(pPrivate->CurrentParams.SourceFormat != LVM_MONO)
+ {
+ JoinTo2i_32x32(pPrivate->pScratchDelayLine[0],
+ pPrivate->pScratchDelayLine[1],
+ pTemp,
+ (LVM_INT16)NumSamples);
+
+ }
+ else
+ {
+ Add2_Sat_32x32(pPrivate->pScratchDelayLine[1],
+ pPrivate->pScratchDelayLine[0],
+ (LVM_INT16)NumSamples);
+
+ /*Apply 3-dB gain in-order to compensate for the gain change in stereo mode*/
+ Mult3s_32x16(pPrivate->pScratchDelayLine[0],
+ LVREV_MIN3DB,
+ pTemp,
+ (LVM_INT16)NumSamples);
+ }
+ break;
+ case LVREV_DELAYLINES_2:
+
+ Copy_16( (LVM_INT16*)pPrivate->pScratchDelayLine[1],
+ (LVM_INT16*)pScratch,
+ (LVM_INT16)(NumSamples << 1));
+
+
+
+ if(pPrivate->CurrentParams.SourceFormat != LVM_MONO)
+ {
+
+ Mac3s_Sat_32x16(pPrivate->pScratchDelayLine[0],
+ -0x8000,
+ pScratch,
+ (LVM_INT16)NumSamples);
+ }
+
+ Add2_Sat_32x32(pPrivate->pScratchDelayLine[1],
+ pPrivate->pScratchDelayLine[0],
+ (LVM_INT16)NumSamples);
+
+
+ if(pPrivate->CurrentParams.SourceFormat != LVM_MONO)
+ {
+ JoinTo2i_32x32(pPrivate->pScratchDelayLine[0],
+ pScratch,
+ pTemp,
+ (LVM_INT16)NumSamples);
+ }
+ else
+ {
+ Copy_16( (LVM_INT16*)pPrivate->pScratchDelayLine[0],
+ (LVM_INT16*)pTemp,
+ (LVM_INT16)(NumSamples << 1));
+
+ }
+ break;
+ case LVREV_DELAYLINES_1:
+ if(pPrivate->CurrentParams.SourceFormat != LVM_MONO)
+ {
+
+ MonoTo2I_32(pPrivate->pScratchDelayLine[0],
+ pTemp,
+ (LVM_INT16)NumSamples);
+ }
+ else
+ {
+ pTemp = pPrivate->pScratchDelayLine[0];
+ }
+ break;
+ default:
+ break;
+ }
+
+
+ /*
+ * Dry/wet mixer
+ */
+ if(pPrivate->CurrentParams.SourceFormat != LVM_MONO)
+ {
+ size = (LVM_INT16)(NumSamples << 1);
+ }
+ else
+ {
+ size = (LVM_INT16)NumSamples;
+ }
+
+ MixSoft_2St_D32C31_SAT(&pPrivate->BypassMixer,
+ pInput,
+ pTemp,
+ pOutput,
+ size);
+
+ /* Apply Gain*/
+ if(pPrivate->CurrentParams.SourceFormat != LVM_MONO)
+ {
+ size = (LVM_INT16)(NumSamples << 1);
+ }
+ else
+ {
+ size = (LVM_INT16)NumSamples;
+ }
+
+ Shift_Sat_v32xv32 (LVREV_OUTPUTGAIN_SHIFT,
+ pOutput,
+ pOutput,
+ size);
+
+ MixSoft_1St_D32C31_WRA(&pPrivate->GainMixer,
+ pOutput,
+ pOutput,
+ size);
+ return;
+}
+
+
+/* End of file */
+
diff --git a/media/libeffects/lvm/lib/Reverb/src/LVREV_SetControlParameters.c b/media/libeffects/lvm/lib/Reverb/src/LVREV_SetControlParameters.c
new file mode 100755
index 0000000..124fd3b
--- /dev/null
+++ b/media/libeffects/lvm/lib/Reverb/src/LVREV_SetControlParameters.c
@@ -0,0 +1,128 @@
+/*
+ * Copyright (C) 2004-2010 NXP Software
+ * Copyright (C) 2010 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.
+ */
+
+/****************************************************************************************/
+/* */
+/* Project:: */
+/* $Author: nxp007753 $ */
+/* $Revision: 1316 $ */
+/* $Date: 2010-07-23 11:53:24 +0200 (Fri, 23 Jul 2010) $ */
+/* */
+/****************************************************************************************/
+
+/****************************************************************************************/
+/* */
+/* Includes */
+/* */
+/****************************************************************************************/
+#include "LVREV_Private.h"
+
+/****************************************************************************************/
+/* */
+/* FUNCTION: LVREV_SetControlParameters */
+/* */
+/* DESCRIPTION: */
+/* Sets or changes the LVREV module parameters. */
+/* */
+/* PARAMETERS: */
+/* hInstance Instance handle */
+/* pNewParams Pointer to a parameter structure */
+/* */
+/* RETURNS: */
+/* LVM_Success Succeeded */
+/* LVREV_NULLADDRESS When hInstance or pNewParams is NULL */
+/* LVREV_OUTOFRANGE When any of the new parameters is out of range */
+/* */
+/* NOTES: */
+/* 1. This function may be interrupted by the LVREV_Process function */
+/* */
+/****************************************************************************************/
+LVREV_ReturnStatus_en LVREV_SetControlParameters(LVREV_Handle_t hInstance,
+ LVREV_ControlParams_st *pNewParams)
+{
+
+ LVREV_Instance_st *pLVREV_Private = (LVREV_Instance_st *)hInstance;
+
+
+ /*
+ * Check for error conditions
+ */
+ if((hInstance == LVM_NULL) || (pNewParams == LVM_NULL))
+ {
+ return LVREV_NULLADDRESS;
+ }
+
+ /*
+ * Check all new control parameters are in range
+ */
+ if( ((pNewParams->OperatingMode != LVM_MODE_OFF) && (pNewParams->OperatingMode != LVM_MODE_ON)) ||
+ ((pNewParams->SampleRate != LVM_FS_8000) && (pNewParams->SampleRate != LVM_FS_11025) && (pNewParams->SampleRate != LVM_FS_12000) &&
+ (pNewParams->SampleRate != LVM_FS_16000) && (pNewParams->SampleRate != LVM_FS_22050) && (pNewParams->SampleRate != LVM_FS_24000) &&
+ (pNewParams->SampleRate != LVM_FS_32000) && (pNewParams->SampleRate != LVM_FS_44100) && (pNewParams->SampleRate != LVM_FS_48000)) ||
+ ((pNewParams->SourceFormat != LVM_STEREO) && (pNewParams->SourceFormat != LVM_MONOINSTEREO) && (pNewParams->SourceFormat != LVM_MONO)) )
+ {
+ return (LVREV_OUTOFRANGE);
+ }
+
+
+ if (pNewParams->Level > LVREV_MAX_LEVEL)
+ {
+ return LVREV_OUTOFRANGE;
+ }
+
+ if ((pNewParams->LPF < LVREV_MIN_LPF_CORNER) || (pNewParams->LPF > LVREV_MAX_LPF_CORNER))
+ {
+ return LVREV_OUTOFRANGE;
+ }
+
+ if ((pNewParams->HPF < LVREV_MIN_HPF_CORNER) || (pNewParams->HPF > LVREV_MAX_HPF_CORNER))
+ {
+ return LVREV_OUTOFRANGE;
+ }
+
+ if (pNewParams->T60 > LVREV_MAX_T60)
+ {
+ return LVREV_OUTOFRANGE;
+ }
+
+ if (pNewParams->Density > LVREV_MAX_DENSITY)
+ {
+ return LVREV_OUTOFRANGE;
+ }
+
+ if (pNewParams->Damping > LVREV_MAX_DAMPING)
+ {
+ return LVREV_OUTOFRANGE;
+ }
+
+ if (pNewParams->RoomSize > LVREV_MAX_ROOMSIZE)
+ {
+ return LVREV_OUTOFRANGE;
+ }
+
+
+
+ /*
+ * Copy the new parameters and set the flag to indicate they are available
+ */
+ pLVREV_Private->NewParams = *pNewParams;
+ pLVREV_Private->bControlPending = LVM_TRUE;
+
+ return LVREV_SUCCESS;
+}
+
+/* End of file */
diff --git a/media/libeffects/lvm/lib/Reverb/src/LVREV_Tables.c b/media/libeffects/lvm/lib/Reverb/src/LVREV_Tables.c
new file mode 100755
index 0000000..9249a31
--- /dev/null
+++ b/media/libeffects/lvm/lib/Reverb/src/LVREV_Tables.c
@@ -0,0 +1,108 @@
+/*
+ * Copyright (C) 2004-2010 NXP Software
+ * Copyright (C) 2010 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.
+ */
+
+/****************************************************************************************/
+/* */
+/* Project:: */
+/* $Author: beq07716 $ */
+/* $Revision: 1011 $ */
+/* $Date: 2010-06-28 15:07:08 +0200 (Mon, 28 Jun 2010) $ */
+/* */
+/****************************************************************************************/
+
+/****************************************************************************************/
+/* */
+/* Includes */
+/* */
+/****************************************************************************************/
+#include "LVREV.h"
+
+/****************************************************************************************/
+/* */
+/* Tables */
+/* */
+/****************************************************************************************/
+
+/* Table with supported sampling rates. The table can be indexed using LVM_Fs_en */
+const LVM_UINT16 LVM_FsTable[] = {
+ 8000 ,
+ 11025,
+ 12000,
+ 16000,
+ 22050,
+ 24000,
+ 32000,
+ 44100,
+ 48000
+};
+
+/* Table with supported sampling rates. The table can be indexed using LVM_Fs_en */
+LVM_UINT16 LVM_GetFsFromTable(LVM_Fs_en FsIndex){
+ if (FsIndex > LVM_FS_48000)
+ return 0;
+
+ return (LVM_FsTable[FsIndex]);
+}
+
+/* In order to maintain consistant input and out put signal strengths
+ output gain/attenuation is applied. This gain depends on T60 and Rooms
+ size parameters. These polynomial coefficients are calculated experimentally.
+ First value in the table is room size
+ second value is A0
+ third value is A1
+ fourth value is A2
+ fifth value is A3
+ sixth value is A4
+
+ shift value is to be added array (to use LVM_Polynomial function)
+
+ The gain is calculated using variable x=(T60*32767/7000)*32768;
+
+ first values is used to get polynomial set for given room size,
+ For room sizes which are not in the table, linear interpolation can be used.
+
+ */
+
+/* Normalizing output including Reverb Level part (only shift up)*/
+const LVM_INT32 LVREV_GainPolyTable[24][5]={{1,17547434,128867434,-120988896,50761228,},
+ {2,18256869,172666902,-193169292,88345744,},
+ {3,16591311,139250151,-149667234,66770059,},
+ {4,17379977,170835131,-173579321,76278163,},
+ {5,18963512,210364934,-228623519,103435022,},
+ {6,17796318,135756417,-144084053,64327698,},
+ {7,17454695,174593214,-187513064,85146582,},
+ {8,17229257,140715570,-145790588,65361740,},
+ {9,17000547,163195946,-176733969,79562130,},
+ {10,16711699,142476304,-133339887,58366547,},
+ {13,18108419,149223697,-161762020,74397589,},
+ {15,16682043,124844884,-134284487,60082180,},
+ {17,16627346,120936430,-121766674,53146421,},
+ {20,17338325,125432694,-126616983,56534237,},
+ {25,16489146,99218217,-94597467,40616506,},
+ {30,15582373,84479043,-75365006,30952348,},
+ {40,16000669,84896611,-75031127,30696306,},
+ {50,15087054,71695031,-59349268,23279669,},
+ {60,15830714,68672971,-58211201,23671158,},
+ {70,15536061,66657972,-55901437,22560153,},
+ {75,15013145,48179917,-24138354,5232074,},
+ {80,15688738,50195036,-34206760,11515792,},
+ {90,16003322,48323661,-35607378,13153872,},
+ {100,15955223,48558201,-33706865,11715792,},
+ };
+
+/* End of file */
+
diff --git a/media/libeffects/lvm/lib/Reverb/src/LVREV_Tables.h b/media/libeffects/lvm/lib/Reverb/src/LVREV_Tables.h
new file mode 100755
index 0000000..98471be
--- /dev/null
+++ b/media/libeffects/lvm/lib/Reverb/src/LVREV_Tables.h
@@ -0,0 +1,59 @@
+/*
+ * Copyright (C) 2004-2010 NXP Software
+ * Copyright (C) 2010 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.
+ */
+
+/****************************************************************************************/
+/* */
+/* Project:: */
+/* $Author: beq07716 $ */
+/* $Revision: 773 $ */
+/* $Date: 2010-06-14 10:43:54 +0200 (Mon, 14 Jun 2010) $ */
+/* */
+/****************************************************************************************/
+
+
+#ifndef _LVREV_TABLES_H_
+#define _LVREV_TABLES_H_
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+
+/****************************************************************************************/
+/* */
+/* Includes */
+/* */
+/****************************************************************************************/
+#include "LVREV_Private.h"
+
+/****************************************************************************************/
+/* */
+/* Definitions */
+/* */
+/****************************************************************************************/
+
+extern const LVM_UINT16 LVM_FsTable[];
+extern LVM_UINT16 LVM_GetFsFromTable(LVM_Fs_en FsIndex);
+extern LVM_INT32 LVREV_GainPolyTable[24][5];
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif /** _LVREV_TABLES_H_ **/
+
+/* End of file */
diff --git a/media/libeffects/lvm/lib/StereoWidening/src/LVCS_Control.c b/media/libeffects/lvm/lib/StereoWidening/src/LVCS_Control.c
index fea44bf..668b151 100755
--- a/media/libeffects/lvm/lib/StereoWidening/src/LVCS_Control.c
+++ b/media/libeffects/lvm/lib/StereoWidening/src/LVCS_Control.c
@@ -17,9 +17,9 @@
/************************************************************************************
- $Author: beq06068 $
- $Revision: 1307 $
- $Date: 2010-07-22 17:41:25 +0200 (Thu, 22 Jul 2010) $
+ $Author: nxp007753 $
+ $Revision: 1331 $
+ $Date: 2010-07-27 12:26:23 +0200 (Tue, 27 Jul 2010) $
*************************************************************************************/
diff --git a/media/libeffects/lvm/lib/StereoWidening/src/LVCS_Equaliser.c b/media/libeffects/lvm/lib/StereoWidening/src/LVCS_Equaliser.c
index 7ab6571..d8023d64 100755
--- a/media/libeffects/lvm/lib/StereoWidening/src/LVCS_Equaliser.c
+++ b/media/libeffects/lvm/lib/StereoWidening/src/LVCS_Equaliser.c
@@ -18,8 +18,8 @@
/************************************************************************************
$Author: nxp007753 $
- $Revision: 1315 $
- $Date: 2010-07-23 11:52:08 +0200 (Fri, 23 Jul 2010) $
+ $Revision: 1331 $
+ $Date: 2010-07-27 12:26:23 +0200 (Tue, 27 Jul 2010) $
*************************************************************************************/
diff --git a/media/libeffects/lvm/lib/StereoWidening/src/LVCS_Init.c b/media/libeffects/lvm/lib/StereoWidening/src/LVCS_Init.c
index f5f7cd0..82a8db2 100755
--- a/media/libeffects/lvm/lib/StereoWidening/src/LVCS_Init.c
+++ b/media/libeffects/lvm/lib/StereoWidening/src/LVCS_Init.c
@@ -17,9 +17,9 @@
/************************************************************************************
- $Author: beq06068 $
- $Revision: 1307 $
- $Date: 2010-07-22 17:41:25 +0200 (Thu, 22 Jul 2010) $
+ $Author: nxp007753 $
+ $Revision: 1331 $
+ $Date: 2010-07-27 12:26:23 +0200 (Tue, 27 Jul 2010) $
*************************************************************************************/
diff --git a/media/libeffects/lvm/lib/StereoWidening/src/LVCS_StereoEnhancer.c b/media/libeffects/lvm/lib/StereoWidening/src/LVCS_StereoEnhancer.c
index b67d824..83748e6 100755
--- a/media/libeffects/lvm/lib/StereoWidening/src/LVCS_StereoEnhancer.c
+++ b/media/libeffects/lvm/lib/StereoWidening/src/LVCS_StereoEnhancer.c
@@ -18,8 +18,8 @@
/************************************************************************************
$Author: nxp007753 $
- $Revision: 1315 $
- $Date: 2010-07-23 11:52:08 +0200 (Fri, 23 Jul 2010) $
+ $Revision: 1331 $
+ $Date: 2010-07-27 12:26:23 +0200 (Tue, 27 Jul 2010) $
*************************************************************************************/
diff --git a/media/libeffects/lvm/wrapper/Android.mk b/media/libeffects/lvm/wrapper/Android.mk
index 7855dcd..2e9b9b4 100644
--- a/media/libeffects/lvm/wrapper/Android.mk
+++ b/media/libeffects/lvm/wrapper/Android.mk
@@ -34,3 +34,36 @@
include $(BUILD_SHARED_LIBRARY)
+
+# reverb wrapper
+include $(CLEAR_VARS)
+
+LOCAL_ARM_MODE := arm
+
+LOCAL_SRC_FILES:= \
+ Reverb/EffectReverb.cpp
+
+LOCAL_MODULE:= libreverbwrapper
+
+LOCAL_MODULE_PATH := $(TARGET_OUT_SHARED_LIBRARIES)/soundfx
+
+LOCAL_PRELINK_MODULE := false
+
+LOCAL_STATIC_LIBRARIES += libreverb
+
+LOCAL_SHARED_LIBRARIES := \
+ libcutils \
+
+ifeq ($(TARGET_SIMULATOR),true)
+LOCAL_LDLIBS += -ldl
+else
+LOCAL_SHARED_LIBRARIES += libdl
+endif
+
+LOCAL_C_INCLUDES += \
+ $(LOCAL_PATH)/Reverb \
+ $(LOCAL_PATH)/../lib/Common/lib/ \
+ $(LOCAL_PATH)/../lib/Reverb/lib/ \
+
+
+include $(BUILD_SHARED_LIBRARY)
\ No newline at end of file
diff --git a/media/libeffects/lvm/wrapper/Bundle/EffectBundle.cpp b/media/libeffects/lvm/wrapper/Bundle/EffectBundle.cpp
index bcd646a..d856eb4 100644
--- a/media/libeffects/lvm/wrapper/Bundle/EffectBundle.cpp
+++ b/media/libeffects/lvm/wrapper/Bundle/EffectBundle.cpp
@@ -17,7 +17,7 @@
#define LOG_TAG "Bundle"
#define ARRAY_SIZE(array) (sizeof array / sizeof array[0])
-#define LOG_NDEBUG 0
+//#define LOG_NDEBUG 0
#include <cutils/log.h>
#include <assert.h>
@@ -66,7 +66,9 @@
// Flag to allow a one time init of global memory, only happens on first call ever
int LvmInitFlag = LVM_FALSE;
-SessionContext GlobalSessionMemory[32];
+int LvmSessionsActive = 0;
+SessionContext GlobalSessionMemory[LVM_MAX_SESSIONS];
+int SessionIndex[LVM_MAX_SESSIONS];
// NXP SW BassBoost UUID
const effect_descriptor_t gBassBoostDescriptor = {
@@ -125,24 +127,24 @@
int LvmEffect_disable (EffectContext *pContext);
void LvmEffect_free (EffectContext *pContext);
int Effect_configure (EffectContext *pContext, effect_config_t *pConfig);
-int BassBoost_setParameter (EffectContext *pContext, int32_t *pParam, void *pValue);
+int BassBoost_setParameter (EffectContext *pContext, void *pParam, void *pValue);
int BassBoost_getParameter (EffectContext *pContext,
- int32_t *pParam,
+ void *pParam,
size_t *pValueSize,
void *pValue);
-int Virtualizer_setParameter (EffectContext *pContext, int32_t *pParam, void *pValue);
+int Virtualizer_setParameter (EffectContext *pContext, void *pParam, void *pValue);
int Virtualizer_getParameter (EffectContext *pContext,
- int32_t *pParam,
+ void *pParam,
size_t *pValueSize,
void *pValue);
-int Equalizer_setParameter (EffectContext *pContext, int32_t *pParam, void *pValue);
+int Equalizer_setParameter (EffectContext *pContext, void *pParam, void *pValue);
int Equalizer_getParameter (EffectContext *pContext,
- int32_t *pParam,
+ void *pParam,
size_t *pValueSize,
void *pValue);
-int Volume_setParameter (EffectContext *pContext, int32_t *pParam, void *pValue);
+int Volume_setParameter (EffectContext *pContext, void *pParam, void *pValue);
int Volume_getParameter (EffectContext *pContext,
- int32_t *pParam,
+ void *pParam,
size_t *pValueSize,
void *pValue);
@@ -189,6 +191,7 @@
int32_t ioId,
effect_interface_t *pInterface){
int ret;
+ int sessionNo;
int i;
EffectContext *pContext = new EffectContext;
@@ -199,7 +202,7 @@
return -EINVAL;
}
- if((sessionId < 0)||(sessionId >= LVM_MAX_SESSIONS)){
+ if(sessionId < 0){
LOGV("\tLVM_ERROR : EffectCreate sessionId is less than 0");
return -EINVAL;
}
@@ -210,16 +213,41 @@
LvmGlobalBundle_init();
}
+ LOGV("\tEffectCreate: There are %d LVM sessions acive\n", LvmSessionsActive);
+
+ // Find next available sessionNo
+ for(i=0; i<LVM_MAX_SESSIONS; i++){
+ if((SessionIndex[i] == -1)||(SessionIndex[i] == sessionId)){
+ sessionNo = i;
+ SessionIndex[i] = sessionId;
+ LOGV("\tEffectCreate: Allocating SessionNo %d for SessionId %d\n", sessionNo,sessionId);
+ break;
+ }
+ }
+
+ if(i==LVM_MAX_SESSIONS){
+ LOGV("\tLVM_ERROR : Cannot find memory to allocate for current session");
+ return -EINVAL;
+ }
// If this is the first create in this session
- if(GlobalSessionMemory[sessionId].bBundledEffectsEnabled == LVM_FALSE){
- LOGV("\tEffectCreate - This is the first effect in current session %d", sessionId);
- LOGV("\tEffectCreate - Setting up Bundled Effects Instance for session %d", sessionId);
+ if(GlobalSessionMemory[sessionNo].bBundledEffectsEnabled == LVM_FALSE){
+ LOGV("\tEffectCreate - This is the first effect in current sessionId %d sessionNo %d",
+ sessionId, sessionNo);
- GlobalSessionMemory[sessionId].bBundledEffectsEnabled = LVM_TRUE;
- GlobalSessionMemory[sessionId].pBundledContext = new BundledEffectContext;
+ LvmSessionsActive++;
- pContext->pBundledContext = GlobalSessionMemory[sessionId].pBundledContext;
- pContext->pBundledContext->SessionNo = sessionId;
+ if(LvmSessionsActive >= LVM_MAX_SESSIONS){
+ LOGV("\tLVM_ERROR : Number of active session is greater than LVM_MAX_SESSIONS (%d)",
+ LVM_MAX_SESSIONS);
+ return -EINVAL;
+ }
+
+ GlobalSessionMemory[sessionNo].bBundledEffectsEnabled = LVM_TRUE;
+ GlobalSessionMemory[sessionNo].pBundledContext = new BundledEffectContext;
+
+ pContext->pBundledContext = GlobalSessionMemory[sessionNo].pBundledContext;
+ pContext->pBundledContext->SessionNo = sessionNo;
+ pContext->pBundledContext->SessionId = sessionId;
pContext->pBundledContext->hInstance = NULL;
pContext->pBundledContext->bVolumeEnabled = LVM_FALSE;
pContext->pBundledContext->bEqualizerEnabled = LVM_FALSE;
@@ -267,37 +295,39 @@
}
}
else{
- pContext->pBundledContext = GlobalSessionMemory[sessionId].pBundledContext;
+ LOGV("\tEffectCreate - Assigning memory for previously created effect on sessionNo %d",
+ sessionNo);
+ pContext->pBundledContext =
+ GlobalSessionMemory[sessionNo].pBundledContext;
}
-
LOGV("\tEffectCreate - pBundledContext is %p", pContext->pBundledContext);
// Create each Effect
if (memcmp(uuid, &gBassBoostDescriptor.uuid, sizeof(effect_uuid_t)) == 0){
// Create Bass Boost
LOGV("\tEffectCreate - Effect to be created is LVM_BASS_BOOST");
- GlobalSessionMemory[sessionId].bBassInstantiated = LVM_TRUE;
+ GlobalSessionMemory[pContext->pBundledContext->SessionNo].bBassInstantiated = LVM_TRUE;
pContext->itfe = &gLvmEffectInterface;
pContext->EffectType = LVM_BASS_BOOST;
} else if (memcmp(uuid, &gVirtualizerDescriptor.uuid, sizeof(effect_uuid_t)) == 0){
// Create Virtualizer
LOGV("\tEffectCreate - Effect to be created is LVM_VIRTUALIZER");
- GlobalSessionMemory[sessionId].bVirtualizerInstantiated = LVM_TRUE;
+ GlobalSessionMemory[pContext->pBundledContext->SessionNo].bVirtualizerInstantiated=LVM_TRUE;
pContext->itfe = &gLvmEffectInterface;
pContext->EffectType = LVM_VIRTUALIZER;
} else if (memcmp(uuid, &gEqualizerDescriptor.uuid, sizeof(effect_uuid_t)) == 0){
// Create Equalizer
LOGV("\tEffectCreate - Effect to be created is LVM_EQUALIZER");
- GlobalSessionMemory[sessionId].bEqualizerInstantiated = LVM_TRUE;
+ GlobalSessionMemory[pContext->pBundledContext->SessionNo].bEqualizerInstantiated = LVM_TRUE;
pContext->itfe = &gLvmEffectInterface;
pContext->EffectType = LVM_EQUALIZER;
} else if (memcmp(uuid, &gVolumeDescriptor.uuid, sizeof(effect_uuid_t)) == 0){
// Create Volume
LOGV("\tEffectCreate - Effect to be created is LVM_VOLUME");
- GlobalSessionMemory[sessionId].bVolumeInstantiated = LVM_TRUE;
+ GlobalSessionMemory[pContext->pBundledContext->SessionNo].bVolumeInstantiated = LVM_TRUE;
pContext->itfe = &gLvmEffectInterface;
pContext->EffectType = LVM_VOLUME;
@@ -316,6 +346,7 @@
LOGV("\n\tEffectRelease start %p", interface);
EffectContext * pContext = (EffectContext *)interface;
+ LOGV("\n\tEffectRelease start interface: %p, context %p", interface, pContext->pBundledContext);
if (pContext == NULL){
LOGV("\tLVM_ERROR : EffectRelease called with NULL pointer");
return -EINVAL;
@@ -349,13 +380,28 @@
fclose(pContext->pBundledContext->PcmInPtr);
fclose(pContext->pBundledContext->PcmOutPtr);
#endif
+
+ LvmSessionsActive--;
+ LOGV("\tEffectRelease: There are %d LVM sessions remaining\n", LvmSessionsActive);
+
+ // Clear the SessionIndex
+ for(int i=0; i<LVM_MAX_SESSIONS; i++){
+ if(SessionIndex[i] == pContext->pBundledContext->SessionId){
+ SessionIndex[i] = -1;
+ LOGV("\tEffectRelease: Clearing SessionIndex SessionNo %d for SessionId %d\n",
+ i, pContext->pBundledContext->SessionId);
+ break;
+ }
+ }
+
LOGV("\tEffectRelease: All effects are no longer instantiated\n");
GlobalSessionMemory[pContext->pBundledContext->SessionNo].bBundledEffectsEnabled =LVM_FALSE;
GlobalSessionMemory[pContext->pBundledContext->SessionNo].pBundledContext = LVM_NULL;
LOGV("\tEffectRelease: Freeing LVM Bundle memory\n");
LvmEffect_free(pContext);
- LOGV("\tEffectRelease: Deleting LVM Bundle context\n");
+ LOGV("\tEffectRelease: Deleting LVM Bundle context %p\n", pContext->pBundledContext);
delete pContext->pBundledContext;
+ pContext->pBundledContext = LVM_NULL;
}
// free the effect context for current effect
delete pContext;
@@ -374,6 +420,8 @@
GlobalSessionMemory[i].bBassInstantiated = LVM_FALSE;
GlobalSessionMemory[i].bVirtualizerInstantiated = LVM_FALSE;
GlobalSessionMemory[i].pBundledContext = LVM_NULL;
+
+ SessionIndex[i] = -1;
}
return;
}
@@ -505,6 +553,9 @@
params.SpeakerType = LVM_HEADPHONES;
pContext->pBundledContext->SampleRate = LVM_FS_44100;
+ pContext->pBundledContext->SamplesToExitCountEq = 44100*2*2; // 2 secs Stereo
+ pContext->pBundledContext->SamplesToExitCountBb = 44100*2*2; // 2 secs Stereo
+ pContext->pBundledContext->SamplesToExitCountVirt = 44100*2*2; // 2 secs Stereo
/* Concert Sound parameters */
params.VirtualizerOperatingMode = LVM_MODE_OFF;
@@ -842,21 +893,27 @@
switch (pConfig->inputCfg.samplingRate) {
case 8000:
SampleRate = LVM_FS_8000;
+ pContext->pBundledContext->SamplesPerSecond = 8000*2; // 2 secs Stereo
break;
case 16000:
SampleRate = LVM_FS_16000;
+ pContext->pBundledContext->SamplesPerSecond = 16000*2; // 2 secs Stereo
break;
case 22050:
SampleRate = LVM_FS_22050;
+ pContext->pBundledContext->SamplesPerSecond = 22050*2; // 2 secs Stereo
break;
case 32000:
SampleRate = LVM_FS_32000;
+ pContext->pBundledContext->SamplesPerSecond = 32000*2; // 2 secs Stereo
break;
case 44100:
SampleRate = LVM_FS_44100;
+ pContext->pBundledContext->SamplesPerSecond = 44100*2; // 2 secs Stereo
break;
case 48000:
SampleRate = LVM_FS_48000;
+ pContext->pBundledContext->SamplesPerSecond = 48000*2; // 2 secs Stereo
break;
default:
LOGV("\tEffect_Configure invalid sampling rate %d", pConfig->inputCfg.samplingRate);
@@ -881,6 +938,7 @@
LVM_ERROR_CHECK(LvmStatus, "LVM_SetControlParameters", "Effect_configure")
LOGV("\tEffect_configure Succesfully called LVM_SetControlParameters\n");
+ pContext->pBundledContext->SampleRate = SampleRate;
}else{
//LOGV("\tEffect_configure keep sampling rate at %d", SampleRate);
@@ -1461,7 +1519,7 @@
LVM_ReturnStatus_en LvmStatus=LVM_SUCCESS; /* Function call status */
LVM_INT16 Balance = 0;
-
+
pContext->pBundledContext->positionSaved = position;
Balance = VolumeConvertStereoPosition(pContext->pBundledContext->positionSaved);
@@ -1614,11 +1672,12 @@
//----------------------------------------------------------------------------
int BassBoost_getParameter(EffectContext *pContext,
- int32_t *pParam,
+ void *pParam,
size_t *pValueSize,
void *pValue){
int status = 0;
- int32_t param = *pParam++;
+ int32_t *pParamTemp = (int32_t *)pParam;
+ int32_t param = *pParamTemp++;
int32_t param2;
char *name;
@@ -1685,13 +1744,14 @@
//
//----------------------------------------------------------------------------
-int BassBoost_setParameter (EffectContext *pContext, int32_t *pParam, void *pValue){
+int BassBoost_setParameter (EffectContext *pContext, void *pParam, void *pValue){
int status = 0;
int16_t strength;
+ int32_t *pParamTemp = (int32_t *)pParam;
//LOGV("\tBassBoost_setParameter start");
- switch (*pParam){
+ switch (*pParamTemp){
case BASSBOOST_PARAM_STRENGTH:
strength = *(int16_t *)pValue;
//LOGV("\tBassBoost_setParameter() BASSBOOST_PARAM_STRENGTH value is %d", strength);
@@ -1700,7 +1760,7 @@
//LOGV("\tBassBoost_setParameter() Called pBassBoost->BassSetStrength");
break;
default:
- LOGV("\tLVM_ERROR : BassBoost_setParameter() invalid param %d", *pParam);
+ LOGV("\tLVM_ERROR : BassBoost_setParameter() invalid param %d", *pParamTemp);
break;
}
@@ -1730,11 +1790,12 @@
//----------------------------------------------------------------------------
int Virtualizer_getParameter(EffectContext *pContext,
- int32_t *pParam,
+ void *pParam,
size_t *pValueSize,
void *pValue){
int status = 0;
- int32_t param = *pParam++;
+ int32_t *pParamTemp = (int32_t *)pParam;
+ int32_t param = *pParamTemp++;
int32_t param2;
char *name;
@@ -1802,13 +1863,15 @@
//
//----------------------------------------------------------------------------
-int Virtualizer_setParameter (EffectContext *pContext, int32_t *pParam, void *pValue){
+int Virtualizer_setParameter (EffectContext *pContext, void *pParam, void *pValue){
int status = 0;
int16_t strength;
+ int32_t *pParamTemp = (int32_t *)pParam;
+ int32_t param = *pParamTemp++;
//LOGV("\tVirtualizer_setParameter start");
- switch (*pParam){
+ switch (param){
case VIRTUALIZER_PARAM_STRENGTH:
strength = *(int16_t *)pValue;
//LOGV("\tVirtualizer_setParameter() VIRTUALIZER_PARAM_STRENGTH value is %d", strength);
@@ -1817,7 +1880,7 @@
//LOGV("\tVirtualizer_setParameter() Called pVirtualizer->setStrength");
break;
default:
- LOGV("\tLVM_ERROR : Virtualizer_setParameter() invalid param %d", *pParam);
+ LOGV("\tLVM_ERROR : Virtualizer_setParameter() invalid param %d", param);
break;
}
@@ -1846,12 +1909,13 @@
//
//----------------------------------------------------------------------------
int Equalizer_getParameter(EffectContext *pContext,
- int32_t *pParam,
+ void *pParam,
size_t *pValueSize,
void *pValue){
int status = 0;
int bMute = 0;
- int32_t param = *pParam++;
+ int32_t *pParamTemp = (int32_t *)pParam;
+ int32_t param = *pParamTemp++;
int32_t param2;
char *name;
@@ -1924,7 +1988,7 @@
break;
case EQ_PARAM_BAND_LEVEL:
- param2 = *pParam;
+ param2 = *pParamTemp;
if (param2 >= FIVEBAND_NUMBANDS) {
status = -EINVAL;
break;
@@ -1935,7 +1999,7 @@
break;
case EQ_PARAM_CENTER_FREQ:
- param2 = *pParam;
+ param2 = *pParamTemp;
if (param2 >= FIVEBAND_NUMBANDS) {
status = -EINVAL;
break;
@@ -1946,7 +2010,7 @@
break;
case EQ_PARAM_BAND_FREQ_RANGE:
- param2 = *pParam;
+ param2 = *pParamTemp;
if (param2 >= FIVEBAND_NUMBANDS) {
status = -EINVAL;
break;
@@ -1957,7 +2021,7 @@
break;
case EQ_PARAM_GET_BAND:
- param2 = *pParam;
+ param2 = *pParamTemp;
*(uint16_t *)pValue = (uint16_t)EqualizerGetBand(pContext, param2);
//LOGV("\tEqualizer_getParameter() EQ_PARAM_GET_BAND frequency %d, band %d",
// param2, *(int32_t *)pValue);
@@ -1974,7 +2038,7 @@
break;
case EQ_PARAM_GET_PRESET_NAME:
- param2 = *pParam;
+ param2 = *pParamTemp;
if (param2 >= EqualizerGetNumPresets()) {
//if (param2 >= 20) { // AGO FIX
status = -EINVAL;
@@ -2022,12 +2086,14 @@
// Outputs:
//
//----------------------------------------------------------------------------
-int Equalizer_setParameter (EffectContext *pContext, int32_t *pParam, void *pValue){
+int Equalizer_setParameter (EffectContext *pContext, void *pParam, void *pValue){
int status = 0;
int32_t preset;
int32_t band;
int32_t level;
- int32_t param = *pParam++;
+ int32_t *pParamTemp = (int32_t *)pParam;
+ int32_t param = *pParamTemp++;
+
//LOGV("\tEqualizer_setParameter start");
switch (param) {
@@ -2042,7 +2108,7 @@
EqualizerSetPreset(pContext, preset);
break;
case EQ_PARAM_BAND_LEVEL:
- band = *pParam;
+ band = *pParamTemp;
level = (int32_t)(*(int16_t *)pValue);
//LOGV("\tEqualizer_setParameter() EQ_PARAM_BAND_LEVEL band %d, level %d", band, level);
if (band >= FIVEBAND_NUMBANDS) {
@@ -2102,13 +2168,13 @@
//----------------------------------------------------------------------------
int Volume_getParameter(EffectContext *pContext,
- int32_t *pParam,
+ void *pParam,
size_t *pValueSize,
void *pValue){
int status = 0;
int bMute = 0;
- int32_t param = *pParam++;
- int32_t param2;
+ int32_t *pParamTemp = (int32_t *)pParam;
+ int32_t param = *pParamTemp++;;
char *name;
LOGV("\tVolume_getParameter start");
@@ -2195,16 +2261,18 @@
//
//----------------------------------------------------------------------------
-int Volume_setParameter (EffectContext *pContext, int32_t *pParam, void *pValue){
+int Volume_setParameter (EffectContext *pContext, void *pParam, void *pValue){
int status = 0;
int16_t level;
int16_t position;
uint32_t mute;
uint32_t positionEnabled;
+ int32_t *pParamTemp = (int32_t *)pParam;
+ int32_t param = *pParamTemp++;
LOGV("\tVolume_setParameter start");
- switch (*pParam){
+ switch (param){
case VOLUME_PARAM_LEVEL:
level = *(int16_t *)pValue;
LOGV("\tVolume_setParameter() VOLUME_PARAM_LEVEL value is %d", level);
@@ -2237,7 +2305,7 @@
break;
default:
- LOGV("\tLVM_ERROR : Volume_setParameter() invalid param %d", *pParam);
+ LOGV("\tLVM_ERROR : Volume_setParameter() invalid param %d", param);
break;
}
@@ -2299,13 +2367,27 @@
audio_buffer_t *inBuffer,
audio_buffer_t *outBuffer){
EffectContext * pContext = (EffectContext *) self;
+ LVM_ControlParams_t ActiveParams; /* Current control Parameters */
+ LVM_ReturnStatus_en LvmStatus = LVM_SUCCESS; /* Function call status */
int status = 0;
+ int status2Sec = 0;
int lvmStatus = 0;
LVM_INT16 *in = (LVM_INT16 *)inBuffer->raw;
LVM_INT16 *out = (LVM_INT16 *)outBuffer->raw;
//LOGV("\tEffect_process Start : Enabled = %d Called = %d",
//pContext->pBundledContext->NumberEffectsEnabled,pContext->pBundledContext->NumberEffectsCalled);
+// LOGV("\tEffect_process Start : Samples left %d %d %d",
+// pContext->pBundledContext->SamplesToExitCountBb,
+// pContext->pBundledContext->SamplesToExitCountVirt,
+// pContext->pBundledContext->SamplesToExitCountEq);
+
+// LvmStatus = LVM_GetControlParameters(pContext->pBundledContext->hInstance, &ActiveParams);
+// LVM_ERROR_CHECK(LvmStatus, "LVM_GetControlParameters", "VolumeGetStereoPosition")
+// if(LvmStatus != LVM_SUCCESS) return -EINVAL;
+// LOGV("\tEffect_process Internal Operating Modes: BB %d VIRT %d EQ %d",
+// ActiveParams.BE_OperatingMode, ActiveParams.VirtualizerOperatingMode,
+// ActiveParams.EQNB_OperatingMode);
if (pContext == NULL){
LOGV("\tLVM_ERROR : Effect_process() ERROR pContext == NULL");
@@ -2319,23 +2401,44 @@
}
if ((pContext->pBundledContext->bBassEnabled == LVM_FALSE)&&
(pContext->EffectType == LVM_BASS_BOOST)){
- LOGV("\tEffect_process() ERROR LVM_BASS_BOOST Effect is not enabled");
+ //LOGV("\tEffect_process() LVM_BASS_BOOST Effect is not enabled");
+ if(pContext->pBundledContext->SamplesToExitCountBb > 0){
+ status2Sec = -ENODATA;
+ pContext->pBundledContext->SamplesToExitCountBb -= outBuffer->frameCount * 2; // STEREO
+ //LOGV("\tEffect_process: Waiting for 2 secs to turn off BASS_BOOST, %d samples left",
+ // pContext->pBundledContext->SamplesToExitCountBb);
+ } else {
status = -ENODATA;
+ }
}
if ((pContext->pBundledContext->bVolumeEnabled == LVM_FALSE)&&
(pContext->EffectType == LVM_VOLUME)){
- LOGV("\tEffect_process() ERROR LVM_VOLUME Effect is not enabled");
+ //LOGV("\tEffect_process() LVM_VOLUME Effect is not enabled");
status = -ENODATA;
}
if ((pContext->pBundledContext->bEqualizerEnabled == LVM_FALSE)&&
(pContext->EffectType == LVM_EQUALIZER)){
- LOGV("\tEffect_process() ERROR LVM_EQUALIZER Effect is not enabled");
- status = -ENODATA;
+ //LOGV("\tEffect_process() LVM_EQUALIZER Effect is not enabled");
+ if(pContext->pBundledContext->SamplesToExitCountEq > 0){
+ status2Sec = -ENODATA;
+ pContext->pBundledContext->SamplesToExitCountEq -= outBuffer->frameCount * 2; // STEREO
+ //LOGV("\tEffect_process: Waiting for 2 secs to turn off EQUALIZER, %d samples left",
+ // pContext->pBundledContext->SamplesToExitCountEq);
+ } else {
+ status = -ENODATA;
+ }
}
if ((pContext->pBundledContext->bVirtualizerEnabled == LVM_FALSE)&&
(pContext->EffectType == LVM_VIRTUALIZER)){
- LOGV("\tEffect_process() ERROR LVM_VIRTUALIZER Effect is not enabled");
- status = -ENODATA;
+ //LOGV("\tEffect_process() LVM_VIRTUALIZER Effect is not enabled");
+ if(pContext->pBundledContext->SamplesToExitCountVirt > 0){
+ status2Sec = -ENODATA;
+ pContext->pBundledContext->SamplesToExitCountVirt -= outBuffer->frameCount * 2;// STEREO
+ //LOGV("\tEffect_process: Waiting for 2 secs to turn off VIRTUALIZER, %d samples left",
+ // pContext->pBundledContext->SamplesToExitCountVirt);
+ } else {
+ status = -ENODATA;
+ }
}
// If this is the last frame of an effect process its output with no effect
@@ -2352,7 +2455,7 @@
}
}
- if(status != -ENODATA){
+ if((status2Sec != -ENODATA)&&(status != -ENODATA)){
pContext->pBundledContext->NumberEffectsCalled++;
}
@@ -2496,7 +2599,7 @@
int voffset = ((p->psize - 1) / sizeof(int32_t) + 1) * sizeof(int32_t);
p->status = android::BassBoost_getParameter(pContext,
- (int32_t *)p->data,
+ p->data,
(size_t *)&p->vsize,
p->data + voffset);
@@ -2527,7 +2630,7 @@
int voffset = ((p->psize - 1) / sizeof(int32_t) + 1) * sizeof(int32_t);
p->status = android::Virtualizer_getParameter(pContext,
- (int32_t *)p->data,
+ (void *)p->data,
(size_t *)&p->vsize,
p->data + voffset);
@@ -2558,8 +2661,10 @@
int voffset = ((p->psize - 1) / sizeof(int32_t) + 1) * sizeof(int32_t);
- p->status = android::Equalizer_getParameter(pContext, (int32_t *)p->data, &p->vsize,
- p->data + voffset);
+ p->status = android::Equalizer_getParameter(pContext,
+ p->data,
+ &p->vsize,
+ p->data + voffset);
*replySize = sizeof(effect_param_t) + voffset + p->vsize;
@@ -2590,7 +2695,7 @@
int voffset = ((p->psize - 1) / sizeof(int32_t) + 1) * sizeof(int32_t);
p->status = android::Volume_getParameter(pContext,
- (int32_t *)p->data,
+ (void *)p->data,
(size_t *)&p->vsize,
p->data + voffset);
@@ -2636,7 +2741,7 @@
// cmdSize, sizeof(effect_param_t), p->psize, p->vsize );
*(int *)pReplyData = android::BassBoost_setParameter(pContext,
- (int32_t *)p->data,
+ (void *)p->data,
p->data + p->psize);
}
if(pContext->EffectType == LVM_VIRTUALIZER){
@@ -2669,7 +2774,7 @@
// cmdSize, sizeof(effect_param_t), p->psize, p->vsize );
*(int *)pReplyData = android::Virtualizer_setParameter(pContext,
- (int32_t *)p->data,
+ (void *)p->data,
p->data + p->psize);
}
if(pContext->EffectType == LVM_EQUALIZER){
@@ -2689,7 +2794,7 @@
effect_param_t *p = (effect_param_t *) pCmdData;
*(int *)pReplyData = android::Equalizer_setParameter(pContext,
- (int32_t *)p->data,
+ (void *)p->data,
p->data + p->psize);
}
if(pContext->EffectType == LVM_VOLUME){
@@ -2711,14 +2816,14 @@
effect_param_t *p = (effect_param_t *) pCmdData;
*(int *)pReplyData = android::Volume_setParameter(pContext,
- (int32_t *)p->data,
+ (void *)p->data,
p->data + p->psize);
}
//LOGV("\tEffect_command cmdCode Case: EFFECT_CMD_SET_PARAM end");
} break;
case EFFECT_CMD_ENABLE:
- //LOGV("\tEffect_command cmdCode Case: EFFECT_CMD_ENABLE start");
+ LOGV("\tEffect_command cmdCode Case: EFFECT_CMD_ENABLE start");
if (pReplyData == NULL || *replySize != sizeof(int)){
LOGV("\tLVM_ERROR : Effect_command cmdCode Case: EFFECT_CMD_ENABLE: ERROR");
return -EINVAL;
@@ -2768,6 +2873,14 @@
*(int *)pReplyData = 0;
pContext->pBundledContext->NumberEffectsEnabled++;
android::LvmEffect_enable(pContext);
+ pContext->pBundledContext->SamplesToExitCountEq =
+ (LVM_INT32)(pContext->pBundledContext->SamplesPerSecond*1); // 0.1 secs Stereo
+ pContext->pBundledContext->SamplesToExitCountBb =
+ (LVM_INT32)(pContext->pBundledContext->SamplesPerSecond*6); // 2 secs Stereo
+ pContext->pBundledContext->SamplesToExitCountVirt =
+ (LVM_INT32)(pContext->pBundledContext->SamplesPerSecond*1); // 2 secs Stereo
+ LOGV("\tEffect_command cmdCode Case: EFFECT_CMD_ENABLE Samples to Exit = %d",
+ pContext->pBundledContext->SamplesToExitCountBb);
//LOGV("\tEffect_command cmdCode Case: EFFECT_CMD_ENABLE NumberEffectsEnabled = %d",
// pContext->pBundledContext->NumberEffectsEnabled);
//LOGV("\tEffect_command cmdCode Case: EFFECT_CMD_ENABLE end");
@@ -2906,11 +3019,8 @@
}
case EFFECT_CMD_SET_VOLUME:
{
- int32_t channels = cmdSize/sizeof(int32_t);
int32_t vol = *(int32_t *)pCmdData;
- int16_t vol_db;
int16_t dB;
- int16_t vol_db_rnd;
int32_t vol_ret[2] = {1<<24,1<<24}; // Apply no volume
// if pReplyData is NULL, VOL_CTRL is delegated to another effect
diff --git a/media/libeffects/lvm/wrapper/Bundle/EffectBundle.h b/media/libeffects/lvm/wrapper/Bundle/EffectBundle.h
index d009bf9..1bee974 100644
--- a/media/libeffects/lvm/wrapper/Bundle/EffectBundle.h
+++ b/media/libeffects/lvm/wrapper/Bundle/EffectBundle.h
@@ -58,6 +58,7 @@
struct BundledEffectContext{
LVM_Handle_t hInstance; /* Instance handle */
int SessionNo; /* Current session number */
+ int SessionId; /* Current session id */
bool bVolumeEnabled; /* Flag for Volume */
bool bEqualizerEnabled; /* Flag for EQ */
bool bBassEnabled; /* Flag for Bass */
@@ -80,6 +81,10 @@
bool bStereoPositionEnabled;
int frameCount;
LVM_Fs_en SampleRate;
+ int SamplesPerSecond;
+ int SamplesToExitCountEq;
+ int SamplesToExitCountBb;
+ int SamplesToExitCountVirt;
#ifdef LVM_PCM
FILE *PcmInPtr;
FILE *PcmOutPtr;
diff --git a/media/libeffects/lvm/wrapper/Reverb/EffectReverb.cpp b/media/libeffects/lvm/wrapper/Reverb/EffectReverb.cpp
new file mode 100755
index 0000000..03f1409
--- /dev/null
+++ b/media/libeffects/lvm/wrapper/Reverb/EffectReverb.cpp
@@ -0,0 +1,1965 @@
+/*
+ * Copyright (C) 2010-2010 NXP Software
+ * Copyright (C) 2009 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_TAG "Reverb"
+#define ARRAY_SIZE(array) (sizeof array / sizeof array[0])
+//#define LOG_NDEBUG 0
+
+#include <cutils/log.h>
+#include <assert.h>
+#include <stdlib.h>
+#include <string.h>
+#include <new>
+#include <EffectReverb.h>
+#include <LVREV.h>
+
+#define MAX_NUM_BANDS 5
+#define MAX_CALL_SIZE 256
+#define LVREV_MAX_T60 7000
+#define LVREV_MAX_REVERB_LEVEL 2000
+
+//#define LVM_PCM
+
+// effect_interface_t interface implementation for reverb
+extern "C" const struct effect_interface_s gReverbInterface;
+
+#define LVM_ERROR_CHECK(LvmStatus, callingFunc, calledFunc){\
+ if (LvmStatus == LVREV_NULLADDRESS){\
+ LOGV("\tLVREV_ERROR : Parameter error - "\
+ "null pointer returned by %s in %s\n\n\n\n", callingFunc, calledFunc);\
+ }\
+ if (LvmStatus == LVREV_INVALIDNUMSAMPLES){\
+ LOGV("\tLVREV_ERROR : Parameter error - "\
+ "bad number of samples returned by %s in %s\n\n\n\n", callingFunc, calledFunc);\
+ }\
+ if (LvmStatus == LVREV_OUTOFRANGE){\
+ LOGV("\tLVREV_ERROR : Parameter error - "\
+ "out of range returned by %s in %s\n", callingFunc, calledFunc);\
+ }\
+ }
+
+// Namespaces
+namespace android {
+namespace {
+
+/************************************************************************************/
+/* */
+/* Preset definitions */
+/* */
+/************************************************************************************/
+
+const static t_reverb_settings sReverbPresets[] = {
+ // REVERB_PRESET_NONE: values are unused
+ {0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
+ // REVERB_PRESET_SMALLROOM
+ {-1000, -600, 1100, 830, -400, 5, 500, 10, 1000, 1000},
+ // REVERB_PRESET_MEDIUMROOM
+ {-1000, -600, 1300, 830, -1000, 20, -200, 20, 1000, 1000},
+ // REVERB_PRESET_LARGEROOM
+ {-1000, -600, 1500, 830, -1600, 5, -1000, 40, 1000, 1000},
+ // REVERB_PRESET_MEDIUMHALL
+ {-1000, -600, 1800, 700, -1300, 15, -800, 30, 1000, 1000},
+ // REVERB_PRESET_LARGEHALL
+ {-1000, -600, 1800, 700, -2000, 30, -1400, 60, 1000, 1000},
+ // REVERB_PRESET_PLATE
+ {-1000, -200, 1300, 900, 0, 2, 0, 10, 1000, 750},
+};
+
+
+// NXP SW auxiliary environmental reverb
+const effect_descriptor_t gAuxEnvReverbDescriptor = {
+ { 0xc2e5d5f0, 0x94bd, 0x4763, 0x9cac, { 0x4e, 0x23, 0x4d, 0x06, 0x83, 0x9e } },
+ { 0x4a387fc0, 0x8ab3, 0x11df, 0x8bad, { 0x00, 0x02, 0xa5, 0xd5, 0xc5, 0x1b } },
+ EFFECT_API_VERSION,
+ EFFECT_FLAG_TYPE_AUXILIARY,
+ 0, // TODO
+ 1,
+ "Auxiliary Environmental Reverb",
+ "NXP Software Ltd.",
+};
+
+// NXP SW insert environmental reverb
+static const effect_descriptor_t gInsertEnvReverbDescriptor = {
+ {0xc2e5d5f0, 0x94bd, 0x4763, 0x9cac, {0x4e, 0x23, 0x4d, 0x06, 0x83, 0x9e}},
+ {0xc7a511a0, 0xa3bb, 0x11df, 0x860e, {0x00, 0x02, 0xa5, 0xd5, 0xc5, 0x1b}},
+ EFFECT_API_VERSION,
+ EFFECT_FLAG_TYPE_INSERT | EFFECT_FLAG_INSERT_FIRST,
+ 0, // TODO
+ 1,
+ "Insert Environmental Reverb",
+ "NXP Software Ltd.",
+};
+
+// NXP SW auxiliary preset reverb
+static const effect_descriptor_t gAuxPresetReverbDescriptor = {
+ {0x47382d60, 0xddd8, 0x11db, 0xbf3a, {0x00, 0x02, 0xa5, 0xd5, 0xc5, 0x1b}},
+ {0xf29a1400, 0xa3bb, 0x11df, 0x8ddc, {0x00, 0x02, 0xa5, 0xd5, 0xc5, 0x1b}},
+ EFFECT_API_VERSION,
+ EFFECT_FLAG_TYPE_AUXILIARY,
+ 0, // TODO
+ 1,
+ "Auxiliary Preset Reverb",
+ "NXP Software Ltd.",
+};
+
+// NXP SW insert preset reverb
+static const effect_descriptor_t gInsertPresetReverbDescriptor = {
+ {0x47382d60, 0xddd8, 0x11db, 0xbf3a, {0x00, 0x02, 0xa5, 0xd5, 0xc5, 0x1b}},
+ {0x172cdf00, 0xa3bc, 0x11df, 0xa72f, {0x00, 0x02, 0xa5, 0xd5, 0xc5, 0x1b}},
+ EFFECT_API_VERSION,
+ EFFECT_FLAG_TYPE_INSERT | EFFECT_FLAG_INSERT_FIRST,
+ 0, // TODO
+ 1,
+ "Insert Preset Reverb",
+ "NXP Software Ltd.",
+};
+
+// gDescriptors contains pointers to all defined effect descriptor in this library
+static const effect_descriptor_t * const gDescriptors[] = {
+ &gAuxEnvReverbDescriptor,
+ &gInsertEnvReverbDescriptor,
+ &gAuxPresetReverbDescriptor,
+ &gInsertPresetReverbDescriptor
+};
+
+struct ReverbContext{
+ const struct effect_interface_s *itfe;
+ effect_config_t config;
+ LVREV_Handle_t hInstance;
+ int16_t SavedRoomLevel;
+ int16_t SavedHfLevel;
+ int16_t SavedDecayTime;
+ int16_t SavedDecayHfRatio;
+ int16_t SavedReverbLevel;
+ int16_t SavedDiffusion;
+ int16_t SavedDensity;
+ bool bEnabled;
+ #ifdef LVM_PCM
+ FILE *PcmInPtr;
+ FILE *PcmOutPtr;
+ #endif
+ LVM_Fs_en SampleRate;
+ bool auxiliary;
+ bool preset;
+ uint16_t curPreset;
+ uint16_t nextPreset;
+};
+
+#define REVERB_DEFAULT_PRESET REVERB_PRESET_MEDIUMROOM
+
+//--- local function prototypes
+int Reverb_init (ReverbContext *pContext);
+void Reverb_free (ReverbContext *pContext);
+int Reverb_configure (ReverbContext *pContext, effect_config_t *pConfig);
+int Reverb_setParameter (ReverbContext *pContext, void *pParam, void *pValue);
+int Reverb_getParameter (ReverbContext *pContext,
+ void *pParam,
+ size_t *pValueSize,
+ void *pValue);
+int Reverb_LoadPreset (ReverbContext *pContext);
+
+/* Effect Library Interface Implementation */
+extern "C" int EffectQueryNumberEffects(uint32_t *pNumEffects){
+ LOGV("\n\tEffectQueryNumberEffects start");
+ *pNumEffects = sizeof(gDescriptors) / sizeof(const effect_descriptor_t *);
+ LOGV("\tEffectQueryNumberEffects creating %d effects", *pNumEffects);
+ LOGV("\tEffectQueryNumberEffects end\n");
+ return 0;
+} /* end EffectQueryNumberEffects */
+
+extern "C" int EffectQueryEffect(uint32_t index, effect_descriptor_t *pDescriptor){
+ LOGV("\n\tEffectQueryEffect start");
+ LOGV("\tEffectQueryEffect processing index %d", index);
+ if (pDescriptor == NULL){
+ LOGV("\tLVM_ERROR : EffectQueryEffect was passed NULL pointer");
+ return -EINVAL;
+ }
+ if (index >= sizeof(gDescriptors) / sizeof(const effect_descriptor_t *)) {
+ LOGV("\tLVM_ERROR : EffectQueryEffect index out of range %d", index);
+ return -ENOENT;
+ }
+ memcpy(pDescriptor, gDescriptors[index], sizeof(effect_descriptor_t));
+ LOGV("\tEffectQueryEffect end\n");
+ return 0;
+} /* end EffectQueryEffect */
+
+extern "C" int EffectCreate(effect_uuid_t *uuid,
+ int32_t sessionId,
+ int32_t ioId,
+ effect_interface_t *pInterface){
+ int ret;
+ int i;
+ int length = sizeof(gDescriptors) / sizeof(const effect_descriptor_t *);
+ const effect_descriptor_t *desc;
+
+ LOGV("\t\nEffectCreate start");
+
+ if (pInterface == NULL || uuid == NULL){
+ LOGV("\tLVM_ERROR : EffectCreate() called with NULL pointer");
+ return -EINVAL;
+ }
+
+ for (i = 0; i < length; i++) {
+ desc = gDescriptors[i];
+ if (memcmp(uuid, &desc->uuid, sizeof(effect_uuid_t))
+ == 0) {
+ break;
+ }
+ }
+
+ if (i == length) {
+ return -ENOENT;
+ }
+
+ ReverbContext *pContext = new ReverbContext;
+
+ pContext->itfe = &gReverbInterface;
+ pContext->hInstance = NULL;
+
+ pContext->auxiliary = false;
+ if ((desc->flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY){
+ pContext->auxiliary = true;
+ }
+
+ pContext->preset = false;
+ if (memcmp(&desc->type, SL_IID_PRESETREVERB, sizeof(effect_uuid_t)) == 0) {
+ pContext->preset = true;
+ // force reloading preset at first call to process()
+ pContext->curPreset = REVERB_PRESET_LAST + 1;
+ pContext->nextPreset = REVERB_DEFAULT_PRESET;
+ }
+
+ LOGV("\tEffectCreate - Calling Reverb_init");
+ ret = Reverb_init(pContext);
+
+ if (ret < 0){
+ LOGV("\tLVM_ERROR : EffectCreate() init failed");
+ delete pContext;
+ return ret;
+ }
+
+ *pInterface = (effect_interface_t)pContext;
+
+ #ifdef LVM_PCM
+ pContext->PcmInPtr = NULL;
+ pContext->PcmOutPtr = NULL;
+
+ pContext->PcmInPtr = fopen("/data/tmp/reverb_pcm_in.pcm", "w");
+ pContext->PcmOutPtr = fopen("/data/tmp/reverb_pcm_out.pcm", "w");
+
+ if((pContext->PcmInPtr == NULL)||
+ (pContext->PcmOutPtr == NULL)){
+ return -EINVAL;
+ }
+ #endif
+
+ LOGV("\tEffectCreate %p, size %d", pContext, sizeof(ReverbContext));
+ LOGV("\tEffectCreate end\n");
+ return 0;
+} /* end EffectCreate */
+
+extern "C" int EffectRelease(effect_interface_t interface){
+ ReverbContext * pContext = (ReverbContext *)interface;
+
+ LOGV("\tEffectRelease %p", interface);
+ if (pContext == NULL){
+ LOGV("\tLVM_ERROR : EffectRelease called with NULL pointer");
+ return -EINVAL;
+ }
+
+ #ifdef LVM_PCM
+ fclose(pContext->PcmInPtr);
+ fclose(pContext->PcmOutPtr);
+ #endif
+ Reverb_free(pContext);
+ delete pContext;
+ return 0;
+} /* end EffectRelease */
+
+/* local functions */
+#define CHECK_ARG(cond) { \
+ if (!(cond)) { \
+ LOGV("\tLVM_ERROR : Invalid argument: "#cond); \
+ return -EINVAL; \
+ } \
+}
+
+//----------------------------------------------------------------------------
+// MonoTo2I_32()
+//----------------------------------------------------------------------------
+// Purpose:
+// Convert MONO to STEREO
+//
+//----------------------------------------------------------------------------
+
+void MonoTo2I_32( const LVM_INT32 *src,
+ LVM_INT32 *dst,
+ LVM_INT16 n)
+{
+ LVM_INT16 ii;
+ src += (n-1);
+ dst += ((n*2)-1);
+
+ for (ii = n; ii != 0; ii--)
+ {
+ *dst = *src;
+ dst--;
+
+ *dst = *src;
+ dst--;
+ src--;
+ }
+
+ return;
+}
+
+//----------------------------------------------------------------------------
+// From2iToMono_32()
+//----------------------------------------------------------------------------
+// Purpose:
+// Convert STEREO to MONO
+//
+//----------------------------------------------------------------------------
+
+void From2iToMono_32( const LVM_INT32 *src,
+ LVM_INT32 *dst,
+ LVM_INT16 n)
+{
+ LVM_INT16 ii;
+ LVM_INT32 Temp;
+
+ for (ii = n; ii != 0; ii--)
+ {
+ Temp = (*src>>1);
+ src++;
+
+ Temp +=(*src>>1);
+ src++;
+
+ *dst = Temp;
+ dst++;
+ }
+
+ return;
+}
+
+static inline int16_t clamp16(int32_t sample)
+{
+ if ((sample>>15) ^ (sample>>31))
+ sample = 0x7FFF ^ (sample>>31);
+ return sample;
+}
+
+//----------------------------------------------------------------------------
+// process()
+//----------------------------------------------------------------------------
+// Purpose:
+// Apply the Reverb
+//
+// Inputs:
+// pIn: pointer to stereo/mono 16 bit input data
+// pOut: pointer to stereo 16 bit output data
+// frameCount: Frames to process
+// pContext: effect engine context
+// strength strength to be applied
+//
+// Outputs:
+// pOut: pointer to updated stereo 16 bit output data
+//
+//----------------------------------------------------------------------------
+
+int process( LVM_INT16 *pIn,
+ LVM_INT16 *pOut,
+ int frameCount,
+ ReverbContext *pContext){
+
+ LVM_INT16 samplesPerFrame = 0;
+ LVREV_ReturnStatus_en LvmStatus = LVREV_SUCCESS; /* Function call status */
+
+ LVM_INT32 *InFrames32;
+ LVM_INT32 *OutFrames32;
+ LVM_INT16 *OutFrames16;
+
+
+ // Check that the input is either mono or stereo
+ if(pContext->config.inputCfg.channels == CHANNEL_STEREO){
+ samplesPerFrame = 2;
+ } else if (pContext->config.inputCfg.channels == CHANNEL_MONO){
+ samplesPerFrame = 1;
+ } else {
+ LOGV("\tLVREV_ERROR : process invalid PCM format");
+ return -EINVAL;
+ }
+
+ InFrames32 = (LVM_INT32 *)malloc(frameCount * sizeof(LVM_INT32) * 2);
+ OutFrames32 = (LVM_INT32 *)malloc(frameCount * sizeof(LVM_INT32) * 2);
+ OutFrames16 = (LVM_INT16 *)OutFrames32;
+
+ // Check for NULL pointers
+ if((InFrames32 == NULL)||(OutFrames32 == NULL)){
+ LOGV("\tLVREV_ERROR : process failed to allocate memory for temporary buffers ");
+ return -EINVAL;
+ }
+
+ #ifdef LVM_PCM
+ fwrite(pIn, frameCount*sizeof(LVM_INT16)*samplesPerFrame, 1, pContext->PcmInPtr);
+ fflush(pContext->PcmInPtr);
+ #endif
+
+ if (pContext->preset && pContext->nextPreset != pContext->curPreset) {
+ Reverb_LoadPreset(pContext);
+ }
+ // Convert to Input 32 bits
+ for(int i=0; i<frameCount*samplesPerFrame; i++){
+ InFrames32[i] = (LVM_INT32)pIn[i]<<8;
+ }
+
+ // If the input was MONO, convert to STEREO
+ if(pContext->config.inputCfg.channels == CHANNEL_MONO){
+ //LOGV("\tConverting Output from MONO to STEREO");
+ MonoTo2I_32(InFrames32, InFrames32, frameCount);
+ }
+
+ //LOGV("\tProcess, frames: %d, InFormat: %d(MONO=%d), OutFormat: %d(STEREO=%d)",
+ //frameCount, pContext->config.inputCfg.channels, CHANNEL_MONO,
+ //pContext->config.outputCfg.channels, CHANNEL_STEREO);
+
+ if (pContext->preset && pContext->curPreset == REVERB_PRESET_NONE) {
+ memset(OutFrames32, 0, frameCount * sizeof(LVM_INT32) * 2);
+ } else {
+ /* Process the samples */
+ LvmStatus = LVREV_Process(pContext->hInstance, /* Instance handle */
+ InFrames32, /* Input buffer */
+ OutFrames32, /* Output buffer */
+ frameCount); /* Number of samples to read */
+ }
+
+ if (!pContext->auxiliary) {
+ for (int i=0; i<frameCount*2; i++){
+ OutFrames32[i] += InFrames32[i];
+ }
+ }
+
+ LVM_ERROR_CHECK(LvmStatus, "LVREV_Process", "process")
+ if(LvmStatus != LVREV_SUCCESS) return -EINVAL;
+
+ // Convert to 16 bits
+ for(int i=0; i<frameCount*2; i++){ // Always stereo
+ OutFrames16[i] = clamp16(OutFrames32[i]>>8);
+ }
+
+ #ifdef LVM_PCM
+ fwrite(OutFrames16, frameCount*sizeof(LVM_INT16)*samplesPerFrame, 1, pContext->PcmOutPtr);
+ fflush(pContext->PcmOutPtr);
+ #endif
+
+ // Accumulate if required
+ if (pContext->config.outputCfg.accessMode == EFFECT_BUFFER_ACCESS_ACCUMULATE){
+ //LOGV("\tBuffer access is ACCUMULATE");
+ for (int i=0; i<frameCount*2; i++){
+ pOut[i] = clamp16((int32_t)pOut[i] + (int32_t)OutFrames16[i]);
+ }
+ }else{
+ //LOGV("\tBuffer access is WRITE");
+ memcpy(pOut, OutFrames16, frameCount*sizeof(LVM_INT16)*2); // 2 is for stereo output
+ }
+
+ free(InFrames32);
+ free(OutFrames32);
+
+ return 0;
+} /* end process */
+
+//----------------------------------------------------------------------------
+// Reverb_free()
+//----------------------------------------------------------------------------
+// Purpose: Free all memory associated with the Bundle.
+//
+// Inputs:
+// pContext: effect engine context
+//
+// Outputs:
+//
+//----------------------------------------------------------------------------
+
+void Reverb_free(ReverbContext *pContext){
+
+ LVREV_ReturnStatus_en LvmStatus=LVREV_SUCCESS; /* Function call status */
+ LVREV_ControlParams_st params; /* Control Parameters */
+ LVREV_MemoryTable_st MemTab;
+
+ /* Free the algorithm memory */
+ LvmStatus = LVREV_GetMemoryTable(pContext->hInstance,
+ &MemTab,
+ LVM_NULL);
+
+ LVM_ERROR_CHECK(LvmStatus, "LVM_GetMemoryTable", "Reverb_free")
+
+ for (int i=0; i<LVM_NR_MEMORY_REGIONS; i++){
+ if (MemTab.Region[i].Size != 0){
+ if (MemTab.Region[i].pBaseAddress != NULL){
+ LOGV("\tfree() - START freeing %ld bytes for region %u at %p\n",
+ MemTab.Region[i].Size, i, MemTab.Region[i].pBaseAddress);
+
+ free(MemTab.Region[i].pBaseAddress);
+
+ LOGV("\tfree() - END freeing %ld bytes for region %u at %p\n",
+ MemTab.Region[i].Size, i, MemTab.Region[i].pBaseAddress);
+ }else{
+ LOGV("\tLVM_ERROR : free() - trying to free with NULL pointer %ld bytes "
+ "for region %u at %p ERROR\n",
+ MemTab.Region[i].Size, i, MemTab.Region[i].pBaseAddress);
+ }
+ }
+ }
+} /* end Reverb_free */
+
+//----------------------------------------------------------------------------
+// Reverb_configure()
+//----------------------------------------------------------------------------
+// Purpose: Set input and output audio configuration.
+//
+// Inputs:
+// pContext: effect engine context
+// pConfig: pointer to effect_config_t structure holding input and output
+// configuration parameters
+//
+// Outputs:
+//
+//----------------------------------------------------------------------------
+
+int Reverb_configure(ReverbContext *pContext, effect_config_t *pConfig){
+ LVM_Fs_en SampleRate;
+ //LOGV("\tReverb_configure start");
+
+ CHECK_ARG(pContext != NULL);
+ CHECK_ARG(pConfig != NULL);
+
+ CHECK_ARG(pConfig->inputCfg.samplingRate == pConfig->outputCfg.samplingRate);
+ CHECK_ARG(pConfig->inputCfg.format == pConfig->outputCfg.format);
+ CHECK_ARG((pContext->auxiliary && pConfig->inputCfg.channels == CHANNEL_MONO) ||
+ ((!pContext->auxiliary) && pConfig->inputCfg.channels == CHANNEL_STEREO));
+ CHECK_ARG(pConfig->outputCfg.channels == CHANNEL_STEREO);
+ CHECK_ARG(pConfig->outputCfg.accessMode == EFFECT_BUFFER_ACCESS_WRITE
+ || pConfig->outputCfg.accessMode == EFFECT_BUFFER_ACCESS_ACCUMULATE);
+ CHECK_ARG(pConfig->inputCfg.format == SAMPLE_FORMAT_PCM_S15);
+
+ if(pConfig->inputCfg.samplingRate != 44100){
+ return -EINVAL;
+ }
+
+ //LOGV("\tReverb_configure calling memcpy");
+ memcpy(&pContext->config, pConfig, sizeof(effect_config_t));
+
+ switch (pConfig->inputCfg.samplingRate) {
+ case 8000:
+ SampleRate = LVM_FS_8000;
+ break;
+ case 16000:
+ SampleRate = LVM_FS_16000;
+ break;
+ case 22050:
+ SampleRate = LVM_FS_22050;
+ break;
+ case 32000:
+ SampleRate = LVM_FS_32000;
+ break;
+ case 44100:
+ SampleRate = LVM_FS_44100;
+ break;
+ case 48000:
+ SampleRate = LVM_FS_48000;
+ break;
+ default:
+ LOGV("\rReverb_Configure invalid sampling rate %d", pConfig->inputCfg.samplingRate);
+ return -EINVAL;
+ }
+
+ if(pContext->SampleRate != SampleRate){
+
+ LVREV_ControlParams_st ActiveParams;
+ LVREV_ReturnStatus_en LvmStatus = LVREV_SUCCESS;
+
+ //LOGV("\tReverb_configure change sampling rate to %d", SampleRate);
+
+ /* Get the current settings */
+ LvmStatus = LVREV_GetControlParameters(pContext->hInstance,
+ &ActiveParams);
+
+ LVM_ERROR_CHECK(LvmStatus, "LVREV_GetControlParameters", "Reverb_configure")
+ if(LvmStatus != LVREV_SUCCESS) return -EINVAL;
+
+ LvmStatus = LVREV_SetControlParameters(pContext->hInstance, &ActiveParams);
+
+ LVM_ERROR_CHECK(LvmStatus, "LVREV_SetControlParameters", "Reverb_configure")
+ //LOGV("\tReverb_configure Succesfully called LVREV_SetControlParameters\n");
+
+ }else{
+ //LOGV("\tReverb_configure keep sampling rate at %d", SampleRate);
+ }
+
+ //LOGV("\tReverb_configure End");
+ return 0;
+} /* end Reverb_configure */
+
+
+//----------------------------------------------------------------------------
+// Reverb_init()
+//----------------------------------------------------------------------------
+// Purpose: Initialize engine with default configuration
+//
+// Inputs:
+// pContext: effect engine context
+//
+// Outputs:
+//
+//----------------------------------------------------------------------------
+
+int Reverb_init(ReverbContext *pContext){
+ int status;
+
+ LOGV("\tReverb_init start");
+
+ CHECK_ARG(pContext != NULL);
+
+ if (pContext->hInstance != NULL){
+ Reverb_free(pContext);
+ }
+
+ pContext->config.inputCfg.accessMode = EFFECT_BUFFER_ACCESS_READ;
+ if (pContext->auxiliary) {
+ pContext->config.inputCfg.channels = CHANNEL_MONO;
+ } else {
+ pContext->config.inputCfg.channels = CHANNEL_STEREO;
+ }
+
+ pContext->config.inputCfg.format = SAMPLE_FORMAT_PCM_S15;
+ pContext->config.inputCfg.samplingRate = 44100;
+ pContext->config.inputCfg.bufferProvider.getBuffer = NULL;
+ pContext->config.inputCfg.bufferProvider.releaseBuffer = NULL;
+ pContext->config.inputCfg.bufferProvider.cookie = NULL;
+ pContext->config.inputCfg.mask = EFFECT_CONFIG_ALL;
+ pContext->config.outputCfg.accessMode = EFFECT_BUFFER_ACCESS_ACCUMULATE;
+ pContext->config.outputCfg.channels = CHANNEL_STEREO;
+ pContext->config.outputCfg.format = SAMPLE_FORMAT_PCM_S15;
+ pContext->config.outputCfg.samplingRate = 44100;
+ pContext->config.outputCfg.bufferProvider.getBuffer = NULL;
+ pContext->config.outputCfg.bufferProvider.releaseBuffer = NULL;
+ pContext->config.outputCfg.bufferProvider.cookie = NULL;
+ pContext->config.outputCfg.mask = EFFECT_CONFIG_ALL;
+
+ LVREV_ReturnStatus_en LvmStatus=LVREV_SUCCESS; /* Function call status */
+ LVREV_ControlParams_st params; /* Control Parameters */
+ LVREV_InstanceParams_st InstParams; /* Instance parameters */
+ LVREV_MemoryTable_st MemTab; /* Memory allocation table */
+ bool bMallocFailure = LVM_FALSE;
+
+ /* Set the capabilities */
+ InstParams.MaxBlockSize = MAX_CALL_SIZE;
+ InstParams.SourceFormat = LVM_STEREO;
+ InstParams.NumDelays = LVREV_DELAYLINES_4;
+
+ /* Allocate memory, forcing alignment */
+ LvmStatus = LVREV_GetMemoryTable(LVM_NULL,
+ &MemTab,
+ &InstParams);
+
+ LVM_ERROR_CHECK(LvmStatus, "LVREV_GetMemoryTable", "Reverb_init")
+ if(LvmStatus != LVREV_SUCCESS) return -EINVAL;
+
+ LOGV("\tCreateInstance Succesfully called LVM_GetMemoryTable\n");
+
+ /* Allocate memory */
+ for (int i=0; i<LVM_NR_MEMORY_REGIONS; i++){
+ if (MemTab.Region[i].Size != 0){
+ MemTab.Region[i].pBaseAddress = malloc(MemTab.Region[i].Size);
+
+ if (MemTab.Region[i].pBaseAddress == LVM_NULL){
+ LOGV("\tLVREV_ERROR :Reverb_init CreateInstance Failed to allocate %ld bytes for region %u\n",
+ MemTab.Region[i].Size, i );
+ bMallocFailure = LVM_TRUE;
+ }else{
+ LOGV("\tReverb_init CreateInstance allocate %ld bytes for region %u at %p\n",
+ MemTab.Region[i].Size, i, MemTab.Region[i].pBaseAddress);
+ }
+ }
+ }
+
+ /* If one or more of the memory regions failed to allocate, free the regions that were
+ * succesfully allocated and return with an error
+ */
+ if(bMallocFailure == LVM_TRUE){
+ for (int i=0; i<LVM_NR_MEMORY_REGIONS; i++){
+ if (MemTab.Region[i].pBaseAddress == LVM_NULL){
+ LOGV("\tLVM_ERROR :Reverb_init CreateInstance Failed to allocate %ld bytes for region %u"
+ " - Not freeing\n", MemTab.Region[i].Size, i );
+ }else{
+ LOGV("\tLVM_ERROR :Reverb_init CreateInstance Failed: but allocated %ld bytes for region %u "
+ "at %p- free\n", MemTab.Region[i].Size, i, MemTab.Region[i].pBaseAddress);
+ free(MemTab.Region[i].pBaseAddress);
+ }
+ }
+ return -EINVAL;
+ }
+ LOGV("\tReverb_init CreateInstance Succesfully malloc'd memory\n");
+
+ /* Initialise */
+ pContext->hInstance = LVM_NULL;
+
+ /* Init sets the instance handle */
+ LvmStatus = LVREV_GetInstanceHandle(&pContext->hInstance,
+ &MemTab,
+ &InstParams);
+
+ LVM_ERROR_CHECK(LvmStatus, "LVM_GetInstanceHandle", "Reverb_init")
+ if(LvmStatus != LVREV_SUCCESS) return -EINVAL;
+
+ LOGV("\tReverb_init CreateInstance Succesfully called LVM_GetInstanceHandle\n");
+
+ /* Set the initial process parameters */
+ /* General parameters */
+ params.OperatingMode = LVM_MODE_ON;
+ params.SampleRate = LVM_FS_44100;
+ params.SourceFormat = LVM_STEREO;
+
+ /* Reverb parameters */
+ params.Level = 0;
+ params.LPF = 23999;
+ params.HPF = 50;
+ params.T60 = 1490;
+ params.Density = 100;
+ params.Damping = 21;
+ params.RoomSize = 100;
+
+ /* Saved strength is used to return the exact strength that was used in the set to the get
+ * because we map the original strength range of 0:1000 to 1:15, and this will avoid
+ * quantisation like effect when returning
+ */
+ pContext->SavedRoomLevel = -6000;
+ pContext->SavedHfLevel = 0;
+ pContext->bEnabled = LVM_FALSE;
+ pContext->SavedDecayTime = params.T60;
+ pContext->SavedDecayHfRatio = params.Damping*10;
+ pContext->SavedDensity = params.RoomSize*10;
+ pContext->SavedDiffusion = params.Density*10;
+ pContext->SavedReverbLevel = -6000;
+
+ /* Activate the initial settings */
+ LvmStatus = LVREV_SetControlParameters(pContext->hInstance,
+ ¶ms);
+
+ LVM_ERROR_CHECK(LvmStatus, "LVREV_SetControlParameters", "Reverb_init")
+ if(LvmStatus != LVREV_SUCCESS) return -EINVAL;
+
+ LOGV("\tReverb_init CreateInstance Succesfully called LVREV_SetControlParameters\n");
+ LOGV("\tReverb_init End");
+ return 0;
+} /* end Reverb_init */
+
+//----------------------------------------------------------------------------
+// ReverbConvertLevel()
+//----------------------------------------------------------------------------
+// Purpose:
+// Convert level from OpenSL ES format to LVM format
+//
+// Inputs:
+// level level to be applied
+//
+//----------------------------------------------------------------------------
+
+int16_t ReverbConvertLevel(int16_t level){
+ static int16_t LevelArray[101] =
+ {
+ -12000, -4000, -3398, -3046, -2796, -2603, -2444, -2310, -2194, -2092,
+ -2000, -1918, -1842, -1773, -1708, -1648, -1592, -1540, -1490, -1443,
+ -1398, -1356, -1316, -1277, -1240, -1205, -1171, -1138, -1106, -1076,
+ -1046, -1018, -990, -963, -938, -912, -888, -864, -841, -818,
+ -796, -775, -754, -734, -714, -694, -675, -656, -638, -620,
+ -603, -585, -568, -552, -536, -520, -504, -489, -474, -459,
+ -444, -430, -416, -402, -388, -375, -361, -348, -335, -323,
+ -310, -298, -286, -274, -262, -250, -239, -228, -216, -205,
+ -194, -184, -173, -162, -152, -142, -132, -121, -112, -102,
+ -92, -82, -73, -64, -54, -45, -36, -27, -18, -9,
+ 0
+ };
+ int16_t i;
+
+ for(i = 0; i < 101; i++)
+ {
+ if(level <= LevelArray[i])
+ break;
+ }
+ return i;
+}
+
+//----------------------------------------------------------------------------
+// ReverbConvertHFLevel()
+//----------------------------------------------------------------------------
+// Purpose:
+// Convert level from OpenSL ES format to LVM format
+//
+// Inputs:
+// level level to be applied
+//
+//----------------------------------------------------------------------------
+
+int16_t ReverbConvertHfLevel(int16_t Hflevel){
+ int16_t i;
+
+ static LPFPair_t LPFArray[97] =
+ { // Limit range to 50 for LVREV parameter range
+ {-10000, 50}, { -5000, 50 }, { -4000, 50}, { -3000, 158}, { -2000, 502},
+ {-1000, 1666},{ -900, 1897}, { -800, 2169}, { -700, 2496}, { -600, 2895},
+ {-500, 3400}, { -400, 4066}, { -300, 5011}, { -200, 6537}, { -100, 9826},
+ {-99, 9881 }, { -98, 9937 }, { -97, 9994 }, { -96, 10052}, { -95, 10111},
+ {-94, 10171}, { -93, 10231}, { -92, 10293}, { -91, 10356}, { -90, 10419},
+ {-89, 10484}, { -88, 10549}, { -87, 10616}, { -86, 10684}, { -85, 10753},
+ {-84, 10823}, { -83, 10895}, { -82, 10968}, { -81, 11042}, { -80, 11117},
+ {-79, 11194}, { -78, 11272}, { -77, 11352}, { -76, 11433}, { -75, 11516},
+ {-74, 11600}, { -73, 11686}, { -72, 11774}, { -71, 11864}, { -70, 11955},
+ {-69, 12049}, { -68, 12144}, { -67, 12242}, { -66, 12341}, { -65, 12443},
+ {-64, 12548}, { -63, 12654}, { -62, 12763}, { -61, 12875}, { -60, 12990},
+ {-59, 13107}, { -58, 13227}, { -57, 13351}, { -56, 13477}, { -55, 13607},
+ {-54, 13741}, { -53, 13878}, { -52, 14019}, { -51, 14164}, { -50, 14313},
+ {-49, 14467}, { -48, 14626}, { -47, 14789}, { -46, 14958}, { -45, 15132},
+ {-44, 15312}, { -43, 15498}, { -42, 15691}, { -41, 15890}, { -40, 16097},
+ {-39, 16311}, { -38, 16534}, { -37, 16766}, { -36, 17007}, { -35, 17259},
+ {-34, 17521}, { -33, 17795}, { -32, 18081}, { -31, 18381}, { -30, 18696},
+ {-29, 19027}, { -28, 19375}, { -27, 19742}, { -26, 20129}, { -25, 20540},
+ {-24, 20976}, { -23, 21439}, { -22, 21934}, { -21, 22463}, { -20, 23031},
+ {-19, 23643}, { -18, 23999}
+ };
+
+ for(i = 0; i < 96; i++)
+ {
+ if(Hflevel <= LPFArray[i].Room_HF)
+ break;
+ }
+ return LPFArray[i].LPF;
+}
+
+//----------------------------------------------------------------------------
+// ReverbSetRoomHfLevel()
+//----------------------------------------------------------------------------
+// Purpose:
+// Apply the HF level to the Reverb. Must first be converted to LVM format
+//
+// Inputs:
+// pContext: effect engine context
+// level level to be applied
+//
+//----------------------------------------------------------------------------
+
+void ReverbSetRoomHfLevel(ReverbContext *pContext, int16_t level){
+ //LOGV("\tReverbSetRoomHfLevel start (%d)", level);
+
+ LVREV_ControlParams_st ActiveParams; /* Current control Parameters */
+ LVREV_ReturnStatus_en LvmStatus=LVREV_SUCCESS; /* Function call status */
+
+ /* Get the current settings */
+ LvmStatus = LVREV_GetControlParameters(pContext->hInstance, &ActiveParams);
+ LVM_ERROR_CHECK(LvmStatus, "LVREV_GetControlParameters", "ReverbSetRoomHfLevel")
+ //LOGV("\tReverbSetRoomHfLevel Succesfully returned from LVM_GetControlParameters\n");
+ //LOGV("\tReverbSetRoomHfLevel() just Got -> %d\n", ActiveParams.LPF);
+
+ ActiveParams.LPF = ReverbConvertHfLevel(level);
+
+ /* Activate the initial settings */
+ LvmStatus = LVREV_SetControlParameters(pContext->hInstance, &ActiveParams);
+ LVM_ERROR_CHECK(LvmStatus, "LVREV_SetControlParameters", "ReverbSetRoomHfLevel")
+ //LOGV("\tReverbSetRoomhfLevel() just Set -> %d\n", ActiveParams.LPF);
+ pContext->SavedHfLevel = level;
+ //LOGV("\tReverbSetHfRoomLevel end.. saving %d", pContext->SavedHfLevel);
+ return;
+}
+
+//----------------------------------------------------------------------------
+// ReverbGetRoomHfLevel()
+//----------------------------------------------------------------------------
+// Purpose:
+// Get the level applied to the Revervb. Must first be converted to LVM format
+//
+// Inputs:
+// pContext: effect engine context
+//
+//----------------------------------------------------------------------------
+
+int16_t ReverbGetRoomHfLevel(ReverbContext *pContext){
+ int16_t level;
+ //LOGV("\tReverbGetRoomHfLevel start, saved level is %d", pContext->SavedHfLevel);
+
+ LVREV_ControlParams_st ActiveParams; /* Current control Parameters */
+ LVREV_ReturnStatus_en LvmStatus=LVREV_SUCCESS; /* Function call status */
+
+ /* Get the current settings */
+ LvmStatus = LVREV_GetControlParameters(pContext->hInstance, &ActiveParams);
+ LVM_ERROR_CHECK(LvmStatus, "LVREV_GetControlParameters", "ReverbGetRoomHfLevel")
+ //LOGV("\tReverbGetRoomHfLevel Succesfully returned from LVM_GetControlParameters\n");
+ //LOGV("\tReverbGetRoomHfLevel() just Got -> %d\n", ActiveParams.LPF);
+
+ level = ReverbConvertHfLevel(pContext->SavedHfLevel);
+
+ //LOGV("\tReverbGetRoomHfLevel() ActiveParams.LPFL %d, pContext->SavedHfLevel: %d, "
+ // "converted level: %d\n", ActiveParams.LPF, pContext->SavedHfLevel, level);
+
+ if(ActiveParams.LPF != level){
+ LOGV("\tLVM_ERROR : (ignore at start up) ReverbGetRoomHfLevel() has wrong level -> %d %d\n",
+ ActiveParams.Level, level);
+ }
+
+ //LOGV("\tReverbGetRoomHfLevel end");
+ return pContext->SavedHfLevel;
+}
+
+//----------------------------------------------------------------------------
+// ReverbSetReverbLevel()
+//----------------------------------------------------------------------------
+// Purpose:
+// Apply the level to the Reverb. Must first be converted to LVM format
+//
+// Inputs:
+// pContext: effect engine context
+// level level to be applied
+//
+//----------------------------------------------------------------------------
+
+void ReverbSetReverbLevel(ReverbContext *pContext, int16_t level){
+ //LOGV("\n\tReverbSetReverbLevel start (%d)", level);
+
+ LVREV_ControlParams_st ActiveParams; /* Current control Parameters */
+ LVREV_ReturnStatus_en LvmStatus=LVREV_SUCCESS; /* Function call status */
+ LVM_INT32 CombinedLevel; // Sum of room and reverb level controls
+
+ /* Get the current settings */
+ LvmStatus = LVREV_GetControlParameters(pContext->hInstance, &ActiveParams);
+ LVM_ERROR_CHECK(LvmStatus, "LVREV_GetControlParameters", "ReverbSetReverbLevel")
+ //LOGV("\tReverbSetReverbLevel Succesfully returned from LVM_GetControlParameters\n");
+ //LOGV("\tReverbSetReverbLevel just Got -> %d\n", ActiveParams.Level);
+
+ // needs to subtract max levels for both RoomLevel and ReverbLevel
+ CombinedLevel = (level + pContext->SavedRoomLevel)-LVREV_MAX_REVERB_LEVEL;
+ //LOGV("\tReverbSetReverbLevel() CombinedLevel is %d = %d + %d\n",
+ // CombinedLevel, level, pContext->SavedRoomLevel);
+
+ ActiveParams.Level = ReverbConvertLevel(CombinedLevel);
+
+ //LOGV("\tReverbSetReverbLevel() Trying to set -> %d\n", ActiveParams.Level);
+
+ /* Activate the initial settings */
+ LvmStatus = LVREV_SetControlParameters(pContext->hInstance, &ActiveParams);
+ LVM_ERROR_CHECK(LvmStatus, "LVREV_SetControlParameters", "ReverbSetReverbLevel")
+ //LOGV("\tReverbSetReverbLevel() just Set -> %d\n", ActiveParams.Level);
+
+ pContext->SavedReverbLevel = level;
+ //LOGV("\tReverbSetReverbLevel end pContext->SavedReverbLevel is %d\n\n",
+ // pContext->SavedReverbLevel);
+ return;
+}
+
+//----------------------------------------------------------------------------
+// ReverbGetReverbLevel()
+//----------------------------------------------------------------------------
+// Purpose:
+// Get the level applied to the Revervb. Must first be converted to LVM format
+//
+// Inputs:
+// pContext: effect engine context
+//
+//----------------------------------------------------------------------------
+
+int16_t ReverbGetReverbLevel(ReverbContext *pContext){
+ int16_t level;
+ //LOGV("\tReverbGetReverbLevel start");
+
+ LVREV_ControlParams_st ActiveParams; /* Current control Parameters */
+ LVREV_ReturnStatus_en LvmStatus=LVREV_SUCCESS; /* Function call status */
+ LVM_INT32 CombinedLevel; // Sum of room and reverb level controls
+
+ /* Get the current settings */
+ LvmStatus = LVREV_GetControlParameters(pContext->hInstance, &ActiveParams);
+ LVM_ERROR_CHECK(LvmStatus, "LVREV_GetControlParameters", "ReverbGetReverbLevel")
+ //LOGV("\tReverbGetReverbLevel Succesfully returned from LVM_GetControlParameters\n");
+ //LOGV("\tReverbGetReverbLevel() just Got -> %d\n", ActiveParams.Level);
+
+ // needs to subtract max levels for both RoomLevel and ReverbLevel
+ CombinedLevel = (pContext->SavedReverbLevel + pContext->SavedRoomLevel)-LVREV_MAX_REVERB_LEVEL;
+
+ //LOGV("\tReverbGetReverbLevel() CombinedLevel is %d = %d + %d\n",
+ //CombinedLevel, pContext->SavedReverbLevel, pContext->SavedRoomLevel);
+ level = ReverbConvertLevel(CombinedLevel);
+
+ //LOGV("\tReverbGetReverbLevel(): ActiveParams.Level: %d, pContext->SavedReverbLevel: %d, "
+ //"pContext->SavedRoomLevel: %d, CombinedLevel: %d, converted level: %d\n",
+ //ActiveParams.Level, pContext->SavedReverbLevel,pContext->SavedRoomLevel, CombinedLevel,level);
+
+ if(ActiveParams.Level != level){
+ LOGV("\tLVM_ERROR : (ignore at start up) ReverbGetReverbLevel() has wrong level -> %d %d\n",
+ ActiveParams.Level, level);
+ }
+
+ //LOGV("\tReverbGetReverbLevel end\n");
+
+ return pContext->SavedReverbLevel;
+}
+
+//----------------------------------------------------------------------------
+// ReverbSetRoomLevel()
+//----------------------------------------------------------------------------
+// Purpose:
+// Apply the level to the Reverb. Must first be converted to LVM format
+//
+// Inputs:
+// pContext: effect engine context
+// level level to be applied
+//
+//----------------------------------------------------------------------------
+
+void ReverbSetRoomLevel(ReverbContext *pContext, int16_t level){
+ //LOGV("\tReverbSetRoomLevel start (%d)", level);
+
+ LVREV_ControlParams_st ActiveParams; /* Current control Parameters */
+ LVREV_ReturnStatus_en LvmStatus=LVREV_SUCCESS; /* Function call status */
+ LVM_INT32 CombinedLevel; // Sum of room and reverb level controls
+
+ /* Get the current settings */
+ LvmStatus = LVREV_GetControlParameters(pContext->hInstance, &ActiveParams);
+ LVM_ERROR_CHECK(LvmStatus, "LVREV_GetControlParameters", "ReverbSetRoomLevel")
+ //LOGV("\tReverbSetRoomLevel Succesfully returned from LVM_GetControlParameters\n");
+ //LOGV("\tReverbSetRoomLevel() just Got -> %d\n", ActiveParams.Level);
+
+ // needs to subtract max levels for both RoomLevel and ReverbLevel
+ CombinedLevel = (level + pContext->SavedReverbLevel)-LVREV_MAX_REVERB_LEVEL;
+ ActiveParams.Level = ReverbConvertLevel(CombinedLevel);
+
+ /* Activate the initial settings */
+ LvmStatus = LVREV_SetControlParameters(pContext->hInstance, &ActiveParams);
+ LVM_ERROR_CHECK(LvmStatus, "LVREV_SetControlParameters", "ReverbSetRoomLevel")
+ //LOGV("\tReverbSetRoomLevel() just Set -> %d\n", ActiveParams.Level);
+
+ pContext->SavedRoomLevel = level;
+ //LOGV("\tReverbSetRoomLevel end");
+ return;
+}
+
+//----------------------------------------------------------------------------
+// ReverbGetRoomLevel()
+//----------------------------------------------------------------------------
+// Purpose:
+// Get the level applied to the Revervb. Must first be converted to LVM format
+//
+// Inputs:
+// pContext: effect engine context
+//
+//----------------------------------------------------------------------------
+
+int16_t ReverbGetRoomLevel(ReverbContext *pContext){
+ int16_t level;
+ //LOGV("\tReverbGetRoomLevel start");
+
+ LVREV_ControlParams_st ActiveParams; /* Current control Parameters */
+ LVREV_ReturnStatus_en LvmStatus=LVREV_SUCCESS; /* Function call status */
+ LVM_INT32 CombinedLevel; // Sum of room and reverb level controls
+
+ /* Get the current settings */
+ LvmStatus = LVREV_GetControlParameters(pContext->hInstance, &ActiveParams);
+ LVM_ERROR_CHECK(LvmStatus, "LVREV_GetControlParameters", "ReverbGetRoomLevel")
+ //LOGV("\tReverbGetRoomLevel Succesfully returned from LVM_GetControlParameters\n");
+ //LOGV("\tReverbGetRoomLevel() just Got -> %d\n", ActiveParams.Level);
+
+ // needs to subtract max levels for both RoomLevel and ReverbLevel
+ CombinedLevel = (pContext->SavedRoomLevel + pContext->SavedReverbLevel-LVREV_MAX_REVERB_LEVEL);
+ level = ReverbConvertLevel(CombinedLevel);
+
+ //LOGV("\tReverbGetRoomLevel, Level = %d, pContext->SavedRoomLevel = %d, "
+ // "pContext->SavedReverbLevel = %d, CombinedLevel = %d, level = %d",
+ //ActiveParams.Level, pContext->SavedRoomLevel, pContext->SavedReverbLevel, CombinedLevel, level);
+
+ if(ActiveParams.Level != level){
+ LOGV("\tLVM_ERROR : (ignore at start up) ReverbGetRoomLevel() has wrong level -> %d %d\n",
+ ActiveParams.Level, level);
+ }
+
+ //LOGV("\tReverbGetRoomLevel end");
+ return pContext->SavedRoomLevel;
+}
+
+//----------------------------------------------------------------------------
+// ReverbSetDecayTime()
+//----------------------------------------------------------------------------
+// Purpose:
+// Apply the decay time to the Reverb.
+//
+// Inputs:
+// pContext: effect engine context
+// time decay to be applied
+//
+//----------------------------------------------------------------------------
+
+void ReverbSetDecayTime(ReverbContext *pContext, uint32_t time){
+ //LOGV("\tReverbSetDecayTime start (%d)", time);
+
+ LVREV_ControlParams_st ActiveParams; /* Current control Parameters */
+ LVREV_ReturnStatus_en LvmStatus=LVREV_SUCCESS; /* Function call status */
+
+ /* Get the current settings */
+ LvmStatus = LVREV_GetControlParameters(pContext->hInstance, &ActiveParams);
+ LVM_ERROR_CHECK(LvmStatus, "LVREV_GetControlParameters", "ReverbSetDecayTime")
+ //LOGV("\tReverbSetDecayTime Succesfully returned from LVM_GetControlParameters\n");
+ //LOGV("\tReverbSetDecayTime() just Got -> %d\n", ActiveParams.T60);
+
+ if (time <= LVREV_MAX_T60) {
+ ActiveParams.T60 = time;
+ }
+ else {
+ ActiveParams.T60 = LVREV_MAX_T60;
+ }
+
+ /* Activate the initial settings */
+ LvmStatus = LVREV_SetControlParameters(pContext->hInstance, &ActiveParams);
+ LVM_ERROR_CHECK(LvmStatus, "LVREV_SetControlParameters", "ReverbSetDecayTime")
+ //LOGV("\tReverbSetDecayTime() just Set -> %d\n", ActiveParams.T60);
+
+ pContext->SavedDecayTime = time;
+ //LOGV("\tReverbSetDecayTime end");
+ return;
+}
+
+//----------------------------------------------------------------------------
+// ReverbGetDecayTime()
+//----------------------------------------------------------------------------
+// Purpose:
+// Get the decay time applied to the Revervb.
+//
+// Inputs:
+// pContext: effect engine context
+//
+//----------------------------------------------------------------------------
+
+int32_t ReverbGetDecayTime(ReverbContext *pContext){
+ //LOGV("\tReverbGetDecayTime start");
+
+ LVREV_ControlParams_st ActiveParams; /* Current control Parameters */
+ LVREV_ReturnStatus_en LvmStatus=LVREV_SUCCESS; /* Function call status */
+
+ /* Get the current settings */
+ LvmStatus = LVREV_GetControlParameters(pContext->hInstance, &ActiveParams);
+ LVM_ERROR_CHECK(LvmStatus, "LVREV_GetControlParameters", "ReverbGetDecayTime")
+ //LOGV("\tReverbGetDecayTime Succesfully returned from LVM_GetControlParameters\n");
+ //LOGV("\tReverbGetDecayTime() just Got -> %d\n", ActiveParams.T60);
+
+ if(ActiveParams.T60 != pContext->SavedDecayTime){
+ // This will fail if the decay time is set to more than 7000
+ LOGV("\tLVM_ERROR : ReverbGetDecayTime() has wrong level -> %d %d\n",
+ ActiveParams.T60, pContext->SavedDecayTime);
+ }
+
+ //LOGV("\tReverbGetDecayTime end");
+ return ActiveParams.T60;
+}
+
+//----------------------------------------------------------------------------
+// ReverbSetDecayHfRatio()
+//----------------------------------------------------------------------------
+// Purpose:
+// Apply the HF decay ratio to the Reverb.
+//
+// Inputs:
+// pContext: effect engine context
+// ratio ratio to be applied
+//
+//----------------------------------------------------------------------------
+
+void ReverbSetDecayHfRatio(ReverbContext *pContext, int16_t ratio){
+ //LOGV("\tReverbSetDecayHfRatioe start (%d)", ratio);
+
+ LVREV_ControlParams_st ActiveParams; /* Current control Parameters */
+ LVREV_ReturnStatus_en LvmStatus=LVREV_SUCCESS; /* Function call status */
+
+ /* Get the current settings */
+ LvmStatus = LVREV_GetControlParameters(pContext->hInstance, &ActiveParams);
+ LVM_ERROR_CHECK(LvmStatus, "LVREV_GetControlParameters", "ReverbSetDecayHfRatio")
+ //LOGV("\tReverbSetDecayHfRatio Succesfully returned from LVM_GetControlParameters\n");
+ //LOGV("\tReverbSetDecayHfRatio() just Got -> %d\n", ActiveParams.Damping);
+
+ ActiveParams.Damping = (LVM_INT16)(ratio/10);
+
+ /* Activate the initial settings */
+ LvmStatus = LVREV_SetControlParameters(pContext->hInstance, &ActiveParams);
+ LVM_ERROR_CHECK(LvmStatus, "LVREV_SetControlParameters", "ReverbSetDecayHfRatio")
+ //LOGV("\tReverbSetDecayHfRatio() just Set -> %d\n", ActiveParams.Damping);
+
+ pContext->SavedDecayHfRatio = ratio;
+ //LOGV("\tReverbSetDecayHfRatio end");
+ return;
+}
+
+//----------------------------------------------------------------------------
+// ReverbGetDecayHfRatio()
+//----------------------------------------------------------------------------
+// Purpose:
+// Get the HF decay ratio applied to the Revervb.
+//
+// Inputs:
+// pContext: effect engine context
+//
+//----------------------------------------------------------------------------
+
+int32_t ReverbGetDecayHfRatio(ReverbContext *pContext){
+ //LOGV("\tReverbGetDecayHfRatio start");
+
+ LVREV_ControlParams_st ActiveParams; /* Current control Parameters */
+ LVREV_ReturnStatus_en LvmStatus=LVREV_SUCCESS; /* Function call status */
+
+ /* Get the current settings */
+ LvmStatus = LVREV_GetControlParameters(pContext->hInstance, &ActiveParams);
+ LVM_ERROR_CHECK(LvmStatus, "LVREV_GetControlParameters", "ReverbGetDecayHfRatio")
+ //LOGV("\tReverbGetDecayHfRatio Succesfully returned from LVM_GetControlParameters\n");
+ //LOGV("\tReverbGetDecayHfRatio() just Got -> %d\n", ActiveParams.Damping);
+
+ if(ActiveParams.Damping != (LVM_INT16)(pContext->SavedDecayHfRatio / 10)){
+ LOGV("\tLVM_ERROR : ReverbGetDecayHfRatio() has wrong level -> %d %d\n",
+ ActiveParams.Damping, pContext->SavedDecayHfRatio);
+ }
+
+ //LOGV("\tReverbGetDecayHfRatio end");
+ return pContext->SavedDecayHfRatio;
+}
+
+//----------------------------------------------------------------------------
+// ReverbSetDiffusion()
+//----------------------------------------------------------------------------
+// Purpose:
+// Apply the diffusion to the Reverb.
+//
+// Inputs:
+// pContext: effect engine context
+// level decay to be applied
+//
+//----------------------------------------------------------------------------
+
+void ReverbSetDiffusion(ReverbContext *pContext, int16_t level){
+ //LOGV("\tReverbSetDiffusion start (%d)", level);
+
+ LVREV_ControlParams_st ActiveParams; /* Current control Parameters */
+ LVREV_ReturnStatus_en LvmStatus=LVREV_SUCCESS; /* Function call status */
+
+ /* Get the current settings */
+ LvmStatus = LVREV_GetControlParameters(pContext->hInstance, &ActiveParams);
+ LVM_ERROR_CHECK(LvmStatus, "LVREV_GetControlParameters", "ReverbSetDiffusion")
+ //LOGV("\tReverbSetDiffusion Succesfully returned from LVM_GetControlParameters\n");
+ //LOGV("\tReverbSetDiffusion() just Got -> %d\n", ActiveParams.Density);
+
+ ActiveParams.Density = (LVM_INT16)(level/10);
+
+ /* Activate the initial settings */
+ LvmStatus = LVREV_SetControlParameters(pContext->hInstance, &ActiveParams);
+ LVM_ERROR_CHECK(LvmStatus, "LVREV_SetControlParameters", "ReverbSetDiffusion")
+ //LOGV("\tReverbSetDiffusion() just Set -> %d\n", ActiveParams.Density);
+
+ pContext->SavedDiffusion = level;
+ //LOGV("\tReverbSetDiffusion end");
+ return;
+}
+
+//----------------------------------------------------------------------------
+// ReverbGetDiffusion()
+//----------------------------------------------------------------------------
+// Purpose:
+// Get the decay time applied to the Revervb.
+//
+// Inputs:
+// pContext: effect engine context
+//
+//----------------------------------------------------------------------------
+
+int32_t ReverbGetDiffusion(ReverbContext *pContext){
+ //LOGV("\tReverbGetDiffusion start");
+
+ LVREV_ControlParams_st ActiveParams; /* Current control Parameters */
+ LVREV_ReturnStatus_en LvmStatus=LVREV_SUCCESS; /* Function call status */
+ LVM_INT16 Temp;
+
+ /* Get the current settings */
+ LvmStatus = LVREV_GetControlParameters(pContext->hInstance, &ActiveParams);
+ LVM_ERROR_CHECK(LvmStatus, "LVREV_GetControlParameters", "ReverbGetDiffusion")
+ //LOGV("\tReverbGetDiffusion Succesfully returned from LVM_GetControlParameters\n");
+ //LOGV("\tReverbGetDiffusion just Got -> %d\n", ActiveParams.Density);
+
+ Temp = (LVM_INT16)(pContext->SavedDiffusion/10);
+
+ if(ActiveParams.Density != Temp){
+ LOGV("\tLVM_ERROR : ReverbGetDiffusion invalid value %d %d", Temp, ActiveParams.Density);
+ }
+
+ //LOGV("\tReverbGetDiffusion end");
+ return pContext->SavedDiffusion;
+}
+
+//----------------------------------------------------------------------------
+// ReverbSetDensity()
+//----------------------------------------------------------------------------
+// Purpose:
+// Apply the density level the Reverb.
+//
+// Inputs:
+// pContext: effect engine context
+// level decay to be applied
+//
+//----------------------------------------------------------------------------
+
+void ReverbSetDensity(ReverbContext *pContext, int16_t level){
+ //LOGV("\tReverbSetDensity start (%d)", level);
+
+ LVREV_ControlParams_st ActiveParams; /* Current control Parameters */
+ LVREV_ReturnStatus_en LvmStatus=LVREV_SUCCESS; /* Function call status */
+
+ /* Get the current settings */
+ LvmStatus = LVREV_GetControlParameters(pContext->hInstance, &ActiveParams);
+ LVM_ERROR_CHECK(LvmStatus, "LVREV_GetControlParameters", "ReverbSetDensity")
+ //LOGV("\tReverbSetDensity Succesfully returned from LVM_GetControlParameters\n");
+ //LOGV("\tReverbSetDensity just Got -> %d\n", ActiveParams.RoomSize);
+
+ ActiveParams.RoomSize = (LVM_INT16)(((level * 99) / 1000) + 1);
+
+ /* Activate the initial settings */
+ LvmStatus = LVREV_SetControlParameters(pContext->hInstance, &ActiveParams);
+ LVM_ERROR_CHECK(LvmStatus, "LVREV_SetControlParameters", "ReverbSetDensity")
+ //LOGV("\tReverbSetDensity just Set -> %d\n", ActiveParams.RoomSize);
+
+ pContext->SavedDensity = level;
+ //LOGV("\tReverbSetDensity end");
+ return;
+}
+
+//----------------------------------------------------------------------------
+// ReverbGetDensity()
+//----------------------------------------------------------------------------
+// Purpose:
+// Get the density level applied to the Revervb.
+//
+// Inputs:
+// pContext: effect engine context
+//
+//----------------------------------------------------------------------------
+
+int32_t ReverbGetDensity(ReverbContext *pContext){
+ //LOGV("\tReverbGetDensity start");
+
+ LVREV_ControlParams_st ActiveParams; /* Current control Parameters */
+ LVREV_ReturnStatus_en LvmStatus=LVREV_SUCCESS; /* Function call status */
+ LVM_INT16 Temp;
+ /* Get the current settings */
+ LvmStatus = LVREV_GetControlParameters(pContext->hInstance, &ActiveParams);
+ LVM_ERROR_CHECK(LvmStatus, "LVREV_GetControlParameters", "ReverbGetDensity")
+ //LOGV("\tReverbGetDensity Succesfully returned from LVM_GetControlParameters\n");
+ //LOGV("\tReverbGetDensity() just Got -> %d\n", ActiveParams.RoomSize);
+
+
+ Temp = (LVM_INT16)(((pContext->SavedDensity * 99) / 1000) + 1);
+
+ if(Temp != ActiveParams.RoomSize){
+ LOGV("\tLVM_ERROR : ReverbGetDensity invalid value %d %d", Temp, ActiveParams.RoomSize);
+ }
+
+ //LOGV("\tReverbGetDensity end");
+ return pContext->SavedDensity;
+}
+
+//----------------------------------------------------------------------------
+// Reverb_LoadPreset()
+//----------------------------------------------------------------------------
+// Purpose:
+// Load a the next preset
+//
+// Inputs:
+// pContext - handle to instance data
+//
+// Outputs:
+//
+// Side Effects:
+//
+//----------------------------------------------------------------------------
+int Reverb_LoadPreset(ReverbContext *pContext)
+{
+ //TODO: add reflections delay, level and reverb delay when early reflections are
+ // implemented
+ pContext->curPreset = pContext->nextPreset;
+
+ if (pContext->curPreset != REVERB_PRESET_NONE) {
+ const t_reverb_settings *preset = &sReverbPresets[pContext->curPreset];
+ ReverbSetRoomLevel(pContext, preset->roomLevel);
+ ReverbSetRoomHfLevel(pContext, preset->roomHFLevel);
+ ReverbSetDecayTime(pContext, preset->decayTime);
+ ReverbSetDecayHfRatio(pContext, preset->decayHFRatio);
+ //reflectionsLevel
+ //reflectionsDelay
+ ReverbSetReverbLevel(pContext, preset->reverbLevel);
+ // reverbDelay
+ ReverbSetDiffusion(pContext, preset->diffusion);
+ ReverbSetDensity(pContext, preset->density);
+ }
+
+ return 0;
+}
+
+
+//----------------------------------------------------------------------------
+// Reverb_getParameter()
+//----------------------------------------------------------------------------
+// Purpose:
+// Get a Reverb parameter
+//
+// Inputs:
+// pContext - handle to instance data
+// pParam - pointer to parameter
+// pValue - pointer to variable to hold retrieved value
+// pValueSize - pointer to value size: maximum size as input
+//
+// Outputs:
+// *pValue updated with parameter value
+// *pValueSize updated with actual value size
+//
+//
+// Side Effects:
+//
+//----------------------------------------------------------------------------
+
+int Reverb_getParameter(ReverbContext *pContext,
+ void *pParam,
+ size_t *pValueSize,
+ void *pValue){
+ int status = 0;
+ int32_t *pParamTemp = (int32_t *)pParam;
+ int32_t param = *pParamTemp++;
+ char *name;
+ t_reverb_settings *pProperties;
+
+ //LOGV("\tReverb_getParameter start");
+ if (pContext->preset) {
+ if (param != REVERB_PARAM_PRESET || *pValueSize < sizeof(uint16_t)) {
+ return -EINVAL;
+ }
+
+ *(uint16_t *)pValue = pContext->nextPreset;
+ LOGV("get REVERB_PARAM_PRESET, preset %d", pContext->nextPreset);
+ return 0;
+ }
+
+ switch (param){
+ case REVERB_PARAM_ROOM_LEVEL:
+ if (*pValueSize != sizeof(int16_t)){
+ LOGV("\tLVM_ERROR : Reverb_getParameter() invalid pValueSize1 %d", *pValueSize);
+ return -EINVAL;
+ }
+ *pValueSize = sizeof(int16_t);
+ break;
+ case REVERB_PARAM_ROOM_HF_LEVEL:
+ if (*pValueSize != sizeof(int16_t)){
+ LOGV("\tLVM_ERROR : Reverb_getParameter() invalid pValueSize12 %d", *pValueSize);
+ return -EINVAL;
+ }
+ *pValueSize = sizeof(int16_t);
+ break;
+ case REVERB_PARAM_DECAY_TIME:
+ if (*pValueSize != sizeof(uint32_t)){
+ LOGV("\tLVM_ERROR : Reverb_getParameter() invalid pValueSize3 %d", *pValueSize);
+ return -EINVAL;
+ }
+ *pValueSize = sizeof(uint32_t);
+ break;
+ case REVERB_PARAM_DECAY_HF_RATIO:
+ if (*pValueSize != sizeof(int16_t)){
+ LOGV("\tLVM_ERROR : Reverb_getParameter() invalid pValueSize4 %d", *pValueSize);
+ return -EINVAL;
+ }
+ *pValueSize = sizeof(int16_t);
+ break;
+ case REVERB_PARAM_REFLECTIONS_LEVEL:
+ if (*pValueSize != sizeof(int16_t)){
+ LOGV("\tLVM_ERROR : Reverb_getParameter() invalid pValueSize5 %d", *pValueSize);
+ return -EINVAL;
+ }
+ *pValueSize = sizeof(int16_t);
+ break;
+ case REVERB_PARAM_REFLECTIONS_DELAY:
+ if (*pValueSize != sizeof(uint32_t)){
+ LOGV("\tLVM_ERROR : Reverb_getParameter() invalid pValueSize6 %d", *pValueSize);
+ return -EINVAL;
+ }
+ *pValueSize = sizeof(uint32_t);
+ break;
+ case REVERB_PARAM_REVERB_LEVEL:
+ if (*pValueSize != sizeof(int16_t)){
+ LOGV("\tLVM_ERROR : Reverb_getParameter() invalid pValueSize7 %d", *pValueSize);
+ return -EINVAL;
+ }
+ *pValueSize = sizeof(int16_t);
+ break;
+ case REVERB_PARAM_REVERB_DELAY:
+ if (*pValueSize != sizeof(uint32_t)){
+ LOGV("\tLVM_ERROR : Reverb_getParameter() invalid pValueSize8 %d", *pValueSize);
+ return -EINVAL;
+ }
+ *pValueSize = sizeof(uint32_t);
+ break;
+ case REVERB_PARAM_DIFFUSION:
+ if (*pValueSize != sizeof(int16_t)){
+ LOGV("\tLVM_ERROR : Reverb_getParameter() invalid pValueSize9 %d", *pValueSize);
+ return -EINVAL;
+ }
+ *pValueSize = sizeof(int16_t);
+ break;
+ case REVERB_PARAM_DENSITY:
+ if (*pValueSize != sizeof(int16_t)){
+ LOGV("\tLVM_ERROR : Reverb_getParameter() invalid pValueSize10 %d", *pValueSize);
+ return -EINVAL;
+ }
+ *pValueSize = sizeof(int16_t);
+ break;
+ case REVERB_PARAM_PROPERTIES:
+ if (*pValueSize != sizeof(t_reverb_settings)){
+ LOGV("\tLVM_ERROR : Reverb_getParameter() invalid pValueSize11 %d", *pValueSize);
+ return -EINVAL;
+ }
+ *pValueSize = sizeof(t_reverb_settings);
+ break;
+
+ default:
+ LOGV("\tLVM_ERROR : Reverb_getParameter() invalid param %d", param);
+ return -EINVAL;
+ }
+
+ pProperties = (t_reverb_settings *) pValue;
+
+ switch (param){
+ case REVERB_PARAM_PROPERTIES:
+ pProperties->roomLevel = ReverbGetRoomLevel(pContext);
+ pProperties->roomHFLevel = ReverbGetRoomHfLevel(pContext);
+ pProperties->decayTime = ReverbGetDecayTime(pContext);
+ pProperties->decayHFRatio = ReverbGetDecayHfRatio(pContext);
+ pProperties->reflectionsLevel = 0;
+ pProperties->reflectionsDelay = 0;
+ pProperties->reverbDelay = 0;
+ pProperties->reverbLevel = ReverbGetReverbLevel(pContext);
+ pProperties->diffusion = ReverbGetDiffusion(pContext);
+ pProperties->density = ReverbGetDensity(pContext);
+
+ LOGV("\tReverb_getParameter() REVERB_PARAM_PROPERTIES Value is roomLevel %d",
+ pProperties->roomLevel);
+ LOGV("\tReverb_getParameter() REVERB_PARAM_PROPERTIES Value is roomHFLevel %d",
+ pProperties->roomHFLevel);
+ LOGV("\tReverb_getParameter() REVERB_PARAM_PROPERTIES Value is decayTime %d",
+ pProperties->decayTime);
+ LOGV("\tReverb_getParameter() REVERB_PARAM_PROPERTIES Value is decayHFRatio %d",
+ pProperties->decayHFRatio);
+ LOGV("\tReverb_getParameter() REVERB_PARAM_PROPERTIES Value is reflectionsLevel %d",
+ pProperties->reflectionsLevel);
+ LOGV("\tReverb_getParameter() REVERB_PARAM_PROPERTIES Value is reflectionsDelay %d",
+ pProperties->reflectionsDelay);
+ LOGV("\tReverb_getParameter() REVERB_PARAM_PROPERTIES Value is reverbDelay %d",
+ pProperties->reverbDelay);
+ LOGV("\tReverb_getParameter() REVERB_PARAM_PROPERTIES Value is reverbLevel %d",
+ pProperties->reverbLevel);
+ LOGV("\tReverb_getParameter() REVERB_PARAM_PROPERTIES Value is diffusion %d",
+ pProperties->diffusion);
+ LOGV("\tReverb_getParameter() REVERB_PARAM_PROPERTIES Value is density %d",
+ pProperties->density);
+ break;
+
+ case REVERB_PARAM_ROOM_LEVEL:
+ *(int16_t *)pValue = ReverbGetRoomLevel(pContext);
+
+ //LOGV("\tReverb_getParameter() REVERB_PARAM_ROOM_LEVEL Value is %d",
+ // *(int16_t *)pValue);
+ break;
+ case REVERB_PARAM_ROOM_HF_LEVEL:
+ *(int16_t *)pValue = ReverbGetRoomHfLevel(pContext);
+
+ //LOGV("\tReverb_getParameter() REVERB_PARAM_ROOM_HF_LEVEL Value is %d",
+ // *(int16_t *)pValue);
+ break;
+ case REVERB_PARAM_DECAY_TIME:
+ *(int32_t *)pValue = ReverbGetDecayTime(pContext);
+
+ //LOGV("\tReverb_getParameter() REVERB_PARAM_DECAY_TIME Value is %d",
+ // *(int32_t *)pValue);
+ break;
+ case REVERB_PARAM_DECAY_HF_RATIO:
+ *(int16_t *)pValue = ReverbGetDecayHfRatio(pContext);
+
+ //LOGV("\tReverb_getParameter() REVERB_PARAM_DECAY_HF_RATION Value is %d",
+ // *(int16_t *)pValue);
+ break;
+ case REVERB_PARAM_REVERB_LEVEL:
+ *(int16_t *)pValue = ReverbGetReverbLevel(pContext);
+
+ //LOGV("\tReverb_getParameter() REVERB_PARAM_REVERB_LEVEL Value is %d",
+ // *(int16_t *)pValue);
+ break;
+ case REVERB_PARAM_DIFFUSION:
+ *(int16_t *)pValue = ReverbGetDiffusion(pContext);
+
+ //LOGV("\tReverb_getParameter() REVERB_PARAM_DECAY_DIFFUSION Value is %d",
+ // *(int16_t *)pValue);
+ break;
+ case REVERB_PARAM_DENSITY:
+ *(uint16_t *)pValue = 0;
+ *(int16_t *)pValue = ReverbGetDensity(pContext);
+ //LOGV("\tReverb_getParameter() REVERB_PARAM_DENSITY Value is %d",
+ // *(uint32_t *)pValue);
+ break;
+ case REVERB_PARAM_REFLECTIONS_LEVEL:
+ *(uint16_t *)pValue = 0;
+ case REVERB_PARAM_REFLECTIONS_DELAY:
+ *(uint32_t *)pValue = 0;
+ case REVERB_PARAM_REVERB_DELAY:
+ *(uint32_t *)pValue = 0;
+ break;
+
+ default:
+ LOGV("\tLVM_ERROR : Reverb_getParameter() invalid param %d", param);
+ status = -EINVAL;
+ break;
+ }
+
+ //LOGV("\tReverb_getParameter end");
+ return status;
+} /* end Reverb_getParameter */
+
+//----------------------------------------------------------------------------
+// Reverb_setParameter()
+//----------------------------------------------------------------------------
+// Purpose:
+// Set a Reverb parameter
+//
+// Inputs:
+// pContext - handle to instance data
+// pParam - pointer to parameter
+// pValue - pointer to value
+//
+// Outputs:
+//
+//----------------------------------------------------------------------------
+
+int Reverb_setParameter (ReverbContext *pContext, void *pParam, void *pValue){
+ int status = 0;
+ int16_t level;
+ uint32_t time;
+ t_reverb_settings *pProperties;
+ int32_t *pParamTemp = (int32_t *)pParam;
+ int32_t param = *pParamTemp++;
+
+ //LOGV("\tReverb_setParameter start");
+ if (pContext->preset) {
+ if (param != REVERB_PARAM_PRESET) {
+ return -EINVAL;
+ }
+
+ uint16_t preset = *(uint16_t *)pValue;
+ LOGV("set REVERB_PARAM_PRESET, preset %d", preset);
+ if (preset > REVERB_PRESET_LAST) {
+ return -EINVAL;
+ }
+ pContext->nextPreset = preset;
+ }
+
+ switch (param){
+ case REVERB_PARAM_PROPERTIES:
+ LOGV("\tReverb_setParameter() REVERB_PARAM_PROPERTIES");
+ pProperties = (t_reverb_settings *) pValue;
+ ReverbSetRoomLevel(pContext, pProperties->roomLevel);
+ ReverbSetRoomHfLevel(pContext, pProperties->roomHFLevel);
+ ReverbSetDecayTime(pContext, pProperties->decayTime);
+ ReverbSetDecayHfRatio(pContext, pProperties->decayHFRatio);
+ ReverbSetReverbLevel(pContext, pProperties->reverbLevel);
+ ReverbSetDiffusion(pContext, pProperties->diffusion);
+ ReverbSetDensity(pContext, pProperties->density);
+ break;
+ case REVERB_PARAM_ROOM_LEVEL:
+ level = *(int16_t *)pValue;
+ //LOGV("\tReverb_setParameter() REVERB_PARAM_ROOM_LEVEL value is %d", level);
+ //LOGV("\tReverb_setParameter() Calling ReverbSetRoomLevel");
+ ReverbSetRoomLevel(pContext, level);
+ //LOGV("\tReverb_setParameter() Called ReverbSetRoomLevel");
+ break;
+ case REVERB_PARAM_ROOM_HF_LEVEL:
+ level = *(int16_t *)pValue;
+ //LOGV("\tReverb_setParameter() REVERB_PARAM_ROOM_HF_LEVEL value is %d", level);
+ //LOGV("\tReverb_setParameter() Calling ReverbSetRoomHfLevel");
+ ReverbSetRoomHfLevel(pContext, level);
+ //LOGV("\tReverb_setParameter() Called ReverbSetRoomHfLevel");
+ break;
+ case REVERB_PARAM_DECAY_TIME:
+ time = *(uint32_t *)pValue;
+ //LOGV("\tReverb_setParameter() REVERB_PARAM_DECAY_TIME value is %d", time);
+ //LOGV("\tReverb_setParameter() Calling ReverbSetDecayTime");
+ ReverbSetDecayTime(pContext, time);
+ //LOGV("\tReverb_setParameter() Called ReverbSetDecayTime");
+ break;
+ case REVERB_PARAM_DECAY_HF_RATIO:
+ time = *(int16_t *)pValue;
+ //LOGV("\tReverb_setParameter() REVERB_PARAM_DECAY_HF_RATIO value is %d", time);
+ //LOGV("\tReverb_setParameter() Calling ReverbSetDecayHfRatio");
+ ReverbSetDecayHfRatio(pContext, time);
+ //LOGV("\tReverb_setParameter() Called ReverbSetDecayHfRatio");
+ break;
+ case REVERB_PARAM_REVERB_LEVEL:
+ level = *(int16_t *)pValue;
+ //LOGV("\tReverb_setParameter() REVERB_PARAM_REVERB_LEVEL value is %d", level);
+ //LOGV("\tReverb_setParameter() Calling ReverbSetReverbLevel");
+ ReverbSetReverbLevel(pContext, level);
+ //LOGV("\tReverb_setParameter() Called ReverbSetReverbLevel");
+ break;
+ case REVERB_PARAM_DIFFUSION:
+ time = *(int16_t *)pValue;
+ //LOGV("\tReverb_setParameter() REVERB_PARAM_DECAY_DIFFUSION value is %d", time);
+ //LOGV("\tReverb_setParameter() Calling ReverbSetDiffusion");
+ ReverbSetDiffusion(pContext, time);
+ //LOGV("\tReverb_setParameter() Called ReverbSetDiffusion");
+ break;
+ case REVERB_PARAM_DENSITY:
+ time = *(int16_t *)pValue;
+ //LOGV("\tReverb_setParameter() REVERB_PARAM_DECAY_DENSITY value is %d", time);
+ //LOGV("\tReverb_setParameter() Calling ReverbSetDensity");
+ ReverbSetDensity(pContext, time);
+ //LOGV("\tReverb_setParameter() Called ReverbSetDensity");
+ break;
+ break;
+ case REVERB_PARAM_REFLECTIONS_LEVEL:
+ case REVERB_PARAM_REFLECTIONS_DELAY:
+ case REVERB_PARAM_REVERB_DELAY:
+ break;
+ default:
+ LOGV("\tLVM_ERROR : Reverb_setParameter() invalid param %d", param);
+ break;
+ }
+
+ //LOGV("\tReverb_setParameter end");
+ return status;
+} /* end Reverb_setParameter */
+
+} // namespace
+} // namespace
+
+/* Effect Control Interface Implementation: Process */
+extern "C" int Reverb_process(effect_interface_t self,
+ audio_buffer_t *inBuffer,
+ audio_buffer_t *outBuffer){
+ android::ReverbContext * pContext = (android::ReverbContext *) self;
+ int status = 0;
+
+ if (pContext == NULL){
+ LOGV("\tLVM_ERROR : Reverb_process() ERROR pContext == NULL");
+ return -EINVAL;
+ }
+ if (inBuffer == NULL || inBuffer->raw == NULL ||
+ outBuffer == NULL || outBuffer->raw == NULL ||
+ inBuffer->frameCount != outBuffer->frameCount){
+ LOGV("\tLVM_ERROR : Reverb_process() ERROR NULL INPUT POINTER OR FRAME COUNT IS WRONG");
+ return -EINVAL;
+ }
+ if (pContext->bEnabled == LVM_FALSE){
+ LOGV("\tReverb_process() ERROR Effect is not enabled");
+ return -ENODATA;
+ }
+ //LOGV("\tReverb_process() Calling process with %d frames", outBuffer->frameCount);
+ /* Process all the available frames, block processing is handled internalLY by the LVM bundle */
+ status = process( (LVM_INT16 *)inBuffer->raw,
+ (LVM_INT16 *)outBuffer->raw,
+ outBuffer->frameCount,
+ pContext);
+
+ return status;
+} /* end Reverb_process */
+
+/* Effect Control Interface Implementation: Command */
+extern "C" int Reverb_command(effect_interface_t self,
+ uint32_t cmdCode,
+ uint32_t cmdSize,
+ void *pCmdData,
+ uint32_t *replySize,
+ void *pReplyData){
+ android::ReverbContext * pContext = (android::ReverbContext *) self;
+ int retsize;
+
+ if (pContext == NULL){
+ LOGV("\tLVM_ERROR : Reverb_command ERROR pContext == NULL");
+ return -EINVAL;
+ }
+
+ //LOGV("\tReverb_command INPUTS are: command %d cmdSize %d",cmdCode, cmdSize);
+
+ switch (cmdCode){
+ case EFFECT_CMD_INIT:
+ //LOGV("\tReverb_command cmdCode Case: "
+ // "EFFECT_CMD_INIT start");
+
+ if (pReplyData == NULL || *replySize != sizeof(int)){
+ LOGV("\tLVM_ERROR : Reverb_command cmdCode Case: "
+ "EFFECT_CMD_INIT: ERROR");
+ return -EINVAL;
+ }
+ *(int *) pReplyData = 0;
+ break;
+
+ case EFFECT_CMD_CONFIGURE:
+ //LOGV("\tReverb_command cmdCode Case: "
+ // "EFFECT_CMD_CONFIGURE start");
+ if (pCmdData == NULL||
+ cmdSize != sizeof(effect_config_t)||
+ pReplyData == NULL||
+ *replySize != sizeof(int)){
+ LOGV("\tLVM_ERROR : Reverb_command cmdCode Case: "
+ "EFFECT_CMD_CONFIGURE: ERROR");
+ return -EINVAL;
+ }
+ *(int *) pReplyData = Reverb_configure(pContext, (effect_config_t *) pCmdData);
+ break;
+
+ case EFFECT_CMD_RESET:
+ //LOGV("\tReverb_command cmdCode Case: "
+ // "EFFECT_CMD_RESET start");
+ Reverb_configure(pContext, &pContext->config);
+ break;
+
+ case EFFECT_CMD_GET_PARAM:{
+ //LOGV("\tReverb_command cmdCode Case: "
+ // "EFFECT_CMD_GET_PARAM start");
+ if (pCmdData == NULL ||
+ cmdSize < (int)(sizeof(effect_param_t) + sizeof(int32_t)) ||
+ pReplyData == NULL ||
+ *replySize < (int) (sizeof(effect_param_t) + sizeof(int32_t))){
+ LOGV("\tLVM_ERROR : Reverb_command cmdCode Case: "
+ "EFFECT_CMD_GET_PARAM: ERROR");
+ return -EINVAL;
+ }
+ effect_param_t *p = (effect_param_t *)pCmdData;
+
+ memcpy(pReplyData, pCmdData, sizeof(effect_param_t) + p->psize);
+
+ p = (effect_param_t *)pReplyData;
+
+ int voffset = ((p->psize - 1) / sizeof(int32_t) + 1) * sizeof(int32_t);
+
+ p->status = android::Reverb_getParameter(pContext,
+ (void *)p->data,
+ (size_t *)&p->vsize,
+ p->data + voffset);
+
+ *replySize = sizeof(effect_param_t) + voffset + p->vsize;
+
+ //LOGV("\tReverb_command EFFECT_CMD_GET_PARAM "
+ // "*pCmdData %d, *replySize %d, *pReplyData %d ",
+ // *(int32_t *)((char *)pCmdData + sizeof(effect_param_t)),
+ // *replySize,
+ // *(int16_t *)((char *)pReplyData + sizeof(effect_param_t) + voffset));
+
+ } break;
+ case EFFECT_CMD_SET_PARAM:{
+
+ //LOGV("\tReverb_command cmdCode Case: "
+ // "EFFECT_CMD_SET_PARAM start");
+ //LOGV("\tReverb_command EFFECT_CMD_SET_PARAM param %d, *replySize %d, value %d ",
+ // *(int32_t *)((char *)pCmdData + sizeof(effect_param_t)),
+ // *replySize,
+ // *(int16_t *)((char *)pCmdData + sizeof(effect_param_t) + sizeof(int32_t)));
+
+ if (pCmdData == NULL || (cmdSize < (int)(sizeof(effect_param_t) + sizeof(int32_t)))
+ || pReplyData == NULL || *replySize != (int)sizeof(int32_t)) {
+ LOGV("\tLVM_ERROR : Reverb_command cmdCode Case: "
+ "EFFECT_CMD_SET_PARAM: ERROR");
+ return -EINVAL;
+ }
+
+ effect_param_t *p = (effect_param_t *) pCmdData;
+
+ if (p->psize != sizeof(int32_t)){
+ LOGV("\t4LVM_ERROR : Reverb_command cmdCode Case: "
+ "EFFECT_CMD_SET_PARAM: ERROR, psize is not sizeof(int32_t)");
+ return -EINVAL;
+ }
+
+ //LOGV("\tn5Reverb_command cmdSize is %d\n"
+ // "\tsizeof(effect_param_t) is %d\n"
+ // "\tp->psize is %d\n"
+ // "\tp->vsize is %d"
+ // "\n",
+ // cmdSize, sizeof(effect_param_t), p->psize, p->vsize );
+
+ *(int *)pReplyData = android::Reverb_setParameter(pContext,
+ (void *)p->data,
+ p->data + p->psize);
+ } break;
+
+ case EFFECT_CMD_ENABLE:
+ //LOGV("\tReverb_command cmdCode Case: "
+ // "EFFECT_CMD_ENABLE start");
+
+ if (pReplyData == NULL || *replySize != sizeof(int)){
+ LOGV("\tLVM_ERROR : Reverb_command cmdCode Case: "
+ "EFFECT_CMD_ENABLE: ERROR");
+ return -EINVAL;
+ }
+ if(pContext->bEnabled == LVM_TRUE){
+ LOGV("\tLVM_ERROR : Reverb_command cmdCode Case: "
+ "EFFECT_CMD_ENABLE: ERROR-Effect is already enabled");
+ return -EINVAL;
+ }
+ *(int *)pReplyData = 0;
+ pContext->bEnabled = LVM_TRUE;
+ break;
+ case EFFECT_CMD_DISABLE:
+ //LOGV("\tReverb_command cmdCode Case: "
+ // "EFFECT_CMD_DISABLE start");
+
+ if (pReplyData == NULL || *replySize != sizeof(int)){
+ LOGV("\tLVM_ERROR : Reverb_command cmdCode Case: "
+ "EFFECT_CMD_DISABLE: ERROR");
+ return -EINVAL;
+ }
+ if(pContext->bEnabled == LVM_FALSE){
+ LOGV("\tLVM_ERROR : Reverb_command cmdCode Case: "
+ "EFFECT_CMD_DISABLE: ERROR-Effect is not yet enabled");
+ return -EINVAL;
+ }
+ *(int *)pReplyData = 0;
+ pContext->bEnabled = LVM_FALSE;
+ break;
+
+ case EFFECT_CMD_SET_DEVICE:
+ case EFFECT_CMD_SET_VOLUME:
+ case EFFECT_CMD_SET_AUDIO_MODE:
+ //LOGV("\tReverb_command cmdCode Case: "
+ // "EFFECT_CMD_SET_DEVICE/EFFECT_CMD_SET_VOLUME/EFFECT_CMD_SET_AUDIO_MODE start");
+ break;
+
+ default:
+ LOGV("\tLVM_ERROR : Reverb_command cmdCode Case: "
+ "DEFAULT start %d ERROR",cmdCode);
+ return -EINVAL;
+ }
+
+ //LOGV("\tReverb_command end\n\n");
+ return 0;
+} /* end Reverb_command */
+
+// effect_interface_t interface implementation for Reverb effect
+const struct effect_interface_s gReverbInterface = {
+ Reverb_process,
+ Reverb_command
+}; /* end gReverbInterface */
+
diff --git a/media/libeffects/lvm/wrapper/Reverb/EffectReverb.h b/media/libeffects/lvm/wrapper/Reverb/EffectReverb.h
new file mode 100755
index 0000000..1ab423f
--- /dev/null
+++ b/media/libeffects/lvm/wrapper/Reverb/EffectReverb.h
@@ -0,0 +1,38 @@
+/*
+ * Copyright (C) 2010 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 ANDROID_EFFECTREVERB_H_
+#define ANDROID_EFFECTREVERB_H_
+
+#include <media/EffectEnvironmentalReverbApi.h>
+#include <media/EffectPresetReverbApi.h>
+
+#if __cplusplus
+extern "C" {
+#endif
+
+
+typedef struct _LPFPair_t
+{
+ int16_t Room_HF;
+ int16_t LPF;
+} LPFPair_t;
+#if __cplusplus
+} // extern "C"
+#endif
+
+
+#endif /*ANDROID_EFFECTREVERB_H_*/
diff --git a/media/libmedia/fixedfft.cpp b/media/libmedia/fixedfft.cpp
index 28eb05a..9cf05ba 100644
--- a/media/libmedia/fixedfft.cpp
+++ b/media/libmedia/fixedfft.cpp
@@ -26,7 +26,9 @@
#include <stdio.h>
#include <stdint.h>
+#ifdef __ARM_ARCH__
#include <machine/cpu-features.h>
+#endif
#define LOG_FFT_SIZE 10
#define MAX_FFT_SIZE (1 << LOG_FFT_SIZE)
diff --git a/media/libmediaplayerservice/StagefrightRecorder.cpp b/media/libmediaplayerservice/StagefrightRecorder.cpp
index 796731b..cf01ff6 100644
--- a/media/libmediaplayerservice/StagefrightRecorder.cpp
+++ b/media/libmediaplayerservice/StagefrightRecorder.cpp
@@ -1162,11 +1162,19 @@
return OK;
}
-status_t StagefrightRecorder::dump(int fd, const Vector<String16>& args) const {
+status_t StagefrightRecorder::dump(
+ int fd, const Vector<String16>& args) const {
+ LOGV("dump");
const size_t SIZE = 256;
char buffer[SIZE];
String8 result;
- snprintf(buffer, SIZE, " Recorder: %p", this);
+ if (mWriter != 0) {
+ mWriter->dump(fd, args);
+ } else {
+ snprintf(buffer, SIZE, " No file writer\n");
+ result.append(buffer);
+ }
+ snprintf(buffer, SIZE, " Recorder: %p\n", this);
snprintf(buffer, SIZE, " Output file (fd %d):\n", mOutputFd);
result.append(buffer);
snprintf(buffer, SIZE, " File format: %d\n", mOutputFormat);
diff --git a/media/libstagefright/AMRExtractor.cpp b/media/libstagefright/AMRExtractor.cpp
index 70af2da..1b05528 100644
--- a/media/libstagefright/AMRExtractor.cpp
+++ b/media/libstagefright/AMRExtractor.cpp
@@ -87,7 +87,7 @@
mInitCheck(NO_INIT) {
String8 mimeType;
float confidence;
- if (!SniffAMR(mDataSource, &mimeType, &confidence)) {
+ if (!SniffAMR(mDataSource, &mimeType, &confidence, NULL)) {
return;
}
@@ -276,7 +276,8 @@
////////////////////////////////////////////////////////////////////////////////
bool SniffAMR(
- const sp<DataSource> &source, String8 *mimeType, float *confidence) {
+ const sp<DataSource> &source, String8 *mimeType, float *confidence,
+ sp<AMessage> *) {
char header[9];
if (source->readAt(0, header, sizeof(header)) != sizeof(header)) {
diff --git a/media/libstagefright/AwesomePlayer.cpp b/media/libstagefright/AwesomePlayer.cpp
index f2653cf..a0cd5c3 100644
--- a/media/libstagefright/AwesomePlayer.cpp
+++ b/media/libstagefright/AwesomePlayer.cpp
@@ -196,6 +196,7 @@
mExtractorFlags(0),
mLastVideoBuffer(NULL),
mVideoBuffer(NULL),
+ mRTSPTimeOffset(0),
mSuspensionState(NULL) {
CHECK_EQ(mClient.connect(), OK);
@@ -393,7 +394,11 @@
mVideoBuffer = NULL;
}
- mRTSPController.clear();
+ if (mRTSPController != NULL) {
+ mRTSPController->disconnect();
+ mRTSPController.clear();
+ }
+
mRTPPusher.clear();
mRTCPPusher.clear();
mRTPSession.clear();
@@ -453,27 +458,34 @@
return;
}
+ bool eos;
+ size_t cachedDataRemaining = mCachedSource->approxDataRemaining(&eos);
+
size_t lowWatermark = 400000;
size_t highWatermark = 1000000;
- off_t size;
- if (mDurationUs >= 0 && mCachedSource->getSize(&size) == OK) {
- int64_t bitrate = size * 8000000ll / mDurationUs; // in bits/sec
+ if (eos) {
+ notifyListener_l(MEDIA_BUFFERING_UPDATE, 100);
+ } else {
+ off_t size;
+ if (mDurationUs >= 0 && mCachedSource->getSize(&size) == OK) {
+ int64_t bitrate = size * 8000000ll / mDurationUs; // in bits/sec
- size_t cachedSize = mCachedSource->cachedSize();
- int64_t cachedDurationUs = cachedSize * 8000000ll / bitrate;
+ size_t cachedSize = mCachedSource->cachedSize();
+ int64_t cachedDurationUs = cachedSize * 8000000ll / bitrate;
- double percentage = (double)cachedDurationUs / mDurationUs;
+ int percentage = 100.0 * (double)cachedDurationUs / mDurationUs;
+ if (percentage > 100) {
+ percentage = 100;
+ }
- notifyListener_l(MEDIA_BUFFERING_UPDATE, percentage * 100.0);
+ notifyListener_l(MEDIA_BUFFERING_UPDATE, percentage);
- lowWatermark = 2 * bitrate / 8; // 2 secs
- highWatermark = 10 * bitrate / 8; // 10 secs
+ lowWatermark = 2 * bitrate / 8; // 2 secs
+ highWatermark = 10 * bitrate / 8; // 10 secs
+ }
}
- bool eos;
- size_t cachedDataRemaining = mCachedSource->approxDataRemaining(&eos);
-
if ((mFlags & PLAYING) && !eos && (cachedDataRemaining < lowWatermark)) {
LOGI("cache is running low (< %d) , pausing.", lowWatermark);
mFlags |= CACHE_UNDERRUN;
@@ -738,6 +750,10 @@
*positionUs = 0;
}
+ if (mRTSPController != NULL) {
+ *positionUs += mRTSPTimeOffset;
+ }
+
return OK;
}
@@ -753,6 +769,17 @@
}
status_t AwesomePlayer::seekTo_l(int64_t timeUs) {
+ if (mRTSPController != NULL) {
+ pause_l();
+ mRTSPController->seek(timeUs);
+ play_l();
+
+ notifyListener_l(MEDIA_SEEK_COMPLETE);
+ mSeekNotificationSent = true;
+ mRTSPTimeOffset = timeUs;
+ return OK;
+ }
+
if (mFlags & CACHE_UNDERRUN) {
mFlags &= ~CACHE_UNDERRUN;
play_l();
diff --git a/media/libstagefright/DataSource.cpp b/media/libstagefright/DataSource.cpp
index 90a596c..49eac62 100644
--- a/media/libstagefright/DataSource.cpp
+++ b/media/libstagefright/DataSource.cpp
@@ -25,6 +25,7 @@
#include "matroska/MatroskaExtractor.h"
+#include <media/stagefright/foundation/AMessage.h>
#include <media/stagefright/DataSource.h>
#include <media/stagefright/FileSource.h>
#include <media/stagefright/MediaErrors.h>
@@ -56,19 +57,23 @@
Mutex DataSource::gSnifferMutex;
List<DataSource::SnifferFunc> DataSource::gSniffers;
-bool DataSource::sniff(String8 *mimeType, float *confidence) {
+bool DataSource::sniff(
+ String8 *mimeType, float *confidence, sp<AMessage> *meta) {
*mimeType = "";
*confidence = 0.0f;
+ meta->clear();
Mutex::Autolock autoLock(gSnifferMutex);
for (List<SnifferFunc>::iterator it = gSniffers.begin();
it != gSniffers.end(); ++it) {
String8 newMimeType;
float newConfidence;
- if ((*it)(this, &newMimeType, &newConfidence)) {
+ sp<AMessage> newMeta;
+ if ((*it)(this, &newMimeType, &newConfidence, &newMeta)) {
if (newConfidence > *confidence) {
*mimeType = newMimeType;
*confidence = newConfidence;
+ *meta = newMeta;
}
}
}
@@ -92,13 +97,13 @@
// static
void DataSource::RegisterDefaultSniffers() {
- RegisterSniffer(SniffMP3);
RegisterSniffer(SniffMPEG4);
- RegisterSniffer(SniffAMR);
- RegisterSniffer(SniffWAV);
- RegisterSniffer(SniffOgg);
RegisterSniffer(SniffMatroska);
+ RegisterSniffer(SniffOgg);
+ RegisterSniffer(SniffWAV);
+ RegisterSniffer(SniffAMR);
RegisterSniffer(SniffMPEG2TS);
+ RegisterSniffer(SniffMP3);
}
// static
diff --git a/media/libstagefright/MP3Extractor.cpp b/media/libstagefright/MP3Extractor.cpp
index 4058fbc..2e36968 100644
--- a/media/libstagefright/MP3Extractor.cpp
+++ b/media/libstagefright/MP3Extractor.cpp
@@ -22,6 +22,7 @@
#include "include/ID3.h"
+#include <media/stagefright/foundation/AMessage.h>
#include <media/stagefright/DataSource.h>
#include <media/stagefright/MediaBuffer.h>
#include <media/stagefright/MediaBufferGroup.h>
@@ -456,15 +457,31 @@
MP3Source &operator=(const MP3Source &);
};
-MP3Extractor::MP3Extractor(const sp<DataSource> &source)
+MP3Extractor::MP3Extractor(
+ const sp<DataSource> &source, const sp<AMessage> &meta)
: mDataSource(source),
mFirstFramePos(-1),
mFixedHeader(0),
mByteNumber(0) {
off_t pos = 0;
uint32_t header;
- bool success = Resync(mDataSource, 0, &pos, &header);
- CHECK(success);
+ bool success;
+
+ int64_t meta_offset;
+ uint32_t meta_header;
+ if (meta != NULL
+ && meta->findInt64("offset", &meta_offset)
+ && meta->findInt32("header", (int32_t *)&meta_header)) {
+ // The sniffer has already done all the hard work for us, simply
+ // accept its judgement.
+ pos = (off_t)meta_offset;
+ header = meta_header;
+
+ success = true;
+ } else {
+ success = Resync(mDataSource, 0, &pos, &header);
+ CHECK(success);
+ }
if (success) {
mFirstFramePos = pos;
@@ -759,15 +776,20 @@
}
bool SniffMP3(
- const sp<DataSource> &source, String8 *mimeType, float *confidence) {
+ const sp<DataSource> &source, String8 *mimeType,
+ float *confidence, sp<AMessage> *meta) {
off_t pos = 0;
uint32_t header;
if (!Resync(source, 0, &pos, &header)) {
return false;
}
+ *meta = new AMessage;
+ (*meta)->setInt64("offset", pos);
+ (*meta)->setInt32("header", header);
+
*mimeType = MEDIA_MIMETYPE_AUDIO_MPEG;
- *confidence = 0.3f;
+ *confidence = 0.2f;
return true;
}
diff --git a/media/libstagefright/MPEG4Extractor.cpp b/media/libstagefright/MPEG4Extractor.cpp
index 12a1e6e..ba90407 100644
--- a/media/libstagefright/MPEG4Extractor.cpp
+++ b/media/libstagefright/MPEG4Extractor.cpp
@@ -1738,7 +1738,7 @@
|| !memcmp(header, "ftypM4A ", 8) || !memcmp(header, "ftypf4v ", 8)
|| !memcmp(header, "ftypkddi", 8) || !memcmp(header, "ftypM4VP", 8)) {
*mimeType = MEDIA_MIMETYPE_CONTAINER_MPEG4;
- *confidence = 0.1;
+ *confidence = 0.4;
return true;
}
@@ -1805,13 +1805,14 @@
}
*mimeType = MEDIA_MIMETYPE_CONTAINER_MPEG4;
- *confidence = 0.3f;
+ *confidence = 0.4f;
return true;
}
bool SniffMPEG4(
- const sp<DataSource> &source, String8 *mimeType, float *confidence) {
+ const sp<DataSource> &source, String8 *mimeType, float *confidence,
+ sp<AMessage> *) {
if (BetterSniffMPEG4(source, mimeType, confidence)) {
return true;
}
diff --git a/media/libstagefright/MPEG4Writer.cpp b/media/libstagefright/MPEG4Writer.cpp
index 568037e..e36d9fe 100644
--- a/media/libstagefright/MPEG4Writer.cpp
+++ b/media/libstagefright/MPEG4Writer.cpp
@@ -60,6 +60,7 @@
bool isAudio() const { return mIsAudio; }
bool isMPEG4() const { return mIsMPEG4; }
void addChunkOffset(off_t offset) { mChunkOffsets.push_back(offset); }
+ status_t dump(int fd, const Vector<String16>& args) const;
private:
MPEG4Writer *mOwner;
@@ -217,6 +218,37 @@
mTracks.clear();
}
+status_t MPEG4Writer::dump(
+ int fd, const Vector<String16>& args) {
+ const size_t SIZE = 256;
+ char buffer[SIZE];
+ String8 result;
+ snprintf(buffer, SIZE, " MPEG4Writer %p\n", this);
+ result.append(buffer);
+ snprintf(buffer, SIZE, " mStarted: %s\n", mStarted? "true": "false");
+ result.append(buffer);
+ ::write(fd, result.string(), result.size());
+ for (List<Track *>::iterator it = mTracks.begin();
+ it != mTracks.end(); ++it) {
+ (*it)->dump(fd, args);
+ }
+ return OK;
+}
+
+status_t MPEG4Writer::Track::dump(
+ int fd, const Vector<String16>& args) const {
+ const size_t SIZE = 256;
+ char buffer[SIZE];
+ String8 result;
+ snprintf(buffer, SIZE, " %s track\n", mIsAudio? "Audio": "Video");
+ result.append(buffer);
+ snprintf(buffer, SIZE, " reached EOS: %s\n",
+ mReachedEOS? "true": "false");
+ result.append(buffer);
+ ::write(fd, result.string(), result.size());
+ return OK;
+}
+
status_t MPEG4Writer::addSource(const sp<MediaSource> &source) {
Track *track = new Track(this, source);
mTracks.push_back(track);
diff --git a/media/libstagefright/MediaExtractor.cpp b/media/libstagefright/MediaExtractor.cpp
index 56e6136..9bc94de 100644
--- a/media/libstagefright/MediaExtractor.cpp
+++ b/media/libstagefright/MediaExtractor.cpp
@@ -27,6 +27,7 @@
#include "matroska/MatroskaExtractor.h"
+#include <media/stagefright/foundation/AMessage.h>
#include <media/stagefright/DataSource.h>
#include <media/stagefright/MediaDefs.h>
#include <media/stagefright/MediaExtractor.h>
@@ -46,10 +47,12 @@
// static
sp<MediaExtractor> MediaExtractor::Create(
const sp<DataSource> &source, const char *mime) {
+ sp<AMessage> meta;
+
String8 tmp;
if (mime == NULL) {
float confidence;
- if (!source->sniff(&tmp, &confidence)) {
+ if (!source->sniff(&tmp, &confidence, &meta)) {
LOGV("FAILED to autodetect media content.");
return NULL;
@@ -64,7 +67,7 @@
|| !strcasecmp(mime, "audio/mp4")) {
return new MPEG4Extractor(source);
} else if (!strcasecmp(mime, MEDIA_MIMETYPE_AUDIO_MPEG)) {
- return new MP3Extractor(source);
+ return new MP3Extractor(source, meta);
} else if (!strcasecmp(mime, MEDIA_MIMETYPE_AUDIO_AMR_NB)
|| !strcasecmp(mime, MEDIA_MIMETYPE_AUDIO_AMR_WB)) {
return new AMRExtractor(source);
diff --git a/media/libstagefright/OggExtractor.cpp b/media/libstagefright/OggExtractor.cpp
index 9630092..2c1311a 100644
--- a/media/libstagefright/OggExtractor.cpp
+++ b/media/libstagefright/OggExtractor.cpp
@@ -804,7 +804,8 @@
}
bool SniffOgg(
- const sp<DataSource> &source, String8 *mimeType, float *confidence) {
+ const sp<DataSource> &source, String8 *mimeType, float *confidence,
+ sp<AMessage> *) {
char tmp[4];
if (source->readAt(0, tmp, 4) < 4 || memcmp(tmp, "OggS", 4)) {
return false;
diff --git a/media/libstagefright/WAVExtractor.cpp b/media/libstagefright/WAVExtractor.cpp
index 8d820c0..57c1075 100644
--- a/media/libstagefright/WAVExtractor.cpp
+++ b/media/libstagefright/WAVExtractor.cpp
@@ -404,7 +404,8 @@
////////////////////////////////////////////////////////////////////////////////
bool SniffWAV(
- const sp<DataSource> &source, String8 *mimeType, float *confidence) {
+ const sp<DataSource> &source, String8 *mimeType, float *confidence,
+ sp<AMessage> *) {
char header[12];
if (source->readAt(0, header, sizeof(header)) < (ssize_t)sizeof(header)) {
return false;
diff --git a/media/libstagefright/id3/ID3.cpp b/media/libstagefright/id3/ID3.cpp
index ca0c68c..da340f7 100644
--- a/media/libstagefright/id3/ID3.cpp
+++ b/media/libstagefright/id3/ID3.cpp
@@ -142,11 +142,22 @@
mSize = size;
if (source->readAt(sizeof(header), mData, mSize) != (ssize_t)mSize) {
+ free(mData);
+ mData = NULL;
+
return false;
}
- if (header.flags & 0x80) {
+ if (header.version_major == 4) {
+ if (!removeUnsynchronizationV2_4()) {
+ free(mData);
+ mData = NULL;
+
+ return false;
+ }
+ } else if (header.flags & 0x80) {
LOGV("removing unsynchronization");
+
removeUnsynchronization();
}
@@ -243,6 +254,74 @@
}
}
+static void WriteSyncsafeInteger(uint8_t *dst, size_t x) {
+ for (size_t i = 0; i < 4; ++i) {
+ dst[3 - i] = (x & 0x7f);
+ x >>= 7;
+ }
+}
+
+bool ID3::removeUnsynchronizationV2_4() {
+ size_t oldSize = mSize;
+
+ size_t offset = 0;
+ while (offset + 10 <= mSize) {
+ if (!memcmp(&mData[offset], "\0\0\0\0", 4)) {
+ break;
+ }
+
+ size_t dataSize;
+ if (!ParseSyncsafeInteger(&mData[offset + 4], &dataSize)) {
+ return false;
+ }
+
+ if (offset + dataSize + 10 > mSize) {
+ return false;
+ }
+
+ uint16_t flags = U16_AT(&mData[offset + 8]);
+ uint16_t prevFlags = flags;
+
+ if (flags & 1) {
+ // Strip data length indicator
+
+ memmove(&mData[offset + 10], &mData[offset + 14], mSize - offset - 14);
+ mSize -= 4;
+ dataSize -= 4;
+
+ flags &= ~1;
+ }
+
+ if (flags & 2) {
+ // Unsynchronization added.
+
+ for (size_t i = 0; i + 1 < dataSize; ++i) {
+ if (mData[offset + 10 + i] == 0xff
+ && mData[offset + 11 + i] == 0x00) {
+ memmove(&mData[offset + 11 + i], &mData[offset + 12 + i],
+ mSize - offset - 12 - i);
+ --mSize;
+ --dataSize;
+ }
+ }
+
+ flags &= ~2;
+ }
+
+ if (flags != prevFlags) {
+ WriteSyncsafeInteger(&mData[offset + 4], dataSize);
+ mData[offset + 8] = flags >> 8;
+ mData[offset + 9] = flags & 0xff;
+ }
+
+ offset += 10 + dataSize;
+ }
+
+ memset(&mData[mSize], 0, oldSize - mSize);
+
+ return true;
+}
+
ID3::Iterator::Iterator(const ID3 &parent, const char *id)
: mParent(parent),
mID(NULL),
@@ -529,10 +608,11 @@
uint16_t flags = U16_AT(&mParent.mData[mOffset + 8]);
- if ((mParent.mVersion == ID3_V2_4 && (flags & 0x000e))
+ if ((mParent.mVersion == ID3_V2_4 && (flags & 0x000c))
|| (mParent.mVersion == ID3_V2_3 && (flags & 0x00c0))) {
- // Compression, Encryption or per-Frame unsynchronization
- // are not supported at this time.
+ // Compression or encryption are not supported at this time.
+ // Per-frame unsynchronization and data-length indicator
+ // have already been taken care of.
LOGV("Skipping unsupported frame (compression, encryption "
"or per-frame unsynchronization flagged");
diff --git a/media/libstagefright/include/AMRExtractor.h b/media/libstagefright/include/AMRExtractor.h
index db49fe4..1cdf36d 100644
--- a/media/libstagefright/include/AMRExtractor.h
+++ b/media/libstagefright/include/AMRExtractor.h
@@ -22,6 +22,7 @@
namespace android {
+struct AMessage;
class String8;
class AMRExtractor : public MediaExtractor {
@@ -49,7 +50,8 @@
};
bool SniffAMR(
- const sp<DataSource> &source, String8 *mimeType, float *confidence);
+ const sp<DataSource> &source, String8 *mimeType, float *confidence,
+ sp<AMessage> *);
} // namespace android
diff --git a/media/libstagefright/include/ARTSPController.h b/media/libstagefright/include/ARTSPController.h
index 55efd41..7020564 100644
--- a/media/libstagefright/include/ARTSPController.h
+++ b/media/libstagefright/include/ARTSPController.h
@@ -19,6 +19,7 @@
#define A_RTSP_CONTROLLER_H_
#include <media/stagefright/foundation/ABase.h>
+#include <media/stagefright/foundation/AHandlerReflector.h>
#include <media/stagefright/MediaExtractor.h>
namespace android {
@@ -32,18 +33,40 @@
status_t connect(const char *url);
void disconnect();
+ void seek(int64_t timeUs);
+
virtual size_t countTracks();
virtual sp<MediaSource> getTrack(size_t index);
virtual sp<MetaData> getTrackMetaData(
size_t index, uint32_t flags);
+ void onMessageReceived(const sp<AMessage> &msg);
+
protected:
virtual ~ARTSPController();
private:
+ enum {
+ kWhatConnectDone = 'cdon',
+ kWhatDisconnectDone = 'ddon',
+ };
+
+ enum State {
+ DISCONNECTED,
+ CONNECTED,
+ CONNECTING,
+ };
+
+ Mutex mLock;
+ Condition mCondition;
+
+ State mState;
+ status_t mConnectionResult;
+
sp<ALooper> mLooper;
sp<MyHandler> mHandler;
+ sp<AHandlerReflector<ARTSPController> > mReflector;
DISALLOW_EVIL_CONSTRUCTORS(ARTSPController);
};
diff --git a/media/libstagefright/include/AwesomePlayer.h b/media/libstagefright/include/AwesomePlayer.h
index 55e2c36..49b5c78 100644
--- a/media/libstagefright/include/AwesomePlayer.h
+++ b/media/libstagefright/include/AwesomePlayer.h
@@ -180,6 +180,7 @@
sp<ALooper> mLooper;
sp<ARTSPController> mRTSPController;
+ int64_t mRTSPTimeOffset;
sp<ARTPSession> mRTPSession;
sp<UDPPusher> mRTPPusher, mRTCPPusher;
diff --git a/media/libstagefright/include/ID3.h b/media/libstagefright/include/ID3.h
index c6b1a8b..7ddbb41 100644
--- a/media/libstagefright/include/ID3.h
+++ b/media/libstagefright/include/ID3.h
@@ -80,6 +80,7 @@
bool parseV1(const sp<DataSource> &source);
bool parseV2(const sp<DataSource> &source);
void removeUnsynchronization();
+ bool removeUnsynchronizationV2_4();
static bool ParseSyncsafeInteger(const uint8_t encoded[4], size_t *x);
diff --git a/media/libstagefright/include/MP3Extractor.h b/media/libstagefright/include/MP3Extractor.h
index 3ce6df3..0e6ccde 100644
--- a/media/libstagefright/include/MP3Extractor.h
+++ b/media/libstagefright/include/MP3Extractor.h
@@ -22,13 +22,14 @@
namespace android {
+struct AMessage;
class DataSource;
class String8;
class MP3Extractor : public MediaExtractor {
public:
// Extractor assumes ownership of "source".
- MP3Extractor(const sp<DataSource> &source);
+ MP3Extractor(const sp<DataSource> &source, const sp<AMessage> &meta);
virtual size_t countTracks();
virtual sp<MediaSource> getTrack(size_t index);
@@ -52,7 +53,8 @@
};
bool SniffMP3(
- const sp<DataSource> &source, String8 *mimeType, float *confidence);
+ const sp<DataSource> &source, String8 *mimeType, float *confidence,
+ sp<AMessage> *meta);
} // namespace android
diff --git a/media/libstagefright/include/MPEG2TSExtractor.h b/media/libstagefright/include/MPEG2TSExtractor.h
index c96973b..1bf4cd1 100644
--- a/media/libstagefright/include/MPEG2TSExtractor.h
+++ b/media/libstagefright/include/MPEG2TSExtractor.h
@@ -9,6 +9,7 @@
namespace android {
+struct AMessage;
struct AnotherPacketSource;
struct ATSParser;
struct DataSource;
@@ -47,7 +48,8 @@
};
bool SniffMPEG2TS(
- const sp<DataSource> &source, String8 *mimeType, float *confidence);
+ const sp<DataSource> &source, String8 *mimeType, float *confidence,
+ sp<AMessage> *);
} // namespace android
diff --git a/media/libstagefright/include/MPEG4Extractor.h b/media/libstagefright/include/MPEG4Extractor.h
index c8663d5..1c9cc7e 100644
--- a/media/libstagefright/include/MPEG4Extractor.h
+++ b/media/libstagefright/include/MPEG4Extractor.h
@@ -23,6 +23,7 @@
namespace android {
+struct AMessage;
class DataSource;
class SampleTable;
class String8;
@@ -75,7 +76,8 @@
};
bool SniffMPEG4(
- const sp<DataSource> &source, String8 *mimeType, float *confidence);
+ const sp<DataSource> &source, String8 *mimeType, float *confidence,
+ sp<AMessage> *);
} // namespace android
diff --git a/media/libstagefright/include/OggExtractor.h b/media/libstagefright/include/OggExtractor.h
index 7066669..1eda025 100644
--- a/media/libstagefright/include/OggExtractor.h
+++ b/media/libstagefright/include/OggExtractor.h
@@ -22,6 +22,7 @@
namespace android {
+struct AMessage;
class DataSource;
class String8;
@@ -53,7 +54,8 @@
};
bool SniffOgg(
- const sp<DataSource> &source, String8 *mimeType, float *confidence);
+ const sp<DataSource> &source, String8 *mimeType, float *confidence,
+ sp<AMessage> *);
} // namespace android
diff --git a/media/libstagefright/include/WAVExtractor.h b/media/libstagefright/include/WAVExtractor.h
index 3e847b9..df6d3e7 100644
--- a/media/libstagefright/include/WAVExtractor.h
+++ b/media/libstagefright/include/WAVExtractor.h
@@ -22,6 +22,7 @@
namespace android {
+struct AMessage;
class DataSource;
class String8;
@@ -58,7 +59,8 @@
};
bool SniffWAV(
- const sp<DataSource> &source, String8 *mimeType, float *confidence);
+ const sp<DataSource> &source, String8 *mimeType, float *confidence,
+ sp<AMessage> *);
} // namespace android
diff --git a/media/libstagefright/matroska/MatroskaExtractor.cpp b/media/libstagefright/matroska/MatroskaExtractor.cpp
index 71f6587..7c7d69e 100644
--- a/media/libstagefright/matroska/MatroskaExtractor.cpp
+++ b/media/libstagefright/matroska/MatroskaExtractor.cpp
@@ -579,7 +579,8 @@
}
bool SniffMatroska(
- const sp<DataSource> &source, String8 *mimeType, float *confidence) {
+ const sp<DataSource> &source, String8 *mimeType, float *confidence,
+ sp<AMessage> *) {
DataSourceReader reader(source);
mkvparser::EBMLHeader ebmlHeader;
long long pos;
diff --git a/media/libstagefright/matroska/MatroskaExtractor.h b/media/libstagefright/matroska/MatroskaExtractor.h
index 7471848..fa20b84 100644
--- a/media/libstagefright/matroska/MatroskaExtractor.h
+++ b/media/libstagefright/matroska/MatroskaExtractor.h
@@ -27,6 +27,7 @@
namespace android {
+struct AMessage;
class String8;
struct DataSourceReader;
@@ -69,7 +70,8 @@
};
bool SniffMatroska(
- const sp<DataSource> &source, String8 *mimeType, float *confidence);
+ const sp<DataSource> &source, String8 *mimeType, float *confidence,
+ sp<AMessage> *);
} // namespace android
diff --git a/media/libstagefright/mpeg2ts/MPEG2TSExtractor.cpp b/media/libstagefright/mpeg2ts/MPEG2TSExtractor.cpp
index b287c95..56ca375 100644
--- a/media/libstagefright/mpeg2ts/MPEG2TSExtractor.cpp
+++ b/media/libstagefright/mpeg2ts/MPEG2TSExtractor.cpp
@@ -174,7 +174,8 @@
////////////////////////////////////////////////////////////////////////////////
bool SniffMPEG2TS(
- const sp<DataSource> &source, String8 *mimeType, float *confidence) {
+ const sp<DataSource> &source, String8 *mimeType, float *confidence,
+ sp<AMessage> *) {
#if 0
char header;
if (source->readAt(0, &header, 1) != 1 || header != 0x47) {
diff --git a/media/libstagefright/rtsp/APacketSource.cpp b/media/libstagefright/rtsp/APacketSource.cpp
index 8c56cb7..b930184 100644
--- a/media/libstagefright/rtsp/APacketSource.cpp
+++ b/media/libstagefright/rtsp/APacketSource.cpp
@@ -406,9 +406,7 @@
const sp<ASessionDescription> &sessionDesc, size_t index)
: mInitCheck(NO_INIT),
mFormat(new MetaData),
- mEOSResult(OK),
- mFirstAccessUnit(true),
- mFirstAccessUnitNTP(0) {
+ mEOSResult(OK) {
unsigned long PT;
AString desc;
AString params;
@@ -550,9 +548,6 @@
}
status_t APacketSource::start(MetaData *params) {
- mFirstAccessUnit = true;
- mFirstAccessUnitNTP = 0;
-
return OK;
}
@@ -600,25 +595,6 @@
return;
}
- uint64_t ntpTime;
- CHECK(buffer->meta()->findInt64(
- "ntp-time", (int64_t *)&ntpTime));
-
- if (mFirstAccessUnit) {
- mFirstAccessUnit = false;
- mFirstAccessUnitNTP = ntpTime;
- }
-
- if (ntpTime > mFirstAccessUnitNTP) {
- ntpTime -= mFirstAccessUnitNTP;
- } else {
- ntpTime = 0;
- }
-
- int64_t timeUs = (int64_t)(ntpTime * 1E6 / (1ll << 32));
-
- buffer->meta()->setInt64("timeUs", timeUs);
-
Mutex::Autolock autoLock(mLock);
mBuffers.push_back(buffer);
mCondition.signal();
@@ -632,31 +608,9 @@
mCondition.signal();
}
-int64_t APacketSource::getQueuedDuration(bool *eos) {
+void APacketSource::flushQueue() {
Mutex::Autolock autoLock(mLock);
-
- *eos = (mEOSResult != OK);
-
- if (mBuffers.empty()) {
- return 0;
- }
-
- sp<ABuffer> buffer = *mBuffers.begin();
-
- uint64_t ntpTime;
- CHECK(buffer->meta()->findInt64(
- "ntp-time", (int64_t *)&ntpTime));
-
- int64_t firstTimeUs = (int64_t)(ntpTime * 1E6 / (1ll << 32));
-
- buffer = *--mBuffers.end();
-
- CHECK(buffer->meta()->findInt64(
- "ntp-time", (int64_t *)&ntpTime));
-
- int64_t lastTimeUs = (int64_t)(ntpTime * 1E6 / (1ll << 32));
-
- return lastTimeUs - firstTimeUs;
+ mBuffers.clear();
}
} // namespace android
diff --git a/media/libstagefright/rtsp/APacketSource.h b/media/libstagefright/rtsp/APacketSource.h
index 647da6e..197af3e 100644
--- a/media/libstagefright/rtsp/APacketSource.h
+++ b/media/libstagefright/rtsp/APacketSource.h
@@ -43,7 +43,7 @@
void queueAccessUnit(const sp<ABuffer> &buffer);
void signalEOS(status_t result);
- int64_t getQueuedDuration(bool *eos);
+ void flushQueue();
protected:
virtual ~APacketSource();
@@ -58,9 +58,6 @@
List<sp<ABuffer> > mBuffers;
status_t mEOSResult;
- bool mFirstAccessUnit;
- uint64_t mFirstAccessUnitNTP;
-
DISALLOW_EVIL_CONSTRUCTORS(APacketSource);
};
diff --git a/media/libstagefright/rtsp/ARTSPController.cpp b/media/libstagefright/rtsp/ARTSPController.cpp
index 195323e..9df17cba 100644
--- a/media/libstagefright/rtsp/ARTSPController.cpp
+++ b/media/libstagefright/rtsp/ARTSPController.cpp
@@ -26,34 +26,70 @@
namespace android {
ARTSPController::ARTSPController(const sp<ALooper> &looper)
- : mLooper(looper) {
+ : mState(DISCONNECTED),
+ mLooper(looper) {
+ mReflector = new AHandlerReflector<ARTSPController>(this);
+ looper->registerHandler(mReflector);
}
ARTSPController::~ARTSPController() {
+ CHECK_EQ((int)mState, (int)DISCONNECTED);
+ mLooper->unregisterHandler(mReflector->id());
}
status_t ARTSPController::connect(const char *url) {
- if (mHandler != NULL) {
+ Mutex::Autolock autoLock(mLock);
+
+ if (mState != DISCONNECTED) {
return ERROR_ALREADY_CONNECTED;
}
+ sp<AMessage> msg = new AMessage(kWhatConnectDone, mReflector->id());
+
mHandler = new MyHandler(url, mLooper);
- mHandler->connect();
- sleep(10);
+ mState = CONNECTING;
- return OK;
+ mHandler->connect(msg);
+
+ while (mState == CONNECTING) {
+ mCondition.wait(mLock);
+ }
+
+ if (mState != CONNECTED) {
+ mHandler.clear();
+ }
+
+ return mConnectionResult;
}
void ARTSPController::disconnect() {
- if (mHandler == NULL) {
+ Mutex::Autolock autoLock(mLock);
+
+ if (mState != CONNECTED) {
return;
}
- mHandler->disconnect();
+ sp<AMessage> msg = new AMessage(kWhatDisconnectDone, mReflector->id());
+ mHandler->disconnect(msg);
+
+ while (mState == CONNECTED) {
+ mCondition.wait(mLock);
+ }
+
mHandler.clear();
}
+void ARTSPController::seek(int64_t timeUs) {
+ Mutex::Autolock autoLock(mLock);
+
+ if (mState != CONNECTED) {
+ return;
+ }
+
+ mHandler->seek(timeUs);
+}
+
size_t ARTSPController::countTracks() {
if (mHandler == NULL) {
return 0;
@@ -75,4 +111,31 @@
return mHandler->getPacketSource(index)->getFormat();
}
+void ARTSPController::onMessageReceived(const sp<AMessage> &msg) {
+ switch (msg->what()) {
+ case kWhatConnectDone:
+ {
+ Mutex::Autolock autoLock(mLock);
+
+ CHECK(msg->findInt32("result", &mConnectionResult));
+ mState = (mConnectionResult == OK) ? CONNECTED : DISCONNECTED;
+
+ mCondition.signal();
+ break;
+ }
+
+ case kWhatDisconnectDone:
+ {
+ Mutex::Autolock autoLock(mLock);
+ mState = DISCONNECTED;
+ mCondition.signal();
+ break;
+ }
+
+ default:
+ TRESPASS();
+ break;
+ }
+}
+
} // namespace android
diff --git a/media/libstagefright/rtsp/MyHandler.h b/media/libstagefright/rtsp/MyHandler.h
index b19ad48..e248463 100644
--- a/media/libstagefright/rtsp/MyHandler.h
+++ b/media/libstagefright/rtsp/MyHandler.h
@@ -38,25 +38,37 @@
mConn(new ARTSPConnection),
mRTPConn(new ARTPConnection),
mSessionURL(url),
- mSetupTracksSuccessful(false) {
+ mSetupTracksSuccessful(false),
+ mSeekPending(false),
+ mFirstAccessUnit(true),
+ mFirstAccessUnitNTP(0) {
mNetLooper->start(false /* runOnCallingThread */,
false /* canCallJava */,
PRIORITY_HIGHEST);
}
- void connect() {
+ void connect(const sp<AMessage> &doneMsg) {
+ mDoneMsg = doneMsg;
+
mLooper->registerHandler(this);
mLooper->registerHandler(mConn);
(1 ? mNetLooper : mLooper)->registerHandler(mRTPConn);
- sp<AMessage> reply = new AMessage('conn', id());
+ sp<AMessage> reply = new AMessage('conn', id());
mConn->connect(mSessionURL.c_str(), reply);
}
- void disconnect() {
- sp<AMessage> reply = new AMessage('disc', id());
- mConn->disconnect(reply);
+ void disconnect(const sp<AMessage> &doneMsg) {
+ mDoneMsg = doneMsg;
+
+ (new AMessage('abor', id()))->post();
+ }
+
+ void seek(int64_t timeUs) {
+ sp<AMessage> msg = new AMessage('seek', id());
+ msg->setInt64("time", timeUs);
+ msg->post();
}
virtual void onMessageReceived(const sp<AMessage> &msg) {
@@ -85,8 +97,6 @@
case 'disc':
{
- LOG(INFO) << "disconnect completed";
-
(new AMessage('quit', id()))->post();
break;
}
@@ -250,8 +260,9 @@
CHECK_EQ(response->mStatusCode, 200u);
- sp<AMessage> msg = new AMessage('abor', id());
- msg->post(60000000ll);
+ mDoneMsg->setInt32("result", OK);
+ mDoneMsg->post();
+ mDoneMsg = NULL;
} else {
sp<AMessage> reply = new AMessage('disc', id());
mConn->disconnect(reply);
@@ -301,6 +312,11 @@
case 'quit':
{
+ if (mDoneMsg != NULL) {
+ mDoneMsg->setInt32("result", UNKNOWN_ERROR);
+ mDoneMsg->post();
+ mDoneMsg = NULL;
+ }
break;
}
@@ -328,7 +344,20 @@
CHECK(accessUnit->meta()->findInt64(
"ntp-time", (int64_t *)&ntpTime));
- accessUnit->meta()->setInt64("ntp-time", ntpTime);
+ if (mFirstAccessUnit) {
+ mFirstAccessUnit = false;
+ mFirstAccessUnitNTP = ntpTime;
+ }
+
+ if (ntpTime >= mFirstAccessUnitNTP) {
+ ntpTime -= mFirstAccessUnitNTP;
+ } else {
+ ntpTime = 0;
+ }
+
+ int64_t timeUs = (int64_t)(ntpTime * 1E6 / (1ll << 32));
+
+ accessUnit->meta()->setInt64("timeUs", timeUs);
#if 0
int32_t damaged;
@@ -344,6 +373,84 @@
break;
}
+ case 'seek':
+ {
+ if (mSeekPending) {
+ break;
+ }
+
+ int64_t timeUs;
+ CHECK(msg->findInt64("time", &timeUs));
+
+ mSeekPending = true;
+
+ AString request = "PAUSE ";
+ request.append(mSessionURL);
+ request.append(" RTSP/1.0\r\n");
+
+ request.append("Session: ");
+ request.append(mSessionID);
+ request.append("\r\n");
+
+ request.append("\r\n");
+
+ sp<AMessage> reply = new AMessage('see1', id());
+ reply->setInt64("time", timeUs);
+ mConn->sendRequest(request.c_str(), reply);
+ break;
+ }
+
+ case 'see1':
+ {
+ int64_t timeUs;
+ CHECK(msg->findInt64("time", &timeUs));
+
+ AString request = "PLAY ";
+ request.append(mSessionURL);
+ request.append(" RTSP/1.0\r\n");
+
+ request.append("Session: ");
+ request.append(mSessionID);
+ request.append("\r\n");
+
+ request.append(
+ StringPrintf(
+ "Range: npt=%lld-\r\n", timeUs / 1000000ll));
+
+ request.append("\r\n");
+
+ sp<AMessage> reply = new AMessage('see2', id());
+ mConn->sendRequest(request.c_str(), reply);
+ break;
+ }
+
+ case 'see2':
+ {
+ CHECK(mSeekPending);
+
+ LOG(INFO) << "seek completed.";
+ mSeekPending = false;
+
+ int32_t result;
+ CHECK(msg->findInt32("result", &result));
+ if (result != OK) {
+ LOG(ERROR) << "seek FAILED";
+ break;
+ }
+
+ sp<RefBase> obj;
+ CHECK(msg->findObject("response", &obj));
+ sp<ARTSPResponse> response =
+ static_cast<ARTSPResponse *>(obj.get());
+
+ CHECK_EQ(response->mStatusCode, 200u);
+
+ for (size_t i = 0; i < mTracks.size(); ++i) {
+ mTracks.editItemAt(i).mPacketSource->flushQueue();
+ }
+ break;
+ }
+
default:
TRESPASS();
break;
@@ -371,6 +478,9 @@
AString mBaseURL;
AString mSessionID;
bool mSetupTracksSuccessful;
+ bool mSeekPending;
+ bool mFirstAccessUnit;
+ uint64_t mFirstAccessUnitNTP;
struct TrackInfo {
int mRTPSocket;
@@ -380,6 +490,8 @@
};
Vector<TrackInfo> mTracks;
+ sp<AMessage> mDoneMsg;
+
void setupTrack(size_t index) {
sp<APacketSource> source =
new APacketSource(mSessionDesc, index);
diff --git a/opengl/java/android/opengl/GLWallpaperService.java b/opengl/java/android/opengl/GLWallpaperService.java
new file mode 100644
index 0000000..c954fed
--- /dev/null
+++ b/opengl/java/android/opengl/GLWallpaperService.java
@@ -0,0 +1,25 @@
+/*
+ * Copyright (C) 2010 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 android.opengl;
+
+/**
+ * reserve this namespace for future use
+ * (making sure external developers don't use it)
+ * @hide
+ */
+class GLWallpaperService {
+}
diff --git a/packages/SettingsProvider/res/values/defaults.xml b/packages/SettingsProvider/res/values/defaults.xml
index 185d72a9..8349fe6 100644
--- a/packages/SettingsProvider/res/values/defaults.xml
+++ b/packages/SettingsProvider/res/values/defaults.xml
@@ -47,7 +47,8 @@
<bool name="def_networks_available_notification_on">true</bool>
<bool name="def_backup_enabled">false</bool>
- <string name="def_backup_transport" translatable="false"></string>
+ <string name="def_backup_transport" translatable="false">android/com.android.internal.backup.LocalTransport</string>
+
<!-- Default value for whether or not to pulse the notification LED when there is a
pending notification -->
<bool name="def_notification_pulse">true</bool>
diff --git a/packages/SettingsProvider/src/com/android/providers/settings/SettingsProvider.java b/packages/SettingsProvider/src/com/android/providers/settings/SettingsProvider.java
index 2e95932..81d82de 100644
--- a/packages/SettingsProvider/src/com/android/providers/settings/SettingsProvider.java
+++ b/packages/SettingsProvider/src/com/android/providers/settings/SettingsProvider.java
@@ -22,6 +22,8 @@
import java.security.SecureRandom;
import java.util.LinkedHashMap;
import java.util.Map;
+import java.util.concurrent.atomic.AtomicBoolean;
+import java.util.concurrent.atomic.AtomicInteger;
import android.app.backup.BackupManager;
import android.content.ContentProvider;
@@ -37,6 +39,7 @@
import android.media.RingtoneManager;
import android.net.Uri;
import android.os.Bundle;
+import android.os.FileObserver;
import android.os.ParcelFileDescriptor;
import android.os.SystemProperties;
import android.provider.DrmStore;
@@ -56,9 +59,15 @@
// Cache for settings, access-ordered for acting as LRU.
// Guarded by themselves.
- private static final int MAX_CACHE_ENTRIES = 50;
- private static final SettingsCache sSystemCache = new SettingsCache();
- private static final SettingsCache sSecureCache = new SettingsCache();
+ private static final int MAX_CACHE_ENTRIES = 200;
+ private static final SettingsCache sSystemCache = new SettingsCache("system");
+ private static final SettingsCache sSecureCache = new SettingsCache("secure");
+
+ // The count of how many known (handled by SettingsProvider)
+ // database mutations are currently being handled. Used by
+ // sFileObserver to not reload the database when it's ourselves
+ // modifying it.
+ private static final AtomicInteger sKnownMutationsInFlight = new AtomicInteger(0);
// Over this size we don't reject loading or saving settings but
// we do consider them broken/malicious and don't keep them in
@@ -67,6 +76,10 @@
private static final Bundle NULL_SETTING = Bundle.forPair("value", null);
+ // Used as a sentinel value in an instance equality test when we
+ // want to cache the existence of a key, but not store its value.
+ private static final Bundle TOO_LARGE_TO_CACHE_MARKER = Bundle.forPair("_dummy", null);
+
protected DatabaseHelper mOpenHelper;
private BackupManager mBackupManager;
@@ -201,6 +214,43 @@
}
}
+ // FileObserver for external modifications to the database file.
+ // Note that this is for platform developers only with
+ // userdebug/eng builds who should be able to tinker with the
+ // sqlite database out from under the SettingsProvider, which is
+ // normally the exclusive owner of the database. But we keep this
+ // enabled all the time to minimize development-vs-user
+ // differences in testing.
+ private static SettingsFileObserver sObserverInstance;
+ private class SettingsFileObserver extends FileObserver {
+ private final AtomicBoolean mIsDirty = new AtomicBoolean(false);
+ private final String mPath;
+
+ public SettingsFileObserver(String path) {
+ super(path, FileObserver.CLOSE_WRITE |
+ FileObserver.CREATE | FileObserver.DELETE |
+ FileObserver.MOVED_TO | FileObserver.MODIFY);
+ mPath = path;
+ }
+
+ public void onEvent(int event, String path) {
+ int modsInFlight = sKnownMutationsInFlight.get();
+ if (modsInFlight > 0) {
+ // our own modification.
+ return;
+ }
+ Log.d(TAG, "external modification to " + mPath + "; event=" + event);
+ if (!mIsDirty.compareAndSet(false, true)) {
+ // already handled. (we get a few update events
+ // during an sqlite write)
+ return;
+ }
+ Log.d(TAG, "updating our caches for " + mPath);
+ fullyPopulateCaches();
+ mIsDirty.set(false);
+ }
+ }
+
@Override
public boolean onCreate() {
mOpenHelper = new DatabaseHelper(getContext());
@@ -210,9 +260,65 @@
return false;
}
+ // Watch for external modifications to the database file,
+ // keeping our cache in sync.
+ // It's kinda lame to call mOpenHelper.getReadableDatabase()
+ // during onCreate(), but since ensureAndroidIdIsSet has
+ // already done it above and initialized/upgraded the
+ // database, might as well just use it...
+ SQLiteDatabase db = mOpenHelper.getReadableDatabase();
+ sObserverInstance = new SettingsFileObserver(db.getPath());
+ sObserverInstance.startWatching();
+ startAsyncCachePopulation();
return true;
}
+ private void startAsyncCachePopulation() {
+ new Thread("populate-settings-caches") {
+ public void run() {
+ fullyPopulateCaches();
+ }
+ }.start();
+ }
+
+ private void fullyPopulateCaches() {
+ fullyPopulateCache("secure", sSecureCache);
+ fullyPopulateCache("system", sSystemCache);
+ }
+
+ // Slurp all values (if sane in number & size) into cache.
+ private void fullyPopulateCache(String table, SettingsCache cache) {
+ SQLiteDatabase db = mOpenHelper.getReadableDatabase();
+ Cursor c = db.query(
+ table,
+ new String[] { Settings.NameValueTable.NAME, Settings.NameValueTable.VALUE },
+ null, null, null, null, null,
+ "" + (MAX_CACHE_ENTRIES + 1) /* limit */);
+ try {
+ synchronized (cache) {
+ cache.clear();
+ cache.setFullyMatchesDisk(true); // optimistic
+ int rows = 0;
+ while (c.moveToNext()) {
+ rows++;
+ String name = c.getString(0);
+ String value = c.getString(1);
+ cache.populate(name, value);
+ }
+ if (rows > MAX_CACHE_ENTRIES) {
+ // Somewhat redundant, as removeEldestEntry() will
+ // have already done this, but to be explicit:
+ cache.setFullyMatchesDisk(false);
+ Log.d(TAG, "row count exceeds max cache entries for table " + table);
+ }
+ Log.d(TAG, "cache for settings table '" + table + "' fullycached=" +
+ cache.fullyMatchesDisk());
+ }
+ } finally {
+ c.close();
+ }
+ }
+
private boolean ensureAndroidIdIsSet() {
final Cursor c = query(Settings.Secure.CONTENT_URI,
new String[] { Settings.NameValueTable.VALUE },
@@ -262,7 +368,19 @@
private Bundle lookupValue(String table, SettingsCache cache, String key) {
synchronized (cache) {
if (cache.containsKey(key)) {
- return cache.get(key);
+ Bundle value = cache.get(key);
+ if (value != TOO_LARGE_TO_CACHE_MARKER) {
+ return value;
+ }
+ // else we fall through and read the value from disk
+ } else if (cache.fullyMatchesDisk()) {
+ // Fast path (very common). Don't even try touch disk
+ // if we know we've slurped it all in. Trying to
+ // touch the disk would mean waiting for yaffs2 to
+ // give us access, which could takes hundreds of
+ // milliseconds. And we're very likely being called
+ // from somebody's UI thread...
+ return NULL_SETTING;
}
}
@@ -338,6 +456,7 @@
checkWritePermissions(args);
SettingsCache cache = SettingsCache.forTable(args.table);
+ sKnownMutationsInFlight.incrementAndGet();
SQLiteDatabase db = mOpenHelper.getWritableDatabase();
db.beginTransaction();
try {
@@ -350,6 +469,7 @@
db.setTransactionSuccessful();
} finally {
db.endTransaction();
+ sKnownMutationsInFlight.decrementAndGet();
}
sendNotify(uri);
@@ -449,8 +569,10 @@
return Uri.withAppendedPath(url, name);
}
+ sKnownMutationsInFlight.incrementAndGet();
SQLiteDatabase db = mOpenHelper.getWritableDatabase();
final long rowId = db.insert(args.table, null, initialValues);
+ sKnownMutationsInFlight.decrementAndGet();
if (rowId <= 0) return null;
SettingsCache.populate(cache, initialValues); // before we notify
@@ -471,12 +593,15 @@
}
checkWritePermissions(args);
+ sKnownMutationsInFlight.incrementAndGet();
SQLiteDatabase db = mOpenHelper.getWritableDatabase();
int count = db.delete(args.table, args.where, args.args);
+ sKnownMutationsInFlight.decrementAndGet();
if (count > 0) {
SettingsCache.wipe(args.table); // before we notify
sendNotify(url);
}
+ startAsyncCachePopulation();
if (LOCAL_LOGV) Log.v(TAG, args.table + ": " + count + " row(s) deleted");
return count;
}
@@ -489,12 +614,15 @@
}
checkWritePermissions(args);
+ sKnownMutationsInFlight.incrementAndGet();
SQLiteDatabase db = mOpenHelper.getWritableDatabase();
+ sKnownMutationsInFlight.decrementAndGet();
int count = db.update(args.table, initialValues, args.where, args.args);
if (count > 0) {
SettingsCache.wipe(args.table); // before we notify
sendNotify(url);
}
+ startAsyncCachePopulation();
if (LOCAL_LOGV) Log.v(TAG, args.table + ": " + count + " row(s) <- " + initialValues);
return count;
}
@@ -506,12 +634,12 @@
* When a client attempts to openFile the default ringtone or
* notification setting Uri, we will proxy the call to the current
* default ringtone's Uri (if it is in the DRM or media provider).
- */
+ */
int ringtoneType = RingtoneManager.getDefaultType(uri);
// Above call returns -1 if the Uri doesn't match a default type
if (ringtoneType != -1) {
Context context = getContext();
-
+
// Get the current value for the default sound
Uri soundUri = RingtoneManager.getActualDefaultRingtoneUri(context, ringtoneType);
@@ -531,7 +659,7 @@
throw new FileNotFoundException(e.getMessage());
}
}
-
+
return context.getContentResolver().openFileDescriptor(soundUri, mode);
}
}
@@ -607,13 +735,38 @@
*/
private static final class SettingsCache extends LinkedHashMap<String, Bundle> {
- public SettingsCache() {
+ private final String mCacheName;
+ private boolean mCacheFullyMatchesDisk = false; // has the whole database slurped.
+
+ public SettingsCache(String name) {
super(MAX_CACHE_ENTRIES, 0.75f /* load factor */, true /* access ordered */);
+ mCacheName = name;
+ }
+
+ /**
+ * Is the whole database table slurped into this cache?
+ */
+ public boolean fullyMatchesDisk() {
+ synchronized (this) {
+ return mCacheFullyMatchesDisk;
+ }
+ }
+
+ public void setFullyMatchesDisk(boolean value) {
+ synchronized (this) {
+ mCacheFullyMatchesDisk = value;
+ }
}
@Override
protected boolean removeEldestEntry(Map.Entry eldest) {
- return size() > MAX_CACHE_ENTRIES;
+ if (size() <= MAX_CACHE_ENTRIES) {
+ return false;
+ }
+ synchronized (this) {
+ mCacheFullyMatchesDisk = false;
+ }
+ return true;
}
/**
@@ -658,11 +811,15 @@
return;
}
String value = contentValues.getAsString(Settings.NameValueTable.VALUE);
- synchronized (cache) {
+ cache.populate(name, value);
+ }
+
+ public void populate(String name, String value) {
+ synchronized (this) {
if (value == null || value.length() <= MAX_CACHE_ENTRY_SIZE) {
- cache.put(name, Bundle.forPair(Settings.NameValueTable.VALUE, value));
+ put(name, Bundle.forPair(Settings.NameValueTable.VALUE, value));
} else {
- cache.remove(name);
+ put(name, TOO_LARGE_TO_CACHE_MARKER);
}
}
}
@@ -678,6 +835,7 @@
}
synchronized (cache) {
cache.clear();
+ cache.mCacheFullyMatchesDisk = true;
}
}
diff --git a/services/java/com/android/server/ConnectivityService.java b/services/java/com/android/server/ConnectivityService.java
index 041c13b..c751f3d 100644
--- a/services/java/com/android/server/ConnectivityService.java
+++ b/services/java/com/android/server/ConnectivityService.java
@@ -889,7 +889,6 @@
}
Intent intent = new Intent(ConnectivityManager.CONNECTIVITY_ACTION);
- intent.addFlags(Intent.FLAG_RECEIVER_REPLACE_PENDING);
intent.putExtra(ConnectivityManager.EXTRA_NETWORK_INFO, info);
if (info.isFailover()) {
intent.putExtra(ConnectivityManager.EXTRA_IS_FAILOVER, true);
@@ -1005,7 +1004,6 @@
private void sendConnectedBroadcast(NetworkInfo info) {
Intent intent = new Intent(ConnectivityManager.CONNECTIVITY_ACTION);
- intent.addFlags(Intent.FLAG_RECEIVER_REPLACE_PENDING);
intent.putExtra(ConnectivityManager.EXTRA_NETWORK_INFO, info);
if (info.isFailover()) {
intent.putExtra(ConnectivityManager.EXTRA_IS_FAILOVER, true);
@@ -1043,7 +1041,6 @@
}
Intent intent = new Intent(ConnectivityManager.CONNECTIVITY_ACTION);
- intent.addFlags(Intent.FLAG_RECEIVER_REPLACE_PENDING);
intent.putExtra(ConnectivityManager.EXTRA_NETWORK_INFO, info);
if (getActiveNetworkInfo() == null) {
intent.putExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY, true);
diff --git a/services/java/com/android/server/WindowManagerService.java b/services/java/com/android/server/WindowManagerService.java
index e259887..9b9d950 100644
--- a/services/java/com/android/server/WindowManagerService.java
+++ b/services/java/com/android/server/WindowManagerService.java
@@ -16,11 +16,6 @@
package com.android.server;
-import static android.os.LocalPowerManager.CHEEK_EVENT;
-import static android.os.LocalPowerManager.OTHER_EVENT;
-import static android.os.LocalPowerManager.TOUCH_EVENT;
-import static android.os.LocalPowerManager.LONG_TOUCH_EVENT;
-import static android.os.LocalPowerManager.TOUCH_UP_EVENT;
import static android.view.WindowManager.LayoutParams.FIRST_APPLICATION_WINDOW;
import static android.view.WindowManager.LayoutParams.FIRST_SUB_WINDOW;
import static android.view.WindowManager.LayoutParams.FLAG_BLUR_BEHIND;
@@ -76,7 +71,6 @@
import android.os.Debug;
import android.os.Handler;
import android.os.IBinder;
-import android.os.LatencyTimer;
import android.os.LocalPowerManager;
import android.os.Looper;
import android.os.Message;
@@ -109,13 +103,11 @@
import android.view.InputChannel;
import android.view.InputDevice;
import android.view.InputEvent;
-import android.view.InputQueue;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.Surface;
import android.view.SurfaceSession;
import android.view.View;
-import android.view.ViewConfiguration;
import android.view.ViewTreeObserver;
import android.view.WindowManager;
import android.view.WindowManagerImpl;
@@ -127,9 +119,13 @@
import android.view.animation.AnimationUtils;
import android.view.animation.Transformation;
+import java.io.BufferedReader;
import java.io.BufferedWriter;
+import java.io.DataInputStream;
import java.io.File;
import java.io.FileDescriptor;
+import java.io.FileInputStream;
+import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
@@ -165,8 +161,6 @@
static final boolean DEBUG_FREEZE = false;
static final boolean SHOW_TRANSACTIONS = false;
static final boolean HIDE_STACK_CRAWLS = true;
- static final boolean MEASURE_LATENCY = false;
- static private LatencyTimer lt;
static final boolean PROFILE_ORIENTATION = false;
static final boolean BLUR = true;
@@ -604,10 +598,6 @@
private WindowManagerService(Context context, PowerManagerService pm,
boolean haveInputMethods) {
- if (MEASURE_LATENCY) {
- lt = new LatencyTimer(100, 1000);
- }
-
mContext = context;
mHaveInputMethods = haveInputMethods;
mLimitedAlphaCompositing = context.getResources().getBoolean(
@@ -4818,6 +4808,8 @@
Parcel data = null;
Parcel reply = null;
+ BufferedWriter out = null;
+
// Any uncaught exception will crash the system process
try {
// Find the hashcode of the window
@@ -4855,6 +4847,12 @@
reply.readException();
+ if (!client.isOutputShutdown()) {
+ out = new BufferedWriter(new OutputStreamWriter(client.getOutputStream()));
+ out.write("DONE\n");
+ out.flush();
+ }
+
} catch (Exception e) {
Slog.w(TAG, "Could not send command " + command + " with parameters " + parameters, e);
success = false;
@@ -4865,6 +4863,13 @@
if (reply != null) {
reply.recycle();
}
+ if (out != null) {
+ try {
+ out.close();
+ } catch (IOException e) {
+
+ }
+ }
}
return success;
@@ -9579,6 +9584,10 @@
Surface.closeTransaction();
+ if (mWatermark != null) {
+ mWatermark.drawIfNeeded();
+ }
+
if (DEBUG_ORIENTATION && mDisplayFrozen) Slog.v(TAG,
"With display frozen, orientationChangeComplete="
+ orientationChangeComplete);
@@ -10072,12 +10081,17 @@
mScreenFrozenLock.release();
}
- static int getPropertyInt(String name, int defUnits, int defDps, DisplayMetrics dm) {
- String str = SystemProperties.get(name);
- try {
- int val = Integer.parseInt(str);
- return val;
- } catch (Exception e) {
+ static int getPropertyInt(String[] tokens, int index, int defUnits, int defDps,
+ DisplayMetrics dm) {
+ if (index < tokens.length) {
+ String str = tokens[index];
+ if (str != null && str.length() > 0) {
+ try {
+ int val = Integer.parseInt(str);
+ return val;
+ } catch (Exception e) {
+ }
+ }
}
if (defUnits == TypedValue.COMPLEX_UNIT_PX) {
return defDps;
@@ -10087,62 +10101,142 @@
}
class Watermark {
- Surface mSurface;
- int mWidth;
- int mHeight;
- int mXPercent;
- int mYPercent;
+ final String[] mTokens;
+ final String mText;
+ final Paint mTextPaint;
+ final int mTextWidth;
+ final int mTextHeight;
+ final int mTextAscent;
+ final int mTextDescent;
+ final int mDeltaX;
+ final int mDeltaY;
- Watermark(SurfaceSession session, String text) {
+ Surface mSurface;
+ int mLastDW;
+ int mLastDH;
+ boolean mDrawNeeded;
+
+ Watermark(SurfaceSession session, String[] tokens) {
final DisplayMetrics dm = new DisplayMetrics();
mDisplay.getMetrics(dm);
- int fontSize = getPropertyInt("ro.watermark.height",
- TypedValue.COMPLEX_UNIT_DIP, 48, dm);
- mXPercent = getPropertyInt("ro.watermark.x",
- TypedValue.COMPLEX_UNIT_PX, 50, dm);
- mYPercent = getPropertyInt("ro.watermark.y",
- TypedValue.COMPLEX_UNIT_PX, 99, dm);
- int color = getPropertyInt("ro.watermark.color",
- TypedValue.COMPLEX_UNIT_PX, 0x80ffffff, dm);
- int shadowRadius = getPropertyInt("ro.watermark.shadow.radius",
- TypedValue.COMPLEX_UNIT_PX, 5, dm);
- int shadowDx = getPropertyInt("ro.watermark.shadow.dx",
- TypedValue.COMPLEX_UNIT_PX, 0, dm);
- int shadowDy = getPropertyInt("ro.watermark.shadow.dy",
- TypedValue.COMPLEX_UNIT_PX, 0, dm);
- int shadowColor = getPropertyInt("ro.watermark.shadow.color",
- TypedValue.COMPLEX_UNIT_PX, 0xff000000, dm);
+ if (false) {
+ Log.i(TAG, "*********************** WATERMARK");
+ for (int i=0; i<tokens.length; i++) {
+ Log.i(TAG, " TOKEN #" + i + ": " + tokens[i]);
+ }
+ }
- Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG);
- paint.setTextSize(fontSize);
- paint.setColor(color);
- paint.setShadowLayer(shadowRadius, shadowDx, shadowDy, shadowColor);
- paint.setTypeface(Typeface.create(Typeface.SANS_SERIF, Typeface.BOLD));
+ mTokens = tokens;
- FontMetricsInt fm = paint.getFontMetricsInt();
- mHeight = fm.descent - fm.ascent + 20;
- mWidth = (int)paint.measureText(text) + 20;
+ StringBuilder builder = new StringBuilder(32);
+ int len = mTokens[0].length();
+ len = len & ~1;
+ for (int i=0; i<len; i+=2) {
+ int c1 = mTokens[0].charAt(i);
+ int c2 = mTokens[0].charAt(i+1);
+ if (c1 >= 'a' && c1 <= 'f') c1 = c1 - 'a' + 10;
+ else if (c1 >= 'A' && c1 <= 'F') c1 = c1 - 'A' + 10;
+ else c1 -= '0';
+ if (c2 >= 'a' && c2 <= 'f') c2 = c2 - 'a' + 10;
+ else if (c2 >= 'A' && c2 <= 'F') c2 = c2 - 'A' + 10;
+ else c2 -= '0';
+ builder.append((char)(255-((c1*16)+c2)));
+ }
+ mText = builder.toString();
+ if (false) {
+ Log.i(TAG, "Final text: " + mText);
+ }
+
+ int fontSize = getPropertyInt(tokens, 1,
+ TypedValue.COMPLEX_UNIT_DIP, 20, dm);
+
+ mTextPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
+ mTextPaint.setTextSize(fontSize);
+ mTextPaint.setTypeface(Typeface.create(Typeface.SANS_SERIF, Typeface.BOLD));
+
+ FontMetricsInt fm = mTextPaint.getFontMetricsInt();
+ mTextWidth = (int)mTextPaint.measureText(mText);
+ mTextAscent = fm.ascent;
+ mTextDescent = fm.descent;
+ mTextHeight = fm.descent - fm.ascent;
+
+ mDeltaX = getPropertyInt(tokens, 2,
+ TypedValue.COMPLEX_UNIT_PX, mTextWidth*2, dm);
+ mDeltaY = getPropertyInt(tokens, 3,
+ TypedValue.COMPLEX_UNIT_PX, mTextHeight*3, dm);
+ int shadowColor = getPropertyInt(tokens, 4,
+ TypedValue.COMPLEX_UNIT_PX, 0xb0000000, dm);
+ int color = getPropertyInt(tokens, 5,
+ TypedValue.COMPLEX_UNIT_PX, 0x60ffffff, dm);
+ int shadowRadius = getPropertyInt(tokens, 6,
+ TypedValue.COMPLEX_UNIT_PX, 7, dm);
+ int shadowDx = getPropertyInt(tokens, 8,
+ TypedValue.COMPLEX_UNIT_PX, 0, dm);
+ int shadowDy = getPropertyInt(tokens, 9,
+ TypedValue.COMPLEX_UNIT_PX, 0, dm);
+
+ mTextPaint.setColor(color);
+ mTextPaint.setShadowLayer(shadowRadius, shadowDx, shadowDy, shadowColor);
try {
mSurface = new Surface(session, 0,
- "WatermarkSurface",
- -1, mWidth, mHeight, PixelFormat.TRANSLUCENT, 0);
+ "WatermarkSurface", -1, 1, 1, PixelFormat.TRANSLUCENT, 0);
mSurface.setLayer(TYPE_LAYER_MULTIPLIER*100);
- Rect dirty = new Rect(0, 0, mWidth, mHeight);
- Canvas c = mSurface.lockCanvas(dirty);
- c.drawText(text, 10, -fm.ascent+10, paint);
- mSurface.unlockCanvasAndPost(c);
+ mSurface.setPosition(0, 0);
mSurface.show();
} catch (OutOfResourcesException e) {
}
}
void positionSurface(int dw, int dh) {
- int availW = dw - mWidth;
- int availH = dh - mHeight;
- mSurface.setPosition((availW*mXPercent)/100,
- (availH*mYPercent)/100);
+ if (mLastDW != dw || mLastDH != dh) {
+ mLastDW = dw;
+ mLastDH = dh;
+ mSurface.setSize(dw, dh);
+ mDrawNeeded = true;
+ }
+ }
+
+ void drawIfNeeded() {
+ if (mDrawNeeded) {
+ final int dw = mLastDW;
+ final int dh = mLastDH;
+
+ mDrawNeeded = false;
+ Rect dirty = new Rect(0, 0, dw, dh);
+ Canvas c = null;
+ try {
+ c = mSurface.lockCanvas(dirty);
+ } catch (IllegalArgumentException e) {
+ } catch (OutOfResourcesException e) {
+ }
+ if (c != null) {
+ int deltaX = mDeltaX;
+ int deltaY = mDeltaY;
+
+ // deltaX shouldn't be close to a round fraction of our
+ // x step, or else things will line up too much.
+ int div = (dw+mTextWidth)/deltaX;
+ int rem = (dw+mTextWidth) - (div*deltaX);
+ int qdelta = deltaX/4;
+ if (rem < qdelta || rem > (deltaX-qdelta)) {
+ deltaX += deltaX/3;
+ }
+
+ int y = -mTextHeight;
+ int x = -mTextWidth;
+ while (y < (dh+mTextHeight)) {
+ c.drawText(mText, x, y, mTextPaint);
+ x += deltaX;
+ if (x >= dw) {
+ x -= (dw+mTextWidth);
+ y += deltaY;
+ }
+ }
+ mSurface.unlockCanvasAndPost(c);
+ }
+ }
}
}
@@ -10151,12 +10245,28 @@
return;
}
- String text = SystemProperties.get("ro.watermark.text");
- if (text == null || text.length() <= 0) {
- return;
+ File file = new File("/system/etc/setup.conf");
+ FileInputStream in = null;
+ try {
+ in = new FileInputStream(file);
+ DataInputStream ind = new DataInputStream(in);
+ String line = ind.readLine();
+ if (line != null) {
+ String[] toks = line.split("%");
+ if (toks != null && toks.length > 0) {
+ mWatermark = new Watermark(mFxSession, toks);
+ }
+ }
+ } catch (FileNotFoundException e) {
+ } catch (IOException e) {
+ } finally {
+ if (in != null) {
+ try {
+ in.close();
+ } catch (IOException e) {
+ }
+ }
}
-
- mWatermark = new Watermark(mFxSession, text);
}
@Override
diff --git a/services/java/com/android/server/am/ActivityManagerService.java b/services/java/com/android/server/am/ActivityManagerService.java
index b37cd89..c316074 100644
--- a/services/java/com/android/server/am/ActivityManagerService.java
+++ b/services/java/com/android/server/am/ActivityManagerService.java
@@ -609,8 +609,8 @@
* All currently bound service connections. Keys are the IBinder of
* the client's IServiceConnection.
*/
- final HashMap<IBinder, ConnectionRecord> mServiceConnections
- = new HashMap<IBinder, ConnectionRecord>();
+ final HashMap<IBinder, ArrayList<ConnectionRecord>> mServiceConnections
+ = new HashMap<IBinder, ArrayList<ConnectionRecord>>();
/**
* List of services that we have been asked to start,
@@ -7376,12 +7376,14 @@
if (mServiceConnections.size() > 0) {
if (needSep) pw.println(" ");
pw.println(" Connection bindings to services:");
- Iterator<ConnectionRecord> it
+ Iterator<ArrayList<ConnectionRecord>> it
= mServiceConnections.values().iterator();
while (it.hasNext()) {
- ConnectionRecord r = it.next();
- pw.print(" * "); pw.println(r);
- r.dump(pw, " ");
+ ArrayList<ConnectionRecord> r = it.next();
+ for (int i=0; i<r.size(); i++) {
+ pw.print(" * "); pw.println(r.get(i));
+ r.get(i).dump(pw, " ");
+ }
}
needSep = true;
}
@@ -7659,18 +7661,21 @@
while (it.hasNext()) {
ServiceRecord r = it.next();
if (r.connections.size() > 0) {
- Iterator<ConnectionRecord> jt
+ Iterator<ArrayList<ConnectionRecord>> jt
= r.connections.values().iterator();
while (jt.hasNext()) {
- ConnectionRecord c = jt.next();
- if (c.binding.client != app) {
- try {
- //c.conn.connected(r.className, null);
- } catch (Exception e) {
- // todo: this should be asynchronous!
- Slog.w(TAG, "Exception thrown disconnected servce "
- + r.shortName
- + " from app " + app.processName, e);
+ ArrayList<ConnectionRecord> cl = jt.next();
+ for (int i=0; i<cl.size(); i++) {
+ ConnectionRecord c = cl.get(i);
+ if (c.binding.client != app) {
+ try {
+ //c.conn.connected(r.className, null);
+ } catch (Exception e) {
+ // todo: this should be asynchronous!
+ Slog.w(TAG, "Exception thrown disconnected servce "
+ + r.shortName
+ + " from app " + app.processName, e);
+ }
}
}
}
@@ -7700,7 +7705,9 @@
}
sr.app = null;
sr.executeNesting = 0;
- mStoppingServices.remove(sr);
+ if (mStoppingServices.remove(sr)) {
+ if (DEBUG_SERVICE) Slog.v(TAG, "killServices remove stopping " + sr);
+ }
boolean hasClients = sr.bindings.size() > 0;
if (hasClients) {
@@ -7753,6 +7760,7 @@
ServiceRecord sr = mStoppingServices.get(i);
if (sr.app == app) {
mStoppingServices.remove(i);
+ if (DEBUG_SERVICE) Slog.v(TAG, "killServices remove stopping " + sr);
}
}
@@ -8016,11 +8024,15 @@
if (r.app != null && r.app.persistent) {
info.flags |= ActivityManager.RunningServiceInfo.FLAG_PERSISTENT_PROCESS;
}
- for (ConnectionRecord conn : r.connections.values()) {
- if (conn.clientLabel != 0) {
- info.clientPackage = conn.binding.client.info.packageName;
- info.clientLabel = conn.clientLabel;
- break;
+
+ for (ArrayList<ConnectionRecord> connl : r.connections.values()) {
+ for (int i=0; i<connl.size(); i++) {
+ ConnectionRecord conn = connl.get(i);
+ if (conn.clientLabel != 0) {
+ info.clientPackage = conn.binding.client.info.packageName;
+ info.clientLabel = conn.clientLabel;
+ return info;
+ }
}
}
return info;
@@ -8055,9 +8067,11 @@
synchronized (this) {
ServiceRecord r = mServices.get(name);
if (r != null) {
- for (ConnectionRecord conn : r.connections.values()) {
- if (conn.clientIntent != null) {
- return conn.clientIntent;
+ for (ArrayList<ConnectionRecord> conn : r.connections.values()) {
+ for (int i=0; i<conn.size(); i++) {
+ if (conn.get(i).clientIntent != null) {
+ return conn.get(i).clientIntent;
+ }
}
}
}
@@ -8234,8 +8248,8 @@
while (r.pendingStarts.size() > 0) {
try {
ServiceRecord.StartItem si = r.pendingStarts.remove(0);
- if (DEBUG_SERVICE) Slog.v(TAG, "Sending arguments to service: "
- + r.name + " " + r.intent + " args=" + si.intent);
+ if (DEBUG_SERVICE) Slog.v(TAG, "Sending arguments to: "
+ + r + " " + r.intent + " args=" + si.intent);
if (si.intent == null) {
// If somehow we got a dummy start at the front, then
// just drop it here.
@@ -8248,6 +8262,7 @@
grantUriPermissionUncheckedFromIntentLocked(si.targetPermissionUid,
r.packageName, si.intent, si);
}
+ if (DEBUG_SERVICE) Slog.v(TAG, ">>> EXECUTING start of " + r);
bumpServiceExecutingLocked(r);
if (!oomAdjusted) {
oomAdjusted = true;
@@ -8264,6 +8279,7 @@
} catch (RemoteException e) {
// Remote process gone... we'll let the normal cleanup take
// care of this.
+ if (DEBUG_SERVICE) Slog.v(TAG, "Crashed while scheduling start: " + r);
break;
} catch (Exception e) {
Slog.w(TAG, "Unexpected exception", e);
@@ -8280,9 +8296,9 @@
}
if ((!i.requested || rebind) && i.apps.size() > 0) {
try {
+ if (DEBUG_SERVICE) Slog.v(TAG, ">>> EXECUTING bind of " + r
+ + " in " + i + ": shouldUnbind=" + i.hasBound);
bumpServiceExecutingLocked(r);
- if (DEBUG_SERVICE) Slog.v(TAG, "Connecting binding " + i
- + ": shouldUnbind=" + i.hasBound);
r.app.thread.scheduleBindService(r, i.intent.getIntent(), rebind);
if (!rebind) {
i.requested = true;
@@ -8290,6 +8306,7 @@
i.hasBound = true;
i.doRebind = false;
} catch (RemoteException e) {
+ if (DEBUG_SERVICE) Slog.v(TAG, "Crashed while binding " + r);
return false;
}
}
@@ -8316,13 +8333,12 @@
r.restartTime = r.lastActivity = SystemClock.uptimeMillis();
app.services.add(r);
+ if (DEBUG_SERVICE) Slog.v(TAG, ">>> EXECUTING create of " + r + " " + r.intent);
bumpServiceExecutingLocked(r);
updateLruProcessLocked(app, true, true);
boolean created = false;
try {
- if (DEBUG_SERVICE) Slog.v(TAG, "Scheduling start service: "
- + r.name + " " + r.intent);
mStringBuilder.setLength(0);
r.intent.getIntent().toShortString(mStringBuilder, false, true);
EventLog.writeEvent(EventLogTags.AM_CREATE_SERVICE,
@@ -8482,8 +8498,7 @@
return true;
}
- if (DEBUG_SERVICE) Slog.v(TAG, "Bringing up service " + r.name
- + " " + r.intent);
+ if (DEBUG_SERVICE) Slog.v(TAG, "Bringing up " + r + " " + r.intent);
// We are now bringing the service up, so no longer in the
// restarting state.
@@ -8534,27 +8549,30 @@
if (!force) {
// XXX should probably keep a count of the number of auto-create
// connections directly in the service.
- Iterator<ConnectionRecord> it = r.connections.values().iterator();
+ Iterator<ArrayList<ConnectionRecord>> it = r.connections.values().iterator();
while (it.hasNext()) {
- ConnectionRecord cr = it.next();
- if ((cr.flags&Context.BIND_AUTO_CREATE) != 0) {
- return;
+ ArrayList<ConnectionRecord> cr = it.next();
+ for (int i=0; i<cr.size(); i++) {
+ if ((cr.get(i).flags&Context.BIND_AUTO_CREATE) != 0) {
+ return;
+ }
}
}
}
// Report to all of the connections that the service is no longer
// available.
- Iterator<ConnectionRecord> it = r.connections.values().iterator();
+ Iterator<ArrayList<ConnectionRecord>> it = r.connections.values().iterator();
while (it.hasNext()) {
- ConnectionRecord c = it.next();
- try {
- // todo: shouldn't be a synchronous call!
- c.conn.connected(r.name, null);
- } catch (Exception e) {
- Slog.w(TAG, "Failure disconnecting service " + r.name +
- " to connection " + c.conn.asBinder() +
- " (in " + c.binding.client.processName + ")", e);
+ ArrayList<ConnectionRecord> c = it.next();
+ for (int i=0; i<c.size(); i++) {
+ try {
+ c.get(i).conn.connected(r.name, null);
+ } catch (Exception e) {
+ Slog.w(TAG, "Failure disconnecting service " + r.name +
+ " to connection " + c.get(i).conn.asBinder() +
+ " (in " + c.get(i).binding.client.processName + ")", e);
+ }
}
}
}
@@ -8568,6 +8586,8 @@
+ ": hasBound=" + ibr.hasBound);
if (r.app != null && r.app.thread != null && ibr.hasBound) {
try {
+ if (DEBUG_SERVICE) Slog.v(TAG, ">>> EXECUTING bring down unbind of " + r
+ + " for " + ibr);
bumpServiceExecutingLocked(r);
updateOomAdjLocked(r.app);
ibr.hasBound = false;
@@ -8582,15 +8602,13 @@
}
}
- if (DEBUG_SERVICE) Slog.v(TAG, "Bringing down service " + r.name
- + " " + r.intent);
+ if (DEBUG_SERVICE) Slog.v(TAG, "Bringing down " + r + " " + r.intent);
EventLog.writeEvent(EventLogTags.AM_DESTROY_SERVICE,
System.identityHashCode(r), r.shortName,
(r.app != null) ? r.app.pid : -1);
mServices.remove(r.name);
mServicesByIntent.remove(r.intent);
- if (localLOGV) Slog.v(TAG, "BRING DOWN SERVICE: " + r.shortName);
r.totalRestartCount = 0;
unscheduleServiceRestartLocked(r);
@@ -8599,8 +8617,7 @@
for (int i=0; i<N; i++) {
if (mPendingServices.get(i) == r) {
mPendingServices.remove(i);
- if (DEBUG_SERVICE) Slog.v(
- TAG, "Removed pending service: " + r.shortName);
+ if (DEBUG_SERVICE) Slog.v(TAG, "Removed pending: " + r);
i--;
N--;
}
@@ -8622,8 +8639,11 @@
r.app.services.remove(r);
if (r.app.thread != null) {
try {
- if (DEBUG_SERVICE) Slog.v(TAG,
- "Stopping service: " + r.shortName);
+ if (DEBUG_SERVICE) {
+ RuntimeException here = new RuntimeException();
+ here.fillInStackTrace();
+ Slog.v(TAG, ">>> EXECUTING stop of " + r, here);
+ }
bumpServiceExecutingLocked(r);
mStoppingServices.add(r);
updateOomAdjLocked(r.app);
@@ -8636,11 +8656,11 @@
updateServiceForegroundLocked(r.app, false);
} else {
if (DEBUG_SERVICE) Slog.v(
- TAG, "Removed service that has no process: " + r.shortName);
+ TAG, "Removed service that has no process: " + r);
}
} else {
if (DEBUG_SERVICE) Slog.v(
- TAG, "Removed service that is not running: " + r.shortName);
+ TAG, "Removed service that is not running: " + r);
}
}
@@ -8675,8 +8695,7 @@
int targetPermissionUid = checkGrantUriPermissionFromIntentLocked(
callingUid, r.packageName, service);
if (unscheduleServiceRestartLocked(r)) {
- if (DEBUG_SERVICE) Slog.v(TAG, "START SERVICE WHILE RESTART PENDING: "
- + r.shortName);
+ if (DEBUG_SERVICE) Slog.v(TAG, "START SERVICE WHILE RESTART PENDING: " + r);
}
r.startRequested = true;
r.callStart = false;
@@ -8970,7 +8989,7 @@
if (unscheduleServiceRestartLocked(s)) {
if (DEBUG_SERVICE) Slog.v(TAG, "BIND SERVICE WHILE RESTART PENDING: "
- + s.shortName);
+ + s);
}
AppBindRecord b = s.retrieveAppBindingLocked(service, callerApp);
@@ -8978,7 +8997,12 @@
connection, flags, clientLabel, clientIntent);
IBinder binder = connection.asBinder();
- s.connections.put(binder, c);
+ ArrayList<ConnectionRecord> clist = s.connections.get(binder);
+ if (clist == null) {
+ clist = new ArrayList<ConnectionRecord>();
+ s.connections.put(binder, clist);
+ }
+ clist.add(c);
b.connections.add(c);
if (activity != null) {
if (activity.connections == null) {
@@ -8987,7 +9011,12 @@
activity.connections.add(c);
}
b.client.connections.add(c);
- mServiceConnections.put(binder, c);
+ clist = mServiceConnections.get(binder);
+ if (clist == null) {
+ clist = new ArrayList<ConnectionRecord>();
+ mServiceConnections.put(binder, clist);
+ }
+ clist.add(c);
if ((flags&Context.BIND_AUTO_CREATE) != 0) {
s.lastActivity = SystemClock.uptimeMillis();
@@ -9038,7 +9067,13 @@
IBinder binder = c.conn.asBinder();
AppBindRecord b = c.binding;
ServiceRecord s = b.service;
- s.connections.remove(binder);
+ ArrayList<ConnectionRecord> clist = s.connections.get(binder);
+ if (clist != null) {
+ clist.remove(c);
+ if (clist.size() == 0) {
+ s.connections.remove(binder);
+ }
+ }
b.connections.remove(c);
if (c.activity != null && c.activity != skipAct) {
if (c.activity.connections != null) {
@@ -9048,7 +9083,13 @@
if (b.client != skipApp) {
b.client.connections.remove(c);
}
- mServiceConnections.remove(binder);
+ clist = mServiceConnections.get(binder);
+ if (clist != null) {
+ clist.remove(c);
+ if (clist.size() == 0) {
+ mServiceConnections.remove(binder);
+ }
+ }
if (b.connections.size() == 0) {
b.intent.apps.remove(b.client);
@@ -9059,6 +9100,8 @@
if (s.app != null && s.app.thread != null && b.intent.apps.size() == 0
&& b.intent.hasBound) {
try {
+ if (DEBUG_SERVICE) Slog.v(TAG, ">>> EXECUTING unbind of " + s
+ + " from " + b);
bumpServiceExecutingLocked(s);
updateOomAdjLocked(s.app);
b.intent.hasBound = false;
@@ -9081,8 +9124,8 @@
synchronized (this) {
IBinder binder = connection.asBinder();
if (DEBUG_SERVICE) Slog.v(TAG, "unbindService: conn=" + binder);
- ConnectionRecord r = mServiceConnections.get(binder);
- if (r == null) {
+ ArrayList<ConnectionRecord> clist = mServiceConnections.get(binder);
+ if (clist == null) {
Slog.w(TAG, "Unbind failed: could not find connection for "
+ connection.asBinder());
return false;
@@ -9090,11 +9133,14 @@
final long origId = Binder.clearCallingIdentity();
- removeConnectionLocked(r, null, null);
+ while (clist.size() > 0) {
+ ConnectionRecord r = clist.get(0);
+ removeConnectionLocked(r, null, null);
- if (r.binding.service.app != null) {
- // This could have made the service less important.
- updateOomAdjLocked(r.binding.service.app);
+ if (r.binding.service.app != null) {
+ // This could have made the service less important.
+ updateOomAdjLocked(r.binding.service.app);
+ }
}
Binder.restoreCallingIdentity(origId);
@@ -9117,7 +9163,7 @@
final long origId = Binder.clearCallingIdentity();
- if (DEBUG_SERVICE) Slog.v(TAG, "PUBLISHING SERVICE " + r.name
+ if (DEBUG_SERVICE) Slog.v(TAG, "PUBLISHING " + r
+ " " + intent + ": " + service);
if (r != null) {
Intent.FilterComparison filter
@@ -9128,26 +9174,29 @@
b.requested = true;
b.received = true;
if (r.connections.size() > 0) {
- Iterator<ConnectionRecord> it
+ Iterator<ArrayList<ConnectionRecord>> it
= r.connections.values().iterator();
while (it.hasNext()) {
- ConnectionRecord c = it.next();
- if (!filter.equals(c.binding.intent.intent)) {
- if (DEBUG_SERVICE) Slog.v(
- TAG, "Not publishing to: " + c);
- if (DEBUG_SERVICE) Slog.v(
- TAG, "Bound intent: " + c.binding.intent.intent);
- if (DEBUG_SERVICE) Slog.v(
- TAG, "Published intent: " + intent);
- continue;
- }
- if (DEBUG_SERVICE) Slog.v(TAG, "Publishing to: " + c);
- try {
- c.conn.connected(r.name, service);
- } catch (Exception e) {
- Slog.w(TAG, "Failure sending service " + r.name +
- " to connection " + c.conn.asBinder() +
- " (in " + c.binding.client.processName + ")", e);
+ ArrayList<ConnectionRecord> clist = it.next();
+ for (int i=0; i<clist.size(); i++) {
+ ConnectionRecord c = clist.get(i);
+ if (!filter.equals(c.binding.intent.intent)) {
+ if (DEBUG_SERVICE) Slog.v(
+ TAG, "Not publishing to: " + c);
+ if (DEBUG_SERVICE) Slog.v(
+ TAG, "Bound intent: " + c.binding.intent.intent);
+ if (DEBUG_SERVICE) Slog.v(
+ TAG, "Published intent: " + intent);
+ continue;
+ }
+ if (DEBUG_SERVICE) Slog.v(TAG, "Publishing to: " + c);
+ try {
+ c.conn.connected(r.name, service);
+ } catch (Exception e) {
+ Slog.w(TAG, "Failure sending service " + r.name +
+ " to connection " + c.conn.asBinder() +
+ " (in " + c.binding.client.processName + ")", e);
+ }
}
}
}
@@ -9208,9 +9257,6 @@
ServiceRecord r = (ServiceRecord)token;
boolean inStopping = mStoppingServices.contains(token);
if (r != null) {
- if (DEBUG_SERVICE) Slog.v(TAG, "DONE EXECUTING SERVICE " + r.name
- + ": nesting=" + r.executeNesting
- + ", inStopping=" + inStopping);
if (r != token) {
Slog.w(TAG, "Done executing service " + r.name
+ " with incorrect token: given " + token
@@ -9267,13 +9313,16 @@
serviceDoneExecutingLocked(r, inStopping);
Binder.restoreCallingIdentity(origId);
} else {
- Slog.w(TAG, "Done executing unknown service " + r.name
- + " with token " + token);
+ Slog.w(TAG, "Done executing unknown service from pid "
+ + Binder.getCallingPid());
}
}
}
public void serviceDoneExecutingLocked(ServiceRecord r, boolean inStopping) {
+ if (DEBUG_SERVICE) Slog.v(TAG, "<<< DONE EXECUTING " + r
+ + ": nesting=" + r.executeNesting
+ + ", inStopping=" + inStopping + ", app=" + r.app);
r.executeNesting--;
if (r.executeNesting <= 0 && r.app != null) {
r.app.executingServices.remove(r);
@@ -9281,6 +9330,7 @@
mHandler.removeMessages(SERVICE_TIMEOUT_MSG, r.app);
}
if (inStopping) {
+ if (DEBUG_SERVICE) Slog.v(TAG, "doneExecuting remove stopping " + r);
mStoppingServices.remove(r);
}
updateOomAdjLocked(r.app);
@@ -11071,61 +11121,64 @@
}
if (s.connections.size() > 0 && (adj > FOREGROUND_APP_ADJ
|| schedGroup == Process.THREAD_GROUP_BG_NONINTERACTIVE)) {
- Iterator<ConnectionRecord> kt
+ Iterator<ArrayList<ConnectionRecord>> kt
= s.connections.values().iterator();
while (kt.hasNext() && adj > FOREGROUND_APP_ADJ) {
- // XXX should compute this based on the max of
- // all connected clients.
- ConnectionRecord cr = kt.next();
- if (cr.binding.client == app) {
- // Binding to ourself is not interesting.
- continue;
- }
- if ((cr.flags&Context.BIND_AUTO_CREATE) != 0) {
- ProcessRecord client = cr.binding.client;
- int myHiddenAdj = hiddenAdj;
- if (myHiddenAdj > client.hiddenAdj) {
- if (client.hiddenAdj >= VISIBLE_APP_ADJ) {
- myHiddenAdj = client.hiddenAdj;
- } else {
- myHiddenAdj = VISIBLE_APP_ADJ;
+ ArrayList<ConnectionRecord> clist = kt.next();
+ for (int i=0; i<clist.size() && adj > FOREGROUND_APP_ADJ; i++) {
+ // XXX should compute this based on the max of
+ // all connected clients.
+ ConnectionRecord cr = clist.get(i);
+ if (cr.binding.client == app) {
+ // Binding to ourself is not interesting.
+ continue;
+ }
+ if ((cr.flags&Context.BIND_AUTO_CREATE) != 0) {
+ ProcessRecord client = cr.binding.client;
+ int myHiddenAdj = hiddenAdj;
+ if (myHiddenAdj > client.hiddenAdj) {
+ if (client.hiddenAdj >= VISIBLE_APP_ADJ) {
+ myHiddenAdj = client.hiddenAdj;
+ } else {
+ myHiddenAdj = VISIBLE_APP_ADJ;
+ }
+ }
+ int clientAdj = computeOomAdjLocked(
+ client, myHiddenAdj, TOP_APP, true);
+ if (adj > clientAdj) {
+ adj = clientAdj >= VISIBLE_APP_ADJ
+ ? clientAdj : VISIBLE_APP_ADJ;
+ if (!client.hidden) {
+ app.hidden = false;
+ }
+ app.adjType = "service";
+ app.adjTypeCode = ActivityManager.RunningAppProcessInfo
+ .REASON_SERVICE_IN_USE;
+ app.adjSource = cr.binding.client;
+ app.adjTarget = s.name;
+ }
+ if ((cr.flags&Context.BIND_NOT_FOREGROUND) == 0) {
+ if (client.curSchedGroup == Process.THREAD_GROUP_DEFAULT) {
+ schedGroup = Process.THREAD_GROUP_DEFAULT;
+ }
}
}
- int clientAdj = computeOomAdjLocked(
- client, myHiddenAdj, TOP_APP, true);
- if (adj > clientAdj) {
- adj = clientAdj >= VISIBLE_APP_ADJ
- ? clientAdj : VISIBLE_APP_ADJ;
- if (!client.hidden) {
- app.hidden = false;
- }
+ ActivityRecord a = cr.activity;
+ //if (a != null) {
+ // Slog.i(TAG, "Connection to " + a ": state=" + a.state);
+ //}
+ if (a != null && adj > FOREGROUND_APP_ADJ &&
+ (a.state == ActivityState.RESUMED
+ || a.state == ActivityState.PAUSING)) {
+ adj = FOREGROUND_APP_ADJ;
+ schedGroup = Process.THREAD_GROUP_DEFAULT;
+ app.hidden = false;
app.adjType = "service";
app.adjTypeCode = ActivityManager.RunningAppProcessInfo
.REASON_SERVICE_IN_USE;
- app.adjSource = cr.binding.client;
+ app.adjSource = a;
app.adjTarget = s.name;
}
- if ((cr.flags&Context.BIND_NOT_FOREGROUND) == 0) {
- if (client.curSchedGroup == Process.THREAD_GROUP_DEFAULT) {
- schedGroup = Process.THREAD_GROUP_DEFAULT;
- }
- }
- }
- ActivityRecord a = cr.activity;
- //if (a != null) {
- // Slog.i(TAG, "Connection to " + a ": state=" + a.state);
- //}
- if (a != null && adj > FOREGROUND_APP_ADJ &&
- (a.state == ActivityState.RESUMED
- || a.state == ActivityState.PAUSING)) {
- adj = FOREGROUND_APP_ADJ;
- schedGroup = Process.THREAD_GROUP_DEFAULT;
- app.hidden = false;
- app.adjType = "service";
- app.adjTypeCode = ActivityManager.RunningAppProcessInfo
- .REASON_SERVICE_IN_USE;
- app.adjSource = a;
- app.adjTarget = s.name;
}
}
}
diff --git a/services/java/com/android/server/am/ServiceRecord.java b/services/java/com/android/server/am/ServiceRecord.java
index 255fbe3..d5b050b 100644
--- a/services/java/com/android/server/am/ServiceRecord.java
+++ b/services/java/com/android/server/am/ServiceRecord.java
@@ -72,8 +72,8 @@
final HashMap<Intent.FilterComparison, IntentBindRecord> bindings
= new HashMap<Intent.FilterComparison, IntentBindRecord>();
// All active bindings to the service.
- final HashMap<IBinder, ConnectionRecord> connections
- = new HashMap<IBinder, ConnectionRecord>();
+ final HashMap<IBinder, ArrayList<ConnectionRecord>> connections
+ = new HashMap<IBinder, ArrayList<ConnectionRecord>>();
// IBinder -> ConnectionRecord of all bound clients
ProcessRecord app; // where this service is running or null.
@@ -296,10 +296,12 @@
}
if (connections.size() > 0) {
pw.print(prefix); pw.println("All Connections:");
- Iterator<ConnectionRecord> it = connections.values().iterator();
+ Iterator<ArrayList<ConnectionRecord>> it = connections.values().iterator();
while (it.hasNext()) {
- ConnectionRecord c = it.next();
- pw.print(prefix); pw.print(" "); pw.println(c);
+ ArrayList<ConnectionRecord> c = it.next();
+ for (int i=0; i<c.size(); i++) {
+ pw.print(prefix); pw.print(" "); pw.println(c.get(i));
+ }
}
}
}
diff --git a/services/java/com/android/server/sip/SipService.java b/services/java/com/android/server/sip/SipService.java
index 1142136..3dcaff6 100644
--- a/services/java/com/android/server/sip/SipService.java
+++ b/services/java/com/android/server/sip/SipService.java
@@ -32,6 +32,7 @@
import android.net.sip.SipSessionAdapter;
import android.net.sip.SipSessionState;
import android.net.wifi.WifiManager;
+import android.os.Binder;
import android.os.Bundle;
import android.os.RemoteException;
import android.os.SystemClock;
@@ -97,6 +98,7 @@
}
public void open(SipProfile localProfile) {
+ localProfile.setCallingUid(Binder.getCallingUid());
if (localProfile.getAutoRegistration()) {
openToReceiveCalls(localProfile);
} else {
@@ -119,6 +121,7 @@
public synchronized void open3(SipProfile localProfile,
String incomingCallBroadcastAction, ISipSessionListener listener) {
+ localProfile.setCallingUid(Binder.getCallingUid());
if (TextUtils.isEmpty(incomingCallBroadcastAction)) {
throw new RuntimeException(
"empty broadcast action for incoming call");
@@ -165,6 +168,7 @@
public synchronized ISipSession createSession(SipProfile localProfile,
ISipSessionListener listener) {
+ localProfile.setCallingUid(Binder.getCallingUid());
if (!mConnected) return null;
try {
SipSessionGroupExt group = createGroup(localProfile);
@@ -362,16 +366,7 @@
private SipProfile duplicate(SipProfile p) {
try {
- return new SipProfile.Builder(p.getUserName(), p.getSipDomain())
- .setProfileName(p.getProfileName())
- .setPassword("*")
- .setPort(p.getPort())
- .setProtocol(p.getProtocol())
- .setOutboundProxy(p.getProxyAddress())
- .setSendKeepAlive(p.getSendKeepAlive())
- .setAutoRegistration(p.getAutoRegistration())
- .setDisplayName(p.getDisplayName())
- .build();
+ return new SipProfile.Builder(p).setPassword("*").build();
} catch (Exception e) {
Log.wtf(TAG, "duplicate()", e);
throw new RuntimeException("duplicate profile", e);
diff --git a/services/surfaceflinger/Layer.cpp b/services/surfaceflinger/Layer.cpp
index 629d993..695cbfa 100644
--- a/services/surfaceflinger/Layer.cpp
+++ b/services/surfaceflinger/Layer.cpp
@@ -162,9 +162,13 @@
const uint32_t hwFlags = hw.getFlags();
mFormat = format;
- mReqFormat = format;
mWidth = w;
mHeight = h;
+
+ mReqFormat = format;
+ mReqWidth = w;
+ mReqHeight = h;
+
mSecure = (flags & ISurfaceComposer::eSecure) ? true : false;
mNeedsBlending = (info.h_alpha - info.l_alpha) > 0;
@@ -196,12 +200,16 @@
} else {
slowpath:
GGLSurface t;
- status_t res = buffer->lock(&t, GRALLOC_USAGE_SW_READ_OFTEN);
- LOGE_IF(res, "error %d (%s) locking buffer %p",
- res, strerror(res), buffer.get());
- if (res == NO_ERROR) {
- mBufferManager.loadTexture(dirty, t);
- buffer->unlock();
+ if (buffer->usage & GRALLOC_USAGE_SW_READ_MASK) {
+ status_t res = buffer->lock(&t, GRALLOC_USAGE_SW_READ_OFTEN);
+ LOGE_IF(res, "error %d (%s) locking buffer %p",
+ res, strerror(res), buffer.get());
+ if (res == NO_ERROR) {
+ mBufferManager.loadTexture(dirty, t);
+ buffer->unlock();
+ }
+ } else {
+ // we can't do anything
}
}
}
@@ -300,16 +308,22 @@
uint32_t w, h, f;
{ // scope for the lock
Mutex::Autolock _l(mLock);
- const bool fixedSizeChanged = mFixedSize != (reqWidth && reqHeight);
- const bool formatChanged = mReqFormat != reqFormat;
- mReqWidth = reqWidth;
- mReqHeight = reqHeight;
- mReqFormat = reqFormat;
- mFixedSize = reqWidth && reqHeight;
- w = reqWidth ? reqWidth : mWidth;
- h = reqHeight ? reqHeight : mHeight;
- f = reqFormat ? reqFormat : mFormat;
- if (fixedSizeChanged || formatChanged) {
+
+ // zero means default
+ if (!reqFormat) reqFormat = mFormat;
+ if (!reqWidth) reqWidth = mWidth;
+ if (!reqHeight) reqHeight = mHeight;
+
+ w = reqWidth;
+ h = reqHeight;
+ f = reqFormat;
+
+ if ((reqWidth != mReqWidth) || (reqHeight != mReqHeight) ||
+ (reqFormat != mReqFormat)) {
+ mReqWidth = reqWidth;
+ mReqHeight = reqHeight;
+ mReqFormat = reqFormat;
+
lcblk->reallocateAllExcept(index);
}
}
@@ -473,9 +487,9 @@
return;
}
- // get the dirty region
sp<GraphicBuffer> newFrontBuffer(getBuffer(buf));
if (newFrontBuffer != NULL) {
+ // get the dirty region
// compute the posted region
const Region dirty(lcblk->getDirtyRegion(buf));
mPostedDirtyRegion = dirty.intersect( newFrontBuffer->getBounds() );
@@ -511,6 +525,13 @@
// we now have the correct size, unfreeze the screen
mFreezeLock.clear();
}
+
+ // get the crop region
+ setBufferCrop( lcblk->getCrop(buf) );
+
+ // get the transformation
+ setBufferTransform( lcblk->getTransform(buf) );
+
} else {
// this should not happen unless we ran out of memory while
// allocating the buffer. we're hoping that things will get back
diff --git a/services/surfaceflinger/LayerBase.cpp b/services/surfaceflinger/LayerBase.cpp
index 91ac915..6fc5010 100644
--- a/services/surfaceflinger/LayerBase.cpp
+++ b/services/surfaceflinger/LayerBase.cpp
@@ -54,6 +54,8 @@
{
const DisplayHardware& hw(flinger->graphicPlane(0).displayHardware());
mFlags = hw.getFlags();
+ mBufferCrop.makeInvalid();
+ mBufferTransform = 0;
}
LayerBase::~LayerBase()
@@ -345,6 +347,14 @@
clearWithOpenGL(clip,0,0,0,0);
}
+template <typename T>
+static inline
+void swap(T& a, T& b) {
+ T t(a);
+ a = b;
+ b = t;
+}
+
void LayerBase::drawWithOpenGL(const Region& clip, const Texture& texture) const
{
const DisplayHardware& hw(graphicPlane(0).displayHardware());
@@ -378,37 +388,72 @@
}
}
- Region::const_iterator it = clip.begin();
- Region::const_iterator const end = clip.end();
- const GLfloat texCoords[4][2] = {
- { 0, 0 },
- { 0, 1 },
- { 1, 1 },
- { 1, 0 }
+ /*
+ * compute texture coordinates
+ * here, we handle NPOT, cropping and buffer transformations
+ */
+
+ GLfloat cl, ct, cr, cb;
+ if (!mBufferCrop.isEmpty()) {
+ // source is cropped
+ const GLfloat us = (texture.NPOTAdjust ? texture.wScale : 1.0f) / width;
+ const GLfloat vs = (texture.NPOTAdjust ? texture.hScale : 1.0f) / height;
+ cl = mBufferCrop.left * us;
+ ct = mBufferCrop.top * vs;
+ cr = mBufferCrop.right * us;
+ cb = mBufferCrop.bottom * vs;
+ } else {
+ cl = 0;
+ ct = 0;
+ cr = (texture.NPOTAdjust ? texture.wScale : 1.0f);
+ cb = (texture.NPOTAdjust ? texture.hScale : 1.0f);
+ }
+
+ struct TexCoords {
+ GLfloat u;
+ GLfloat v;
};
- glMatrixMode(GL_TEXTURE);
- glLoadIdentity();
+ enum {
+ // name of the corners in the texture map
+ LB = 0, // left-bottom
+ LT = 1, // left-top
+ RT = 2, // right-top
+ RB = 3 // right-bottom
+ };
+
+ // vertices in screen space
+ int vLT = LB;
+ int vLB = LT;
+ int vRB = RT;
+ int vRT = RB;
// the texture's source is rotated
- switch (texture.transform) {
- case HAL_TRANSFORM_ROT_90:
- glTranslatef(0, 1, 0);
- glRotatef(-90, 0, 0, 1);
- break;
- case HAL_TRANSFORM_ROT_180:
- glTranslatef(1, 1, 0);
- glRotatef(-180, 0, 0, 1);
- break;
- case HAL_TRANSFORM_ROT_270:
- glTranslatef(1, 0, 0);
- glRotatef(-270, 0, 0, 1);
- break;
+ uint32_t transform = mBufferTransform;
+ if (transform & HAL_TRANSFORM_ROT_90) {
+ vLT = RB;
+ vLB = LB;
+ vRB = LT;
+ vRT = RT;
+ }
+ if (transform & HAL_TRANSFORM_FLIP_V) {
+ swap(vLT, vLB);
+ swap(vRB, vRT);
+ }
+ if (transform & HAL_TRANSFORM_FLIP_H) {
+ swap(vLT, vRB);
+ swap(vLB, vRT);
}
- if (texture.NPOTAdjust) {
- glScalef(texture.wScale, texture.hScale, 1.0f);
- }
+ TexCoords texCoords[4];
+ texCoords[vLT].u = cl;
+ texCoords[vLT].v = ct;
+ texCoords[vLB].u = cl;
+ texCoords[vLB].v = cb;
+ texCoords[vRB].u = cr;
+ texCoords[vRB].v = cb;
+ texCoords[vRT].u = cr;
+ texCoords[vRT].v = ct;
if (needsDithering()) {
glEnable(GL_DITHER);
@@ -420,6 +465,8 @@
glVertexPointer(2, GL_FLOAT, 0, mVertices);
glTexCoordPointer(2, GL_FLOAT, 0, texCoords);
+ Region::const_iterator it = clip.begin();
+ Region::const_iterator const end = clip.end();
while (it != end) {
const Rect& r = *it++;
const GLint sy = fbHeight - (r.top + r.height());
@@ -429,6 +476,16 @@
glDisableClientState(GL_TEXTURE_COORD_ARRAY);
}
+void LayerBase::setBufferCrop(const Rect& crop) {
+ if (!crop.isEmpty()) {
+ mBufferCrop = crop;
+ }
+}
+
+void LayerBase::setBufferTransform(uint32_t transform) {
+ mBufferTransform = transform;
+}
+
void LayerBase::dump(String8& result, char* buffer, size_t SIZE) const
{
const Layer::State& s(drawingState());
diff --git a/services/surfaceflinger/LayerBase.h b/services/surfaceflinger/LayerBase.h
index 22bf857..8cba287 100644
--- a/services/surfaceflinger/LayerBase.h
+++ b/services/surfaceflinger/LayerBase.h
@@ -226,9 +226,17 @@
void clearWithOpenGL(const Region& clip) const;
void drawWithOpenGL(const Region& clip, const Texture& texture) const;
+ // these must be called from the post/drawing thread
+ void setBufferCrop(const Rect& crop);
+ void setBufferTransform(uint32_t transform);
+
sp<SurfaceFlinger> mFlinger;
uint32_t mFlags;
+ // post/drawing thread
+ Rect mBufferCrop;
+ uint32_t mBufferTransform;
+
// cached during validateVisibility()
bool mNeedsFiltering;
int32_t mOrientation;
diff --git a/services/surfaceflinger/LayerBlur.cpp b/services/surfaceflinger/LayerBlur.cpp
index 64a43c7..2ee21b9 100644
--- a/services/surfaceflinger/LayerBlur.cpp
+++ b/services/surfaceflinger/LayerBlur.cpp
@@ -241,6 +241,8 @@
glDrawArrays(GL_TRIANGLE_FAN, 0, 4);
}
glDisableClientState(GL_TEXTURE_COORD_ARRAY);
+ glLoadIdentity();
+ glMatrixMode(GL_MODELVIEW);
}
}
diff --git a/services/surfaceflinger/LayerBuffer.cpp b/services/surfaceflinger/LayerBuffer.cpp
index 5f836366..0240748 100644
--- a/services/surfaceflinger/LayerBuffer.cpp
+++ b/services/surfaceflinger/LayerBuffer.cpp
@@ -485,7 +485,7 @@
mTextureManager.loadTexture(&mTexture, dirty, t);
}
- mTexture.transform = mBufferHeap.transform;
+ mLayer.setBufferTransform(mBufferHeap.transform);
mLayer.drawWithOpenGL(clip, mTexture);
}
diff --git a/services/surfaceflinger/TextureManager.h b/services/surfaceflinger/TextureManager.h
index c7c14e7..18c43486 100644
--- a/services/surfaceflinger/TextureManager.h
+++ b/services/surfaceflinger/TextureManager.h
@@ -40,12 +40,11 @@
struct Image {
enum { TEXTURE_2D=0, TEXTURE_EXTERNAL=1 };
Image() : name(-1U), image(EGL_NO_IMAGE_KHR), width(0), height(0),
- transform(0), dirty(1), target(TEXTURE_2D) { }
+ dirty(1), target(TEXTURE_2D) { }
GLuint name;
EGLImageKHR image;
GLuint width;
GLuint height;
- uint32_t transform;
unsigned dirty : 1;
unsigned target : 1;
};
diff --git a/telephony/java/com/android/internal/telephony/CallManager.java b/telephony/java/com/android/internal/telephony/CallManager.java
index 8e08592..12df44e 100644
--- a/telephony/java/com/android/internal/telephony/CallManager.java
+++ b/telephony/java/com/android/internal/telephony/CallManager.java
@@ -322,7 +322,9 @@
}
break;
}
- audioManager.setMode(mode);
+ // calling audioManager.setMode() multiple times in a short period of
+ // time seems to break the audio recorder in in-call mode
+ if (audioManager.getMode() != mode) audioManager.setMode(mode);
}
private Context getContext() {
@@ -689,8 +691,8 @@
* Stop the playing DTMF tone. Ignored if there is no playing DTMF
* tone or no active call.
*/
- public void stopDtmf(Phone phone) {
- phone.stopDtmf();
+ public void stopDtmf() {
+ if (hasActiveFgCall()) getFgPhone().stopDtmf();
}
/**
@@ -707,7 +709,7 @@
* @param onComplete is the callback message when the action is processed by BP
*
*/
- public boolean sendBurstDtmf(Phone phone, String dtmfString, int on, int off, Message onComplete) {
+ public boolean sendBurstDtmf(String dtmfString, int on, int off, Message onComplete) {
if (hasActiveFgCall()) {
getActiveFgCall().getPhone().sendBurstDtmf(dtmfString, on, off, onComplete);
return true;
diff --git a/telephony/java/com/android/internal/telephony/sip/SipConnectionBase.java b/telephony/java/com/android/internal/telephony/sip/SipConnectionBase.java
index d48f94a..6c989b4 100644
--- a/telephony/java/com/android/internal/telephony/sip/SipConnectionBase.java
+++ b/telephony/java/com/android/internal/telephony/sip/SipConnectionBase.java
@@ -85,8 +85,10 @@
protected void setState(Call.State state) {
switch (state) {
case ACTIVE:
- connectTimeReal = SystemClock.elapsedRealtime();
- connectTime = System.currentTimeMillis();
+ if (connectTime == 0) {
+ connectTimeReal = SystemClock.elapsedRealtime();
+ connectTime = System.currentTimeMillis();
+ }
break;
case DISCONNECTED:
duration = SystemClock.elapsedRealtime() - connectTimeReal;
diff --git a/telephony/java/com/android/internal/telephony/sip/SipPhone.java b/telephony/java/com/android/internal/telephony/sip/SipPhone.java
index a052db0..1325dd3 100755
--- a/telephony/java/com/android/internal/telephony/sip/SipPhone.java
+++ b/telephony/java/com/android/internal/telephony/sip/SipPhone.java
@@ -100,7 +100,7 @@
}
public String getPhoneName() {
- return mProfile.getProfileName();
+ return "SIP:" + getUriString(mProfile);
}
public String getSipUri() {
@@ -222,21 +222,25 @@
}
public void conference() throws CallStateException {
- if ((foregroundCall.getState() != SipCall.State.ACTIVE)
- || (foregroundCall.getState() != SipCall.State.ACTIVE)) {
- throw new CallStateException("wrong state to merge calls: fg="
- + foregroundCall.getState() + ", bg="
- + backgroundCall.getState());
+ synchronized (SipPhone.class) {
+ if ((foregroundCall.getState() != SipCall.State.ACTIVE)
+ || (foregroundCall.getState() != SipCall.State.ACTIVE)) {
+ throw new CallStateException("wrong state to merge calls: fg="
+ + foregroundCall.getState() + ", bg="
+ + backgroundCall.getState());
+ }
+ foregroundCall.merge(backgroundCall);
}
- foregroundCall.merge(backgroundCall);
}
public void conference(Call that) throws CallStateException {
- if (!(that instanceof SipCall)) {
- throw new CallStateException("expect " + SipCall.class
- + ", cannot merge with " + that.getClass());
+ synchronized (SipPhone.class) {
+ if (!(that instanceof SipCall)) {
+ throw new CallStateException("expect " + SipCall.class
+ + ", cannot merge with " + that.getClass());
+ }
+ foregroundCall.merge((SipCall) that);
}
- foregroundCall.merge((SipCall) that);
}
public boolean canTransfer() {
@@ -248,12 +252,14 @@
}
public void clearDisconnected() {
- ringingCall.clearDisconnected();
- foregroundCall.clearDisconnected();
- backgroundCall.clearDisconnected();
+ synchronized (SipPhone.class) {
+ ringingCall.clearDisconnected();
+ foregroundCall.clearDisconnected();
+ backgroundCall.clearDisconnected();
- updatePhoneState();
- notifyPreciseCallStateChanged();
+ updatePhoneState();
+ notifyPreciseCallStateChanged();
+ }
}
public void sendDtmf(char c) {
@@ -261,7 +267,9 @@
Log.e(LOG_TAG,
"sendDtmf called with invalid character '" + c + "'");
} else if (foregroundCall.getState().isAlive()) {
- foregroundCall.sendDtmf(c);
+ synchronized (SipPhone.class) {
+ foregroundCall.sendDtmf(c);
+ }
}
}
@@ -307,7 +315,9 @@
}
public void setMute(boolean muted) {
- foregroundCall.setMute(muted);
+ synchronized (SipPhone.class) {
+ foregroundCall.setMute(muted);
+ }
}
public boolean getMute() {
@@ -410,18 +420,20 @@
@Override
public void hangup() throws CallStateException {
- Log.v(LOG_TAG, "hang up call: " + getState() + ": " + this
- + " on phone " + getPhone());
- CallStateException excp = null;
- for (Connection c : connections) {
- try {
- c.hangup();
- } catch (CallStateException e) {
- excp = e;
+ synchronized (SipPhone.class) {
+ Log.v(LOG_TAG, "hang up call: " + getState() + ": " + this
+ + " on phone " + getPhone());
+ CallStateException excp = null;
+ for (Connection c : connections) {
+ try {
+ c.hangup();
+ } catch (CallStateException e) {
+ excp = e;
+ }
}
+ if (excp != null) throw excp;
+ setState(State.DISCONNECTING);
}
- if (excp != null) throw excp;
- setState(State.DISCONNECTING);
}
void initIncomingCall(SipAudioCall sipAudioCall, boolean makeCallWait) {
@@ -454,19 +466,20 @@
}
void hold() throws CallStateException {
- AudioGroup audioGroup = getAudioGroup();
- if (audioGroup == null) return;
- audioGroup.setMode(AudioGroup.MODE_ON_HOLD);
setState(State.HOLDING);
+ AudioGroup audioGroup = getAudioGroup();
+ if (audioGroup != null) {
+ audioGroup.setMode(AudioGroup.MODE_ON_HOLD);
+ }
for (Connection c : connections) ((SipConnection) c).hold();
}
void unhold() throws CallStateException {
- AudioGroup audioGroup = getAudioGroup();
- if (audioGroup == null) return;
- audioGroup.setMode(AudioGroup.MODE_NORMAL);
setState(State.ACTIVE);
- for (Connection c : connections) ((SipConnection) c).unhold();
+ AudioGroup audioGroup = new AudioGroup();
+ for (Connection c : connections) {
+ ((SipConnection) c).unhold(audioGroup);
+ }
}
void setMute(boolean muted) {
@@ -483,17 +496,26 @@
}
void merge(SipCall that) throws CallStateException {
- AudioGroup myGroup = getAudioGroup();
+ AudioGroup audioGroup = getAudioGroup();
for (Connection c : that.connections) {
SipConnection conn = (SipConnection) c;
- conn.mergeTo(myGroup);
- connections.add(conn);
- conn.changeOwner(this);
+ add(conn);
+ if (conn.getState() == Call.State.HOLDING) {
+ conn.unhold(audioGroup);
+ }
}
- that.connections.clear();
that.setState(Call.State.IDLE);
}
+ private void add(SipConnection conn) {
+ SipCall call = conn.getCall();
+ if (call == this) return;
+ if (call != null) call.connections.remove(conn);
+
+ connections.add(conn);
+ conn.changeOwner(this);
+ }
+
void sendDtmf(char c) {
AudioGroup audioGroup = getAudioGroup();
if (audioGroup == null) return;
@@ -568,7 +590,6 @@
private class SipConnection extends SipConnectionBase {
private SipCall mOwner;
private SipAudioCall mSipAudioCall;
- private AudioGroup mOriginalGroup;
private Call.State mState = Call.State.IDLE;
private SipProfile mPeer;
private boolean mIncoming = false;
@@ -673,6 +694,7 @@
}
void hold() throws CallStateException {
+ setState(Call.State.HOLDING);
try {
mSipAudioCall.holdCall();
} catch (SipException e) {
@@ -680,7 +702,9 @@
}
}
- void unhold() throws CallStateException {
+ void unhold(AudioGroup audioGroup) throws CallStateException {
+ mSipAudioCall.setAudioGroup(audioGroup);
+ setState(Call.State.ACTIVE);
try {
mSipAudioCall.continueCall();
} catch (SipException e) {
@@ -688,16 +712,6 @@
}
}
- void mergeTo(AudioGroup group) throws CallStateException {
- AudioStream stream = mSipAudioCall.getAudioStream();
- if (stream == null) {
- throw new CallStateException("wrong state to merge: "
- + mSipAudioCall.getState());
- }
- if (mOriginalGroup == null) mOriginalGroup = getAudioGroup();
- stream.join(group);
- }
-
@Override
protected void setState(Call.State state) {
if (state == mState) return;
@@ -732,29 +746,36 @@
@Override
public void hangup() throws CallStateException {
- // TODO: need to pull AudioStream out of the AudioGroup in case
- // this conn was part of a conf call
- Log.v(LOG_TAG, "hangup conn: " + mPeer.getUriString() + ": "
- + ": on phone " + getPhone());
- try {
- mSipAudioCall.endCall();
- setState(Call.State.DISCONNECTING);
- setDisconnectCause(DisconnectCause.LOCAL);
- } catch (SipException e) {
- throw new CallStateException("hangup(): " + e);
+ synchronized (SipPhone.class) {
+ Log.v(LOG_TAG, "hangup conn: " + mPeer.getUriString() + ": "
+ + ": on phone " + getPhone().getPhoneName());
+ try {
+ mSipAudioCall.endCall();
+ setState(Call.State.DISCONNECTING);
+ setDisconnectCause(DisconnectCause.LOCAL);
+ } catch (SipException e) {
+ throw new CallStateException("hangup(): " + e);
+ }
}
}
@Override
public void separate() throws CallStateException {
- // TODO: what's this for SIP?
- /*
- if (!disconnected) {
- owner.separate(this);
- } else {
- throw new CallStateException ("disconnected");
+ synchronized (SipPhone.class) {
+ SipCall call = (SipCall) SipPhone.this.getBackgroundCall();
+ if (call.getState() != Call.State.IDLE) {
+ throw new CallStateException(
+ "cannot put conn back to a call in non-idle state: "
+ + call.getState());
+ }
+ Log.v(LOG_TAG, "separate conn: " + mPeer.getUriString()
+ + " from " + mOwner + " back to " + call);
+
+ AudioGroup audioGroup = call.getAudioGroup(); // may be null
+ call.add(this);
+ mSipAudioCall.setAudioGroup(audioGroup);
+ call.hold();
}
- */
}
@Override
diff --git a/telephony/java/com/android/internal/telephony/sip/SipPhoneBase.java b/telephony/java/com/android/internal/telephony/sip/SipPhoneBase.java
index 36d65db..4b7e991 100755
--- a/telephony/java/com/android/internal/telephony/sip/SipPhoneBase.java
+++ b/telephony/java/com/android/internal/telephony/sip/SipPhoneBase.java
@@ -175,10 +175,6 @@
return state;
}
- public String getPhoneName() {
- return "SIP";
- }
-
public int getPhoneType() {
// FIXME: add SIP phone type
return Phone.PHONE_TYPE_GSM;
diff --git a/tests/CoreTests/android/core/JavaPerformanceTests.java b/tests/CoreTests/android/core/JavaPerformanceTests.java
index fbe70cc..95075ea 100644
--- a/tests/CoreTests/android/core/JavaPerformanceTests.java
+++ b/tests/CoreTests/android/core/JavaPerformanceTests.java
@@ -23,7 +23,6 @@
public static String[] children() {
return new String[] {
- StringTest.class.getName(),
HashMapPerformanceTest.class.getName(),
ArrayListPerformanceTest.class.getName(),
TreeMapPerformanceTest.class.getName(),
diff --git a/tests/CoreTests/android/core/StringTest.java b/tests/CoreTests/android/core/StringTest.java
deleted file mode 100644
index 128531c..0000000
--- a/tests/CoreTests/android/core/StringTest.java
+++ /dev/null
@@ -1,951 +0,0 @@
-/*
- * Copyright (C) 2007 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 android.core;
-
-import java.util.Locale;
-
-import android.test.PerformanceTestBase;
-import android.test.PerformanceTestCase;
-
-public class StringTest extends PerformanceTestBase {
- public static final int ITERATIONS = 1000;
- public static final String STATIC_STRING_01 = "Hello Android";
- public static final String STATIC_STRING_02 =
- "Remember, today is the tomorrow you worried about yesterday";
- public static final char[] STATIC_CHAR_ARRAY =
- {'N', 'A', 'N', 'D', 'R', 'O', 'I', 'D'};
- public static StringBuffer STATIC_SBUF = new StringBuffer(STATIC_STRING_02);
-
- @Override
- public int startPerformance(PerformanceTestCase.Intermediates intermediates) {
- intermediates.setInternalIterations(ITERATIONS);
- return 0;
- }
-
- /** Create an empty String object* */
-
- public void testStringCreate() {
- String rString;
- for (int i = ITERATIONS - 1; i >= 0; i--) {
- rString = new String();
- rString = new String();
- rString = new String();
- rString = new String();
- rString = new String();
- rString = new String();
- rString = new String();
- rString = new String();
- rString = new String();
- rString = new String();
- }
- }
-
- /** Create an initialised String object* */
-
- public void testStringCreate1() {
- String rString, str = STATIC_STRING_01;
- for (int i = ITERATIONS - 1; i >= 0; i--) {
- rString = new String(str);
- rString = new String(str);
- rString = new String(str);
- rString = new String(str);
- rString = new String(str);
- rString = new String(str);
- rString = new String(str);
- rString = new String(str);
- rString = new String(str);
- rString = new String(str); // 10
- }
- }
-
- /** equals() with for loop* */
- public void testStringEquals() {
- String mString = new String(STATIC_STRING_01);
- String str = STATIC_STRING_01;
- boolean result;
- for (int i = ITERATIONS - 1; i >= 0; i--) {
- result = mString.equals(str);
- result = mString.equals(str);
- result = mString.equals(str);
- result = mString.equals(str);
- result = mString.equals(str);
- result = mString.equals(str);
- result = mString.equals(str);
- result = mString.equals(str);
- result = mString.equals(str);
- result = mString.equals(str);
- }
- }
-
- /**
- * ContentEquals- Comparing the content of a String with that of a String
- * Buffer*
- */
-
- public void testStringContentEquals() {
- StringBuffer sBuf = new StringBuffer(STATIC_STRING_01);
- String str = STATIC_STRING_01;
- boolean result;
- for (int i = ITERATIONS - 1; i >= 0; i--) {
- result = str.contentEquals(sBuf);
- result = str.contentEquals(sBuf);
- result = str.contentEquals(sBuf);
- result = str.contentEquals(sBuf);
- result = str.contentEquals(sBuf);
- result = str.contentEquals(sBuf);
- result = str.contentEquals(sBuf);
- result = str.contentEquals(sBuf);
- result = str.contentEquals(sBuf);
- result = str.contentEquals(sBuf);
- }
- }
-
- /** Compare string objects lexicographically using compareTo() with for loop* */
-
- public void testStringCompareTo() {
- String str1 = new String(STATIC_STRING_01);
- String str2 = STATIC_STRING_01;
- int result;
- for (int i = ITERATIONS - 1; i >= 0; i--) {
- result = str1.compareTo(str2);
- result = str1.compareTo(str2);
- result = str1.compareTo(str2);
- result = str1.compareTo(str2);
- result = str1.compareTo(str2);
- result = str1.compareTo(str2);
- result = str1.compareTo(str2);
- result = str1.compareTo(str2);
- result = str1.compareTo(str2);
- result = str1.compareTo(str2);
- }
-
- }
-
- /** Compare string objects using compareToIgnorecase() with for loop* */
-
- public void testStringCompareToIgnoreCase() {
- String mString = new String(STATIC_STRING_01);
- String str2 = STATIC_STRING_01;
- int result;
- for (int i = ITERATIONS - 1; i >= 0; i--) {
- result = mString.compareToIgnoreCase(str2);
- result = mString.compareToIgnoreCase(str2);
- result = mString.compareToIgnoreCase(str2);
- result = mString.compareToIgnoreCase(str2);
- result = mString.compareToIgnoreCase(str2);
- result = mString.compareToIgnoreCase(str2);
- result = mString.compareToIgnoreCase(str2);
- result = mString.compareToIgnoreCase(str2);
- result = mString.compareToIgnoreCase(str2);
- result = mString.compareToIgnoreCase(str2);
- }
- }
-
- /** startsWith * */
-
- public void testStringstartsWith() {
- boolean result;
- String str1 = STATIC_STRING_02, str2 = "Rem";
- for (int i = ITERATIONS - 1; i >= 0; i--) {
- result = str1.startsWith(str2);
- result = str1.startsWith(str2);
- result = str1.startsWith(str2);
- result = str1.startsWith(str2);
- result = str1.startsWith(str2);
- result = str1.startsWith(str2);
- result = str1.startsWith(str2);
- result = str1.startsWith(str2);
- result = str1.startsWith(str2);
- result = str1.startsWith(str2);
- }
- }
-
- /** startsWith(String seq, int begin) * */
-
- public void testStringstartsWith1() {
- String str1 = STATIC_STRING_02, str2 = "tom";
- int pos = 10;
- boolean result;
- for (int i = ITERATIONS - 1; i >= 0; i--) {
- result = str1.startsWith(str2, pos);
- result = str1.startsWith(str2, pos);
- result = str1.startsWith(str2, pos);
- result = str1.startsWith(str2, pos);
- result = str1.startsWith(str2, pos);
- result = str1.startsWith(str2, pos);
- result = str1.startsWith(str2, pos);
- result = str1.startsWith(str2, pos);
- result = str1.startsWith(str2, pos);
- result = str1.startsWith(str2, pos);
- }
- }
-
- /** endsWith * */
-
- public void testStringendsWith() {
- String str = STATIC_STRING_02, str1 = "day";
- boolean result;
- for (int i = ITERATIONS - 1; i >= 0; i--) {
- result = str.endsWith(str1);
- result = str.endsWith(str1);
- result = str.endsWith(str1);
- result = str.endsWith(str1);
- result = str.endsWith(str1);
- result = str.endsWith(str1);
- result = str.endsWith(str1);
- result = str.endsWith(str1);
- result = str.endsWith(str1);
- result = str.endsWith(str1);
- }
- }
-
- /**
- * indexOf to determine whether a string contains a substring
- */
- public void testStringindexOf() {
- boolean result;
- String str = STATIC_STRING_02, str1 = "tomo";
- for (int i = ITERATIONS - 1; i >= 0; i--) {
- result = str.indexOf(str1) > 0;
- result = str.indexOf(str1) > 0;
- result = str.indexOf(str1) > 0;
- result = str.indexOf(str1) > 0;
- result = str.indexOf(str1) > 0;
- result = str.indexOf(str1) > 0;
- result = str.indexOf(str1) > 0;
- result = str.indexOf(str1) > 0;
- result = str.indexOf(str1) > 0;
- result = str.indexOf(str1) > 0;
- }
- }
-
- /** indexOf()* */
-
- public void testStringindexOf1() {
- int index;
- String str = STATIC_STRING_02;
- char c = 't';
- for (int i = ITERATIONS - 1; i >= 0; i--) {
- index = str.indexOf(c);
- index = str.indexOf(c);
- index = str.indexOf(c);
- index = str.indexOf(c);
- index = str.indexOf(c);
- index = str.indexOf(c);
- index = str.indexOf(c);
- index = str.indexOf(c);
- index = str.indexOf(c);
- index = str.indexOf(c);
- }
-
- }
-
- /** indexOf(char c, int start)* */
- public void testStringindexOf2() {
- int index, pos = 12;
- String str = STATIC_STRING_02, str1 = "tom";
- for (int i = ITERATIONS - 1; i >= 0; i--) {
- index = str.indexOf(str1, pos);
- index = str.indexOf(str1, pos);
- index = str.indexOf(str1, pos);
- index = str.indexOf(str1, pos);
- index = str.indexOf(str1, pos);
- index = str.indexOf(str1, pos);
- index = str.indexOf(str1, pos);
- index = str.indexOf(str1, pos);
- index = str.indexOf(str1, pos);
- index = str.indexOf(str1, pos);
- }
- }
-
- /** lastIndexOf()* */
-
- public void testStringlastIndexOf() {
- int index;
- char c = 't';
- String str = STATIC_STRING_02;
- for (int i = ITERATIONS - 1; i >= 0; i--) {
- index = str.lastIndexOf(c);
- index = str.lastIndexOf(c);
- index = str.lastIndexOf(c);
- index = str.lastIndexOf(c);
- index = str.lastIndexOf(c);
- index = str.lastIndexOf(c);
- index = str.lastIndexOf(c);
- index = str.lastIndexOf(c);
- index = str.lastIndexOf(c);
- index = str.lastIndexOf(c);
- }
- }
-
- /** lastIndexOf()* */
-
- public void testStringlastIndexOf1() {
- int index, pos = 36;
- String str = STATIC_STRING_02, str1 = "tom";
- for (int i = ITERATIONS - 1; i >= 0; i--) {
- index = str.lastIndexOf(str1, pos);
- index = str.lastIndexOf(str1, pos);
- index = str.lastIndexOf(str1, pos);
- index = str.lastIndexOf(str1, pos);
- index = str.lastIndexOf(str1, pos);
- index = str.lastIndexOf(str1, pos);
- index = str.lastIndexOf(str1, pos);
- index = str.lastIndexOf(str1, pos);
- index = str.lastIndexOf(str1, pos);
- index = str.lastIndexOf(str1, pos);
- }
- }
-
- /**
- * contains() to determine whether a string contains a substring
- */
-
- public void testStringcontains() {
- boolean result;
- String str = STATIC_STRING_02, str1 = "tomo";
- for (int i = ITERATIONS - 1; i >= 0; i--) {
- result = str.contains(str1);
- result = str.contains(str1);
- result = str.contains(str1);
- result = str.contains(str1);
- result = str.contains(str1);
- result = str.contains(str1);
- result = str.contains(str1);
- result = str.contains(str1);
- result = str.contains(str1);
- result = str.contains(str1);
- }
- }
-
- /** substring(int start) */
-
- public void testStringsubstring() {
- String rString;
- String str = STATIC_STRING_02;
- int index = 10;
- for (int i = ITERATIONS - 1; i >= 0; i--) {
- rString = str.substring(index);
- rString = str.substring(index);
- rString = str.substring(index);
- rString = str.substring(index);
- rString = str.substring(index);
- rString = str.substring(index);
- rString = str.substring(index);
- rString = str.substring(index);
- rString = str.substring(index);
- rString = str.substring(index);
- }
- }
-
- /** substring(int start, int end) in a for loop* */
-
- public void testStringsubstring1() {
- String rString;
- String str = STATIC_STRING_02;
- int start = 10, end = 48;
- for (int i = ITERATIONS - 1; i >= 0; i--) {
- rString = str.substring(start, end);
- rString = str.substring(start, end);
- rString = str.substring(start, end);
- rString = str.substring(start, end);
- rString = str.substring(start, end);
- rString = str.substring(start, end);
- rString = str.substring(start, end);
- rString = str.substring(start, end);
- rString = str.substring(start, end);
- rString = str.substring(start, end);
- }
- }
-
- /**
- * valueOf(char[] cArray) String representation of a character array
- */
- public void testStringvalueOf() {
- String rString;
- char[] cArray = STATIC_CHAR_ARRAY;
- for (int i = ITERATIONS - 1; i >= 0; i--) {
- rString = String.valueOf(cArray);
- rString = String.valueOf(cArray);
- rString = String.valueOf(cArray);
- rString = String.valueOf(cArray);
- rString = String.valueOf(cArray);
- rString = String.valueOf(cArray);
- rString = String.valueOf(cArray);
- rString = String.valueOf(cArray);
- rString = String.valueOf(cArray);
- rString = String.valueOf(cArray);
- }
- }
-
- /** valueOf(char[] cArray, int offset, int count)* */
-
- public void testStringvalueOf1() {
- String rString;
- char[] cArray = STATIC_CHAR_ARRAY;
- int start = 1, end = 7;
- for (int i = ITERATIONS - 1; i >= 0; i--) {
- rString = String.valueOf(cArray, start, end);
- rString = String.valueOf(cArray, start, end);
- rString = String.valueOf(cArray, start, end);
- rString = String.valueOf(cArray, start, end);
- rString = String.valueOf(cArray, start, end);
- rString = String.valueOf(cArray, start, end);
- rString = String.valueOf(cArray, start, end);
- rString = String.valueOf(cArray, start, end);
- rString = String.valueOf(cArray, start, end);
- rString = String.valueOf(cArray, start, end);
- }
- }
-
- /** Convert a string to a char Array* */
-
- public void testStringtoCharArray() {
- char[] cArray;
- String str = STATIC_STRING_02;
- for (int i = ITERATIONS - 1; i >= 0; i--) {
- cArray = str.toCharArray();
- cArray = str.toCharArray();
- cArray = str.toCharArray();
- cArray = str.toCharArray();
- cArray = str.toCharArray();
- cArray = str.toCharArray();
- cArray = str.toCharArray();
- cArray = str.toCharArray();
- cArray = str.toCharArray();
- cArray = str.toCharArray();
- }
- }
-
- /** length()* */
-
- public void testStringlength() {
- int len;
- String str = STATIC_STRING_02;
- for (int i = ITERATIONS - 1; i >= 0; i--) {
- len = str.length();
- len = str.length();
- len = str.length();
- len = str.length();
- len = str.length();
- len = str.length();
- len = str.length();
- len = str.length();
- len = str.length();
- len = str.length();
- }
- }
-
- /** hashcode()* */
-
- public void testStringhashCode() {
- int index;
- String str = STATIC_STRING_02;
- for (int i = ITERATIONS - 1; i >= 0; i--) {
- index = str.hashCode();
- index = str.hashCode();
- index = str.hashCode();
- index = str.hashCode();
- index = str.hashCode();
- index = str.hashCode();
- index = str.hashCode();
- index = str.hashCode();
- index = str.hashCode();
- index = str.hashCode();
- }
- }
-
- /** replace()* */
-
- public void testStringreplace() {
- String rString;
- String str = STATIC_STRING_02;
- char c1 = ' ', c2 = ' ';
- for (int i = ITERATIONS - 1; i >= 0; i--) {
- rString = str.replace(c1, c2);
- rString = str.replace(c1, c2);
- rString = str.replace(c1, c2);
- rString = str.replace(c1, c2);
- rString = str.replace(c1, c2);
- rString = str.replace(c1, c2);
- rString = str.replace(c1, c2);
- rString = str.replace(c1, c2);
- rString = str.replace(c1, c2);
- rString = str.replace(c1, c2);
- }
- }
-
- public void testStringreplaceAll() {
- String rString;
- String str = STATIC_STRING_02, str1 = " ", str2 = "/";
- for (int i = ITERATIONS - 1; i >= 0; i--) {
- rString = str.replaceAll(str1, str2);
- rString = str.replaceAll(str1, str2);
- rString = str.replaceAll(str1, str2);
- rString = str.replaceAll(str1, str2);
- rString = str.replaceAll(str1, str2);
- rString = str.replaceAll(str1, str2);
- rString = str.replaceAll(str1, str2);
- rString = str.replaceAll(str1, str2);
- rString = str.replaceAll(str1, str2);
- rString = str.replaceAll(str1, str2);
- }
- }
-
- /** Convert a StringBuffer to a String* */
-
- public void testStringtoString() {
- StringBuffer sBuf = new StringBuffer(STATIC_STRING_02);
-
- String rString;
- for (int i = ITERATIONS - 1; i >= 0; i--) {
- rString = sBuf.toString();
- rString = sBuf.toString();
- rString = sBuf.toString();
- rString = sBuf.toString();
- rString = sBuf.toString();
- rString = sBuf.toString();
- rString = sBuf.toString();
- rString = sBuf.toString();
- rString = sBuf.toString();
- rString = sBuf.toString();
- }
- }
-
- /** Split a string into an array of strings* */
-
- public void testStringsplit() {
- String[] strings;
- String str1 = STATIC_STRING_02, str = " ";
- for (int i = ITERATIONS - 1; i >= 0; i--) {
- strings = str1.split(str);
- strings = str1.split(str);
- strings = str1.split(str);
- strings = str1.split(str);
- strings = str1.split(str);
- strings = str1.split(str);
- strings = str1.split(str);
- strings = str1.split(str);
- strings = str1.split(str);
- strings = str1.split(str);
-
- }
- }
-
- /** Split a string into an array of strings* */
-
- public void testStringsplit1() {
- String str = STATIC_STRING_02, str1 = " ";
- String[] strings;
- int pos = 8;
- for (int i = ITERATIONS - 1; i >= 0; i--) {
- strings = str.split(str1, pos);
- strings = str.split(str1, pos);
- strings = str.split(str1, pos);
- strings = str.split(str1, pos);
- strings = str.split(str1, pos);
- strings = str.split(str1, pos);
- strings = str.split(str1, pos);
- strings = str.split(str1, pos);
- strings = str.split(str1, pos);
- strings = str.split(str1, pos);
- }
- }
-
- public void testStringgetBytes() {
- byte[] bytes;
- String str = STATIC_STRING_02;
- for (int i = ITERATIONS - 1; i >= 0; i--) {
- bytes = str.getBytes();
- bytes = str.getBytes();
- bytes = str.getBytes();
- bytes = str.getBytes();
- bytes = str.getBytes();
- bytes = str.getBytes();
- bytes = str.getBytes();
- bytes = str.getBytes();
- bytes = str.getBytes();
- bytes = str.getBytes();
- }
- }
-
- /** copyValueOf(char[] data) * */
-
- public void testStringcopyValueOf() {
- String rString;
- char[] cArray = STATIC_CHAR_ARRAY;
- for (int i = ITERATIONS - 1; i >= 0; i--) {
- rString = String.copyValueOf(cArray);
- rString = String.copyValueOf(cArray);
- rString = String.copyValueOf(cArray);
- rString = String.copyValueOf(cArray);
- rString = String.copyValueOf(cArray);
- rString = String.copyValueOf(cArray);
- rString = String.copyValueOf(cArray);
- rString = String.copyValueOf(cArray);
- rString = String.copyValueOf(cArray);
- rString = String.copyValueOf(cArray);
- }
- }
-
- /** copyValueOf(char[] data, int index, int count)* */
-
- public void testStringcopyValueOf1() {
- String rString;
- int start = 1, end = 7;
- char[] cArray = STATIC_CHAR_ARRAY;
- for (int i = ITERATIONS - 1; i >= 0; i--) {
- rString = String.copyValueOf(cArray, start, end);
- rString = String.copyValueOf(cArray, start, end);
- rString = String.copyValueOf(cArray, start, end);
- rString = String.copyValueOf(cArray, start, end);
- rString = String.copyValueOf(cArray, start, end);
- rString = String.copyValueOf(cArray, start, end);
- rString = String.copyValueOf(cArray, start, end);
- rString = String.copyValueOf(cArray, start, end);
- rString = String.copyValueOf(cArray, start, end);
- rString = String.copyValueOf(cArray, start, end);
- }
- }
-
- /** trim()* */
-
- public void testStringtrim() {
- String mString =
- new String(
- " HELLO ANDROID ");
- String rString;
- for (int i = ITERATIONS - 1; i >= 0; i--) {
- rString = mString.trim();
- rString = mString.trim();
- rString = mString.trim();
- rString = mString.trim();
- rString = mString.trim();
- rString = mString.trim();
- rString = mString.trim();
- rString = mString.trim();
- rString = mString.trim();
- rString = mString.trim();
- }
- }
-
- /** getChars(int srcBegin, int srcEnd, char[] dst, int dstBegin)* */
-
- public void testStringgetChars() {
- char[] cArray = STATIC_CHAR_ARRAY;
- String str = STATIC_STRING_01;
- int value1 = 7, value2 = 12, value3 = 1;
- for (int i = ITERATIONS - 1; i >= 0; i--) {
- str.getChars(value1, value2, cArray, value3);
- str.getChars(value1, value2, cArray, value3);
- str.getChars(value1, value2, cArray, value3);
- str.getChars(value1, value2, cArray, value3);
- str.getChars(value1, value2, cArray, value3);
- str.getChars(value1, value2, cArray, value3);
- str.getChars(value1, value2, cArray, value3);
- str.getChars(value1, value2, cArray, value3);
- str.getChars(value1, value2, cArray, value3);
- str.getChars(value1, value2, cArray, value3);
- }
- }
-
- /** toUpperCase()* */
-
- public void testStringtoUpperCase() {
- String rString, str = STATIC_STRING_02;
- for (int i = ITERATIONS - 1; i >= 0; i--) {
- rString = str.toUpperCase();
- rString = str.toUpperCase();
- rString = str.toUpperCase();
- rString = str.toUpperCase();
- rString = str.toUpperCase();
- rString = str.toUpperCase();
- rString = str.toUpperCase();
- rString = str.toUpperCase();
- rString = str.toUpperCase();
- rString = str.toUpperCase();
- }
- }
-
- /** toUpperCase() with locale* */
-
- public void testStringtoUpperCase1() {
- Locale locale = new Locale("tr");
- String str = STATIC_STRING_02;
- String rString;
- for (int i = ITERATIONS - 1; i >= 0; i--) {
- rString = str.toUpperCase(locale);
- rString = str.toUpperCase(locale);
- rString = str.toUpperCase(locale);
- rString = str.toUpperCase(locale);
- rString = str.toUpperCase(locale);
- rString = str.toUpperCase(locale);
- rString = str.toUpperCase(locale);
- rString = str.toUpperCase(locale);
- rString = str.toUpperCase(locale);
- rString = str.toUpperCase(locale);
- }
- }
-
- /** toLowerCase* */
-
- public void StringtoLowerCase() {
- String rString, str = STATIC_STRING_02;
- for (int i = ITERATIONS - 1; i >= 0; i--) {
- rString = str.toLowerCase();
- rString = str.toLowerCase();
- rString = str.toLowerCase();
- rString = str.toLowerCase();
- rString = str.toLowerCase();
- rString = str.toLowerCase();
- rString = str.toLowerCase();
- rString = str.toLowerCase();
- rString = str.toLowerCase();
- rString = str.toLowerCase();
- }
- }
-
- /** toLowerCase with locale* */
-
- public void testStringtoLowerCase1() {
- Locale locale = new Locale("tr");
- String rString, str = STATIC_STRING_02;
- for (int i = ITERATIONS - 1; i >= 0; i--) {
- rString = str.toLowerCase(locale);
- rString = str.toLowerCase(locale);
- rString = str.toLowerCase(locale);
- rString = str.toLowerCase(locale);
- rString = str.toLowerCase(locale);
- rString = str.toLowerCase(locale);
- rString = str.toLowerCase(locale);
- rString = str.toLowerCase(locale);
- rString = str.toLowerCase(locale);
- rString = str.toLowerCase(locale);
- }
- }
-
- /** charAt()* */
-
- public void testStringcharAt() {
- String str = STATIC_STRING_02;
- int index, pos = 21;
- for (int i = ITERATIONS - 1; i >= 0; i--) {
- index = str.charAt(pos);
- index = str.charAt(pos);
- index = str.charAt(pos);
- index = str.charAt(pos);
- index = str.charAt(pos);
- index = str.charAt(pos);
- index = str.charAt(pos);
- index = str.charAt(pos);
- index = str.charAt(pos);
- index = str.charAt(pos);
- }
- }
-
- public void testStringConcat() {
- String mString, str1 = STATIC_STRING_01, str2 = STATIC_STRING_02;
- for (int i = ITERATIONS - 1; i >= 0; i--) {
- mString = str1.concat(str2);
- mString = str1.concat(str2);
- mString = str1.concat(str2);
- mString = str1.concat(str2);
- mString = str1.concat(str2);
- mString = str1.concat(str2);
- mString = str1.concat(str2);
- mString = str1.concat(str2);
- mString = str1.concat(str2);
- mString = str1.concat(str2);
- }
- }
-
- public void testStringBufferAppend() {
- StringBuffer sBuf = new StringBuffer(" ");
- for (int i = ITERATIONS - 1; i >= 0; i--) {
- sBuf.append(i);
- sBuf.append(i);
- sBuf.append(i);
- sBuf.append(i);
- sBuf.append(i);
- sBuf.append(i);
- sBuf.append(i);
- sBuf.append(i);
- sBuf.append(i);
- sBuf.append(i);
- }
- }
-
- public void testStringBufferInsert() {
- StringBuffer sBuf = new StringBuffer(" ");
- int index = sBuf.length();
- for (int i = ITERATIONS - 1; i >= 0; i--) {
- sBuf.insert(index, i);
- sBuf.insert(index, i);
- sBuf.insert(index, i);
- sBuf.insert(index, i);
- sBuf.insert(index, i);
- sBuf.insert(index, i);
- sBuf.insert(index, i);
- sBuf.insert(index, i);
- sBuf.insert(index, i);
- sBuf.insert(index, i);
- }
- }
-
- public void testStringBufferReverse() {
- StringBuffer sBuf = STATIC_SBUF;
- for (int i = ITERATIONS - 1; i >= 0; i--) {
- sBuf.reverse();
- sBuf.reverse();
- sBuf.reverse();
- sBuf.reverse();
- sBuf.reverse();
- sBuf.reverse();
- sBuf.reverse();
- sBuf.reverse();
- sBuf.reverse();
- sBuf.reverse();
- }
- }
-
- public void testStringBufferSubstring() {
- StringBuffer sBuf = STATIC_SBUF;
- String rString;
- int index = 0;
- for (int i = ITERATIONS - 1; i >= 0; i--) {
- rString = sBuf.substring(index);
- rString = sBuf.substring(index);
- rString = sBuf.substring(index);
- rString = sBuf.substring(index);
- rString = sBuf.substring(index);
- rString = sBuf.substring(index);
- rString = sBuf.substring(index);
- rString = sBuf.substring(index);
- rString = sBuf.substring(index);
- rString = sBuf.substring(index);
- }
- }
-
- public void testStringBufferSubstring1() {
- StringBuffer sBuf = STATIC_SBUF;
- String rString;
- int start = 5, end = 25;
- for (int i = ITERATIONS - 1; i >= 0; i--) {
- rString = sBuf.substring(start, end);
- rString = sBuf.substring(start, end);
- rString = sBuf.substring(start, end);
- rString = sBuf.substring(start, end);
- rString = sBuf.substring(start, end);
- rString = sBuf.substring(start, end);
- rString = sBuf.substring(start, end);
- rString = sBuf.substring(start, end);
- rString = sBuf.substring(start, end);
- rString = sBuf.substring(start, end);
- }
- }
-
- public void testStringBufferReplace() {
- StringBuffer sBuf = STATIC_SBUF;
- int start = 3, end = 6;
- String str = "ind";
- for (int i = ITERATIONS - 1; i >= 0; i--) {
- sBuf.replace(start, end, str);
- sBuf.replace(start, end, str);
- sBuf.replace(start, end, str);
- sBuf.replace(start, end, str);
- sBuf.replace(start, end, str);
- sBuf.replace(start, end, str);
- sBuf.replace(start, end, str);
- sBuf.replace(start, end, str);
- sBuf.replace(start, end, str);
- sBuf.replace(start, end, str);
- }
- }
-
- public void testStringBufferIndexOf() {
- StringBuffer sBuf = STATIC_SBUF;
- String str = "t";
- int index;
- for (int i = ITERATIONS - 1; i >= 0; i--) {
- index = sBuf.indexOf(str);
- index = sBuf.indexOf(str);
- index = sBuf.indexOf(str);
- index = sBuf.indexOf(str);
- index = sBuf.indexOf(str);
- index = sBuf.indexOf(str);
- index = sBuf.indexOf(str);
- index = sBuf.indexOf(str);
- index = sBuf.indexOf(str);
- index = sBuf.indexOf(str);
- }
- }
-
- public void testStringBufferIndexOf1() {
- StringBuffer sBuf = STATIC_SBUF;
- String str = "tom";
- int index, pos = 12;
- for (int i = ITERATIONS - 1; i >= 0; i--) {
- index = sBuf.indexOf(str, pos);
- index = sBuf.indexOf(str, pos);
- index = sBuf.indexOf(str, pos);
- index = sBuf.indexOf(str, pos);
- index = sBuf.indexOf(str, pos);
- index = sBuf.indexOf(str, pos);
- index = sBuf.indexOf(str, pos);
- index = sBuf.indexOf(str, pos);
- index = sBuf.indexOf(str, pos);
- index = sBuf.indexOf(str, pos);
- }
-
- }
-
- public void testStringBufferLastIndexOf() {
- StringBuffer sBuf = STATIC_SBUF;
- String str = "t";
- int index;
- for (int i = ITERATIONS - 1; i >= 0; i--) {
- index = sBuf.lastIndexOf(str);
- index = sBuf.lastIndexOf(str);
- index = sBuf.lastIndexOf(str);
- index = sBuf.lastIndexOf(str);
- index = sBuf.lastIndexOf(str);
- index = sBuf.lastIndexOf(str);
- index = sBuf.lastIndexOf(str);
- index = sBuf.lastIndexOf(str);
- index = sBuf.lastIndexOf(str);
- index = sBuf.lastIndexOf(str);
- }
- }
-
- public void testStringBufferLastIndexOf1() {
- StringBuffer sBuf = STATIC_SBUF;
- int index, pos = 36;
- String str = "tom";
- for (int i = ITERATIONS - 1; i >= 0; i--) {
- index = sBuf.lastIndexOf(str, pos);
- index = sBuf.lastIndexOf(str, pos);
- index = sBuf.lastIndexOf(str, pos);
- index = sBuf.lastIndexOf(str, pos);
- index = sBuf.lastIndexOf(str, pos);
- index = sBuf.lastIndexOf(str, pos);
- index = sBuf.lastIndexOf(str, pos);
- index = sBuf.lastIndexOf(str, pos);
- index = sBuf.lastIndexOf(str, pos);
- index = sBuf.lastIndexOf(str, pos);
- }
- }
-}
diff --git a/tools/aapt/Android.mk b/tools/aapt/Android.mk
index b339a2c..094b7db 100644
--- a/tools/aapt/Android.mk
+++ b/tools/aapt/Android.mk
@@ -41,7 +41,7 @@
libpng
ifeq ($(HOST_OS),linux)
-LOCAL_LDLIBS += -lrt
+LOCAL_LDLIBS += -lrt -lpthread
endif
# Statically link libz for MinGW (Win SDK under Linux),
diff --git a/tools/aapt/Command.cpp b/tools/aapt/Command.cpp
index 35124aa..b0f086b 100644
--- a/tools/aapt/Command.cpp
+++ b/tools/aapt/Command.cpp
@@ -141,9 +141,9 @@
if (bundle->getVerbose()) {
printf("Archive: %s\n", zipFileName);
printf(
- " Length Method Size Ratio Date Time CRC-32 Name\n");
+ " Length Method Size Ratio Offset Date Time CRC-32 Name\n");
printf(
- "-------- ------ ------- ----- ---- ---- ------ ----\n");
+ "-------- ------ ------- ----- ------- ---- ---- ------ ----\n");
}
totalUncLen = totalCompLen = 0;
@@ -159,12 +159,13 @@
strftime(dateBuf, sizeof(dateBuf), "%m-%d-%y %H:%M",
localtime(&when));
- printf("%8ld %-7.7s %7ld %3d%% %s %08lx %s\n",
+ printf("%8ld %-7.7s %7ld %3d%% %8zd %s %08lx %s\n",
(long) entry->getUncompressedLen(),
compressionName(entry->getCompressionMethod()),
(long) entry->getCompressedLen(),
calcPercent(entry->getUncompressedLen(),
entry->getCompressedLen()),
+ (size_t) entry->getLFHOffset(),
dateBuf,
entry->getCRC32(),
entry->getFileName());
diff --git a/tools/aapt/ZipEntry.h b/tools/aapt/ZipEntry.h
index 7f721b4..c2f3227 100644
--- a/tools/aapt/ZipEntry.h
+++ b/tools/aapt/ZipEntry.h
@@ -72,6 +72,11 @@
off_t getCompressedLen(void) const { return mCDE.mCompressedSize; }
/*
+ * Return the offset of the local file header.
+ */
+ off_t getLFHOffset(void) const { return mCDE.mLocalHeaderRelOffset; }
+
+ /*
* Return the absolute file offset of the start of the compressed or
* uncompressed data.
*/
@@ -186,11 +191,6 @@
void setModWhen(time_t when);
/*
- * Return the offset of the local file header.
- */
- off_t getLFHOffset(void) const { return mCDE.mLocalHeaderRelOffset; }
-
- /*
* Set the offset of the local file header, relative to the start of
* the current file.
*/
diff --git a/tools/localize/Android.mk b/tools/localize/Android.mk
index ab79f8d..f284e86 100644
--- a/tools/localize/Android.mk
+++ b/tools/localize/Android.mk
@@ -34,7 +34,7 @@
libcutils
ifeq ($(HOST_OS),linux)
-LOCAL_LDLIBS += -lrt
+LOCAL_LDLIBS += -lrt -lpthread
endif
diff --git a/voip/java/android/net/sip/SipAudioCall.java b/voip/java/android/net/sip/SipAudioCall.java
index f4be839..3cdd114 100644
--- a/voip/java/android/net/sip/SipAudioCall.java
+++ b/voip/java/android/net/sip/SipAudioCall.java
@@ -244,7 +244,8 @@
* Also, the {@code AudioStream} may change its group during a call (e.g.,
* after the call is held/un-held). Finally, the {@code AudioGroup} object
* returned by this method is undefined after the call ends or the
- * {@link #close} method is called.
+ * {@link #close} method is called. If a group object is set by
+ * {@link #setAudioGroup(AudioGroup)}, then this method returns that object.
*
* @return the {@link AudioGroup} object or null if the RTP stream has not
* yet been set up
@@ -253,6 +254,15 @@
AudioGroup getAudioGroup();
/**
+ * Sets the {@link AudioGroup} object which the {@link AudioStream} object
+ * joins. If {@code audioGroup} is null, then the {@code AudioGroup} object
+ * will be dynamically created when needed.
+ *
+ * @see #getAudioStream
+ */
+ void setAudioGroup(AudioGroup audioGroup);
+
+ /**
* Checks if the call is established.
*
* @return true if the call is established
diff --git a/voip/java/android/net/sip/SipAudioCallImpl.java b/voip/java/android/net/sip/SipAudioCallImpl.java
index 7161309..b8ac6d7 100644
--- a/voip/java/android/net/sip/SipAudioCallImpl.java
+++ b/voip/java/android/net/sip/SipAudioCallImpl.java
@@ -70,7 +70,8 @@
private ISipSession mSipSession;
private SdpSessionDescription mPeerSd;
- private AudioStream mRtpSession;
+ private AudioStream mAudioStream;
+ private AudioGroup mAudioGroup;
private SdpSessionDescription.AudioCodec mCodec;
private long mSessionId = -1L; // SDP session ID
private boolean mInCall = false;
@@ -505,11 +506,19 @@
}
public synchronized AudioStream getAudioStream() {
- return mRtpSession;
+ return mAudioStream;
}
public synchronized AudioGroup getAudioGroup() {
- return ((mRtpSession == null) ? null : mRtpSession.getAudioGroup());
+ if (mAudioGroup != null) return mAudioGroup;
+ return ((mAudioStream == null) ? null : mAudioStream.getAudioGroup());
+ }
+
+ public synchronized void setAudioGroup(AudioGroup group) {
+ if ((mAudioStream != null) && (mAudioStream.getAudioGroup() != null)) {
+ mAudioStream.join(group);
+ }
+ mAudioGroup = group;
}
private SdpSessionDescription.AudioCodec getCodec(SdpSessionDescription sd) {
@@ -561,7 +570,7 @@
// TODO: get sample rate from sdp
mCodec = getCodec(peerSd);
- AudioStream audioStream = mRtpSession;
+ AudioStream audioStream = mAudioStream;
audioStream.associate(InetAddress.getByName(peerMediaAddress),
peerMediaPort);
audioStream.setCodec(convert(mCodec), mCodec.payloadType);
@@ -580,7 +589,7 @@
Log.d(TAG, " not sending");
audioStream.setMode(RtpStream.MODE_RECEIVE_ONLY);
}
- } else {
+
/* The recorder volume will be very low if the device is in
* IN_CALL mode. Therefore, we have to set the mode to NORMAL
* in order to have the normal microphone level.
@@ -590,14 +599,22 @@
.setMode(AudioManager.MODE_NORMAL);
}
- AudioGroup audioGroup = new AudioGroup();
- audioStream.join(audioGroup);
+ // AudioGroup logic:
+ AudioGroup audioGroup = getAudioGroup();
if (mHold) {
- audioGroup.setMode(AudioGroup.MODE_ON_HOLD);
- } else if (mMuted) {
- audioGroup.setMode(AudioGroup.MODE_MUTED);
+ if (audioGroup != null) {
+ audioGroup.setMode(AudioGroup.MODE_ON_HOLD);
+ }
+ // don't create an AudioGroup here; doing so will fail if
+ // there's another AudioGroup out there that's active
} else {
- audioGroup.setMode(AudioGroup.MODE_NORMAL);
+ if (audioGroup == null) audioGroup = new AudioGroup();
+ audioStream.join(audioGroup);
+ if (mMuted) {
+ audioGroup.setMode(AudioGroup.MODE_MUTED);
+ } else {
+ audioGroup.setMode(AudioGroup.MODE_NORMAL);
+ }
}
} catch (Exception e) {
Log.e(TAG, "call()", e);
@@ -606,20 +623,20 @@
private void stopCall(boolean releaseSocket) {
Log.d(TAG, "stop audiocall");
- if (mRtpSession != null) {
- mRtpSession.join(null);
+ if (mAudioStream != null) {
+ mAudioStream.join(null);
if (releaseSocket) {
- mRtpSession.release();
- mRtpSession = null;
+ mAudioStream.release();
+ mAudioStream = null;
}
}
}
private int getLocalMediaPort() {
- if (mRtpSession != null) return mRtpSession.getLocalPort();
+ if (mAudioStream != null) return mAudioStream.getLocalPort();
try {
- AudioStream s = mRtpSession =
+ AudioStream s = mAudioStream =
new AudioStream(InetAddress.getByName(getLocalIp()));
return s.getLocalPort();
} catch (IOException e) {
diff --git a/voip/java/android/net/sip/SipProfile.java b/voip/java/android/net/sip/SipProfile.java
index e71c293..6c99141 100644
--- a/voip/java/android/net/sip/SipProfile.java
+++ b/voip/java/android/net/sip/SipProfile.java
@@ -35,7 +35,7 @@
* Class containing a SIP account, domain and server information.
* @hide
*/
-public class SipProfile implements Parcelable, Serializable {
+public class SipProfile implements Parcelable, Serializable, Cloneable {
private static final long serialVersionUID = 1L;
private static final int DEFAULT_PORT = 5060;
private Address mAddress;
@@ -46,6 +46,8 @@
private String mProfileName;
private boolean mSendKeepAlive = false;
private boolean mAutoRegistration = true;
+ private boolean mAllowOutgoingCall = false;
+ private int mCallingUid = -1;
/** @hide */
public static final Parcelable.Creator<SipProfile> CREATOR =
@@ -79,6 +81,23 @@
}
/**
+ * Creates a builder based on the given profile.
+ */
+ public Builder(SipProfile profile) {
+ if (profile == null) throw new NullPointerException();
+ try {
+ mProfile = (SipProfile) profile.clone();
+ } catch (CloneNotSupportedException e) {
+ throw new RuntimeException("should not occur", e);
+ }
+ mProfile.mAddress = null;
+ mUri = profile.getUri();
+ mUri.setUserPassword(profile.getPassword());
+ mDisplayName = profile.getDisplayName();
+ mProxyAddress = profile.getProxyAddress();
+ }
+
+ /**
* Constructor.
*
* @param uriString the URI string as "sip:<user_name>@<domain>"
@@ -226,6 +245,18 @@
}
/**
+ * Sets the allow-outgoing-call flag.
+ *
+ * @param flag true if allowing to make outgoing call on the profile;
+ * false otherwise
+ * @return this builder object
+ */
+ public Builder setOutgoingCallAllowed(boolean flag) {
+ mProfile.mAllowOutgoingCall = flag;
+ return this;
+ }
+
+ /**
* Builds and returns the SIP profile object.
*
* @return the profile object created
@@ -262,6 +293,8 @@
mProfileName = in.readString();
mSendKeepAlive = (in.readInt() == 0) ? false : true;
mAutoRegistration = (in.readInt() == 0) ? false : true;
+ mAllowOutgoingCall = (in.readInt() == 0) ? false : true;
+ mCallingUid = in.readInt();
}
/** @hide */
@@ -274,6 +307,8 @@
out.writeString(mProfileName);
out.writeInt(mSendKeepAlive ? 1 : 0);
out.writeInt(mAutoRegistration ? 1 : 0);
+ out.writeInt(mAllowOutgoingCall ? 1 : 0);
+ out.writeInt(mCallingUid);
}
/** @hide */
@@ -398,4 +433,27 @@
public boolean getAutoRegistration() {
return mAutoRegistration;
}
+
+ /**
+ * Returns true if allowing to make outgoing calls on this profile.
+ */
+ public boolean isOutgoingCallAllowed() {
+ return mAllowOutgoingCall;
+ }
+
+ /**
+ * Sets the calling process's Uid in the sip service.
+ * @hide
+ */
+ public void setCallingUid(int uid) {
+ mCallingUid = uid;
+ }
+
+ /**
+ * Gets the calling process's Uid in the sip settings.
+ * @hide
+ */
+ public int getCallingUid() {
+ return mCallingUid;
+ }
}